In JavaScript, a function is a reusable block of code that performs a specific task. You can define it once and execute (invoke) it whenever you need. Functions help you:
this context using call(), apply(), and bind().function keyword with a name.this.return.this and arguments are passed.Basic Declaration
A typical function declaration looks like this:
function greet(name) {
return "Hello, " + name + "!";
}
Parameters & Return
Functions can accept parameters (inputs) and return a value using the return keyword:
function add(a, b) {
return a + b;
}
let result = add(4, 6);
console.log(result);
// 10
Function Forms
JavaScript supports multiple ways to define functions:
this.Here are different ways to define and use functions in JavaScript:
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function expression
const greet2 = function(name) {
return "Hi, " + name + "!";
};
// Arrow function (ES6+)
const greet3 = (name) => "Hey, " + name + "!";
// Simple function example
function greetWorld() {
console.log("Hello, world!");
}
greetWorld();
Functions can accept parameters to work with dynamic data and can use default parameters.
function multiply(a, b) {
return a * b;
}
console.log(multiply(4, 5));
// 20
// Default parameters
function greet(name = "Guest") {
return "Welcome, " + name;
}
console.log(greet());
// Welcome, Guest
The methods call(), apply(), and bind() let you control the value of this inside a function.
function introduce(city) {
return this.name + " lives in " + city;
}
const person = { name: "Alice" };
// call() - arguments listed one by one
console.log(introduce.call(person, "Paris"));
// Alice lives in Paris
// apply() - arguments passed as an array
console.log(introduce.apply(person, ["London"]));
// Alice lives in London
// bind() - returns a new bound function
const boundIntroduce = introduce.bind(person);
console.log(boundIntroduce("New York"));
// Alice lives in New York
A closure is a function that remembers the environment in which it was created, even after that outer function has finished executing.
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const counter = outer();
console.log(counter());
console.log(counter());
console.log(counter());
// Function inside another function
function outerFn() {
function innerFn() {
console.log("Inner function");
}
innerFn();
}
outerFn();
// Function with a loop
function printNumbers(n) {
for (let i = 1; i <= n; i++) {
console.log(i);
}
}
printNumbers(5);
Arrow functions are concise, anonymous functions are often used as arguments, and callbacks are functions passed into other functions.
// Arrow functions
const square = (n) => n * n;
console.log(square(7));
// 49
const greetArrow = name => `Hello, ${name}!`;
console.log(greetArrow("Alice"));
// Hello, Alice!
// Anonymous function with setTimeout
setTimeout(function() {
console.log("This runs after 1 second");
}, 1000);
// Callback function example
function greetUser(name, callback) {
console.log("Hello, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greetUser("John", sayBye);
Function declarations are hoisted, so they can be called before they are defined. Function expressions are not hoisted.
// Function declaration hoisting
sayHello();
function sayHello() {
console.log("Hi!");
}
// Function expression is NOT hoisted
// sayBye(); // ❌ Error if uncommented
const sayBye = function() {
console.log("Bye!");
};
Consider this small program:
function add(a, b) {
return a + b;
}
function printSum(x, y) {
const total = add(x, y);
console.log("Sum is:", total);
}
printSum(3, 7);
Step-by-step:
add(a, b) adds two numbers and returns the result.printSum(x, y) calls add(x, y) and stores the result in total.console.log("Sum is:", total) prints the result.printSum(3, 7) outputs: Sum is: 10.undefined arguments.call(), apply(), and bind() to control this when needed.this.isEven that takes a number and returns true if it is even, otherwise false.sumArray that takes an array of numbers and returns their sum.reverseString that takes a string and returns it reversed.findMax that returns the largest number from an array.factorial that returns the factorial of a given number.capitalizeWords that capitalizes the first letter of each word in a string.countVowels that counts the number of vowels in a string.uniqueElements that returns an array with only unique elements from the input array.