Functions in JavaScript
Introduction: Link to heading
Functions are reusable blocks of code that perform a specific task. They are an essential tool for writing efficient and organized JavaScript code.
Types of functions Link to heading
- Declaratives: They are defined using the
function
keyword. - Expression: They are defined as an expression that is assigned to a variable.
Examples Link to heading
Declaratives: Link to heading
// Function declaration
function myFunction() {
// Function code
return 3;
}
// Function call
myFunction();
Expression: Link to heading
// Declaration of the function as an expression
var myFunction = function(a, b) {
// Function code
return a + b;
};
// Function call
myFunction(1, 2);
Getting results Link to heading
- Browser Console:
console.log()
can be used to print the value of a variable or expression to the browser console. - Return: The function can return a value using the
return
keyword.
Examples Link to heading
Browser console Link to heading
function greetStudents(student) {
console.log(student);
}
greetStudents("John"); // Print "John" to the console
Return: Link to heading
function add(a, b) {
var result = a + b;
return result;
}
var sum = add(1, 2); // The variable `sum` stores the result of the function, which is 3
More examples: Link to heading
// Function that calculates the area of a square
function squareArea(side) {
return side \* side;
}
var area = squareArea(5); // The variable `area` stores the area of the square, which is 25
// Function that checks if a number is even
function isEven(number) {
return number % 2 === 0;
}
var isEven = isEven(10); // The variable `isEven` stores `true` because 10 is an even number
// Function that greets a user
function greetUser(name) {
return `Hello ${name}, how are you?`;
}
var greeting = greetUser("Diego"); // The variable `greeting` stores the message "Hello Diego, how are you?"
Tips for using functions: Link to heading
- Use descriptive names for functions.
- Break your code into small, manageable functions.
- Document your features with comments.
- Reuse functions whenever possible.
Keep learning about functions in JavaScript to improve your programming skills!
Take advantage of understanding functions to write more modular and effective JavaScript code!