function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Output: 5
Explanation: This is the classic way to define a function. It can be called before it appears in the code (hoisted).
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(2, 3)); // Output: 6
Explanation: The function is stored in a variable. It is not hoisted, so it must be defined before use.
const divide = function divideFunc(a, b) {
return a / b;
};
console.log(divide(6, 2)); // Output: 3
Explanation: Similar to a function expression, but the function has its own name (useful for recursion or debugging).
const subtract = (a, b) => a - b;
console.log(subtract(5, 2)); // Output: 3
Explanation: Shorter syntax, does not have its own this context.
const square = x => x * x;
console.log(square(4)); // Output: 16
Explanation: Parentheses can be omitted if there is only one parameter.
const calculator = {
sum: function(a, b) {
return a + b;
}
};
console.log(calculator.sum(3, 4)); // Output: 7
Explanation: Functions can be properties (methods) of objects.
const math = {
multiply(a, b) {
return a * b;
}
};
console.log(math.multiply(3, 5)); // Output: 15
Explanation: ES6 allows a shorter way to define methods in objects.
function Person(name) {
this.name = name;
}
const person1 = new Person('Alice');
console.log(person1.name); // Output: Alice
Explanation: Used to create objects with the new keyword.
(function() {
console.log('IIFE runs immediately!');
})();
Explanation: Runs as soon as it is defined. Useful for creating a private scope.