Functions are reusable blocks of code designed to perform specific task. They help in:
- Code reusability: Avoid redundant code by calling functions multiple times.
- Modular programming: Break down a large program into smaller, manageable parts.
- Ease of debugging: Functions make code more readable and maintainable.
- Functions do not execute unless they are explicitly called.
JavaScript provides two main types of functions:
The functions which are provided by javascript itself is called as built in function.
Examples:
console.log(Math.random()); // Generates a random number between 0 and 1
console.log(Date.now()); // Returns the current timestamp in milliseconds since 1741862558007
console.log(parseInt("42")); // Converts a string to an integerThe functions which has been created by developer to perform the operation is called as User defined function.
User-defined functions can be categorized based on parameters:
A function that accepts arguments while defining and calling.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: "Hello, Alice!"
console.log(greet("Bob")); // Output: "Hello, Bob!"A function that does not accept any arguments.
function greet() {
return "Hello, World!";
}
console.log(greet()); // Output: "Hello, World!"- Named function, hoisted.
- Can be called before its definition.
Example:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: "Hello, Alice!"- Can be named or anonymous.
- Not hoisted, meaning it cannot be called before its declaration.
Example:
const greet2 = function(name) {
return `Hello, ${name}!`;
};
console.log(greet2("Bob")); // Output: "Hello, Bob!"- Provides a shorter syntax for defining functions.
- Does not have its own
this. - Not hoisted.
Example:
const greet1 = (name) => `Hello, ${name}!`;
console.log(greet1("Charlie")); // Output: "Hello, Charlie!"- Functions without names, often used as callbacks.
Example:
setTimeout(function() {
console.log("This is an anonymous function!");
}, 2000);- A function passed as an argument to another function and executed later.
Example:
function greeting(name, callback) {
console.log(`Hello, ${name}`);
callback();
}
greeting("Buddy", () => {
console.log(`Callback executed`);
});- Executes immediately after creation.
- Anonymous function.
Example:
(() => {
console.log(`IIFE function`);
})();- Provides default values for parameters to prevent errors.
Example:
function add(a, b, c = 10) {
return a + b + c;
}
console.log(add(10, 12)); // Output: 32
console.log(add(10, 12, 5)); // Output: 27- A closure is a bundle of function its bind together with its lexical environment
- It allows maintaining private variables and encapsulation.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
};
}
const closureExample = outerFunction("Hello");
closureExample("World"); // Output: Outer: Hello, Inner: World- Normal Function:
function functionName() { ... } - Arrow Function:
() => { ... }
- Normal Function: Supports
thisand refers to the current object. - Arrow Function: Does not have its own
this.
Example:
let emp = {
empId: 123,
empName: "Buddy",
yoe: 2,
skills: ["Angular", "Java", "Python", "C++"],
getBasicDetails: function() {
return `Using normal function with empID ${this.empId} and name is ${this.empName}`;
},
getTechnicalDetails: () => {
return `Using arrow function: yoe ${this.yoe}`;
}
};
console.log(emp.getBasicDetails()); // Works fine
console.log(emp.getTechnicalDetails()); // Undefined due to arrow function- Normal Function: Has access to
arguments. - Arrow Function: Does not have an
argumentsobject.
Example:
function getData(a, b) {
console.log(arguments);
}
getData(10, 12);- Normal Function: Requires
returnfor output. - Arrow Function: Requires
returnonly if the function body has more than one line.
- Normal Function: Function declarations are hoisted.
- Arrow Function: Not hoisted.
- In the global scope,
thisrefers to the global object (windowin browsers,globalin Node.js).
Example:
console.log(this); // In browser: window object- In strict mode,
thisisundefinedin global functions.
Example:
'use strict';
function strictFunc() {
console.log(this); // Output: undefined
}
strictFunc();- When used in an object method,
thisrefers to the object itself.
Example:
const person = {
name: "Vishnu",
greet: function() {
console.log(`Hello, ${this.name}`);
}
};
person.greet(); // Output: Hello, Vishnu- In event handlers,
thisrefers to the element that triggered the event.
Example:
document.querySelector("button").addEventListener("click", function() {
console.log(this); // Output: Button element
});