A function is a block of reusable code designed to perform a particular task. A function is executed when "something" invokes it (calls it). Functions help in reducing code redundancy and making the code modular.
A function declaration defines a named function. These are hoisted, meaning they can be called before they are defined.
function functionName(parameters) {
// code to be executed
}
function add(a, b) {
return a + b;
}
console.log(add(5, 10)); // 15
A function expression defines a function inside a variable. These are not hoisted.
const functionName = function(parameters) {
// code to be executed
};
const multiply = function(x, y) {
return x * y;
};
document.write(multiply(4, 5)); // 20
Arrow functions provide a shorter syntax for writing function expressions. They do not have their own
this context.
const functionName = (parameters) => {
// code to be executed
};
const subtract = (a, b) => a - b;
// One-liner (implicit return)
const square = n => n * n;
document.write(subtract(10, 3)); // 7
document.write(square(6)); // 36
Parameters are variables listed in the function definition.
Arguments are values passed to the function when it is invoked.
The return statement stops the execution of a function and returns a value to the caller.
function greet(name = "Guest") { // Default parameter
return "Welcome, " + name;
}
document.write(greet("Ragini")); // "Welcome, Ragini"
document.write(greet()); // "Welcome, Guest"
An IIFE is a function that runs as soon as it is defined. It is often used to create a private scope.
(function() {
let secret = "I am hidden";
document.write("IIFE executed immediately!");
})();
| Type | Syntax | Hoisted? | 'this' Binding |
|---|---|---|---|
| Declaration | function foo() {} |
Yes | Dynamic |
| Expression | const foo = function() {} |
No | Dynamic |
| Arrow | const foo = () => {} |
No | Lexical (Inherited) |
Test your understanding of JavaScript Functions.
multiply.a and b).Convert the following function declaration into an ES6 arrow function:
function isEven(num) {
return num % 2 === 0;
}
power.base and exponent.exponent to 2.** operator).makeCounter that initializes a count to 0.count.count.