function functionName(parameters) {
// Code to be executed
}
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
const functionName = function(parameters) {
// Code to be executed
};
const greet = function(name) {
console.log("Hello, " + name + "!");
};
greet("Bob");
const functionName = (parameters) => {
// Code to be executed
};
const greet = (name) => {
console.log("Hello, " + name + "!");
};
greet("Charlie");
function greet(name = "Stranger") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Stranger!
return
statement. The function execution stops when the return
statement is reached.function add(a, b) {
return a + b;
}
const result = add(5, 3); // result = 8
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayGoodbye() {
console.log("Goodbye!");
}
greet("Alice", sayGoodbye); // Output: Hello, Alice \n Goodbye!
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
map()
method creates a new array by applying a function to each element of an array.const newArray = array.map(function(currentValue, index, arr), thisValue);
const numbers = [1, 2, 3, 4];
const squares = numbers.map(number => number * number);
console.log(squares); // [1, 4, 9, 16]
filter()
method creates a new array containing elements that pass a test provided by a function.const newArray = array.filter(function(currentValue, index, arr), thisValue);
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // [2, 4]
reduce()
method executes a reducer function on each element of the array, resulting in a single output value.const result = array.reduce(function(accumulator, currentValue, index, arr), initialValue);
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, number) => total + number, 0);
console.log(sum); // 10