Understanding and using functions in JavaScript
Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code that performs a specific task or calculates a value.
Here's how you can declare a function in JavaScript:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Outputs: Hello, Alice!
Functions can also be created using a function expression:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
greet("Bob"); // Outputs: Hello, Bob!
Arrow functions provide a more concise syntax for writing function expressions:
const greet = (name) => {
console.log("Hello, " + name + "!");
};
greet("Charlie"); // Outputs: Hello, Charlie!
Functions can take parameters and return values:
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Outputs: 8
You can specify default values for function parameters:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Outputs: 6
console.log(sum(4, 5, 6, 7)); // Outputs: 22
Variables declared inside a function are only accessible within that function:
function exampleFunction() {
let localVar = "I'm local";
console.log(localVar); // Outputs: I'm local
}
console.log(localVar); // Throws an error: localVar is not defined
Closures allow a function to access variables from an outer function even after the outer function has returned:
function outerFunction(x) {
return function(y) {
return x + y;
}
}
const addFive = outerFunction(5);
console.log(addFive(3)); // Outputs: 8