A funation is a reusable block of code that performs a specific task.
Type of Function | Definition | Syntax | Example |
---|---|---|---|
Named Function | A function with a specific name. | function functionName() { // code } |
function greet() { console.log("Hello!"); } |
Anonymous Function | A function without a name. | function() { // code } |
let greet = function() { console.log("Hello!"); }; |
Function Expression | A function assigned to a variable. | let functionName = function() { // code }; |
let greet = function() { console.log("Hello!"); }; |
Arrow Function | A concise way to define functions using arrow syntax. | const functionName = () => { // code }; |
const greet = () => console.log("Hello!"); |
IIFE (Immediately Invoked Function Expression) | A function that is defined and executed immediately. | (function() { // code })(); |
(function() { console.log("Hello!"); })(); |
Callback Function | A function passed as an argument to another function. | function outerFunction(callback) { callback(); } |
function greet() { console.log("Hello!"); } outerFunction(greet); |
Higher-Order Function | A function that takes another function as an argument or returns a function. | function higherOrderFunction(callback) { // ... } |
function add(x, y) { return x + y; } function applyOperation(callback, a, b) { return callback(a, b); } |
- Named functions have a
name identifier
- Use named functions for
bog and complex
logics. - Use when you want to
reuse
one function at multiple places.
// Named function
function sum(a, b) {
return a + b;
}
console.log(sum(5, 3));
// Output: 8
- Anonymous functions
do not have a name identifier
and cannot be referenced directly by name. - Use anonymous functions for
small logics
- Use when want to use a function in a
single place
//Anonymous function
console.log(function(a, b) {
return a * b;
})(4, 5);
// Output: 20
A function expression is a way to define a function by assigning it to a variable
.
// Anonymous Function Expression
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3));
// Output: 8
// Named Function Expression
const add = function sum(a, b) {
return a + b;
};
console.log(add(5, 3));
// Output: 8
A callback function is a function that is passed as an argument
to another function.
// Function to add two numbers
function add(x, y) {
return x + y;
}
// Using the functions
let a = 3, b = 5;
let result = add(a, b);
console.log(result);
// Output: 8
// Function to display the result of an operation
function display(x, y, operation) {
var result = operation(x, y);
console.log(result);
}
// Passing different operations to display
display(10, 5, add); // Output: 15
display(10, 5, multiply); // Output: 50
display(10, 5, subtract); // Output: 5
display(10, 5, divide); // Output: 2
A callback function is a function that is passed as an argument
to another function.
function add(x, y) {
return x + y;
}
function display(x, y, operation) {
var result = operation(x, y);
console.log(result);
}
//Output: 8
let a = 3, b = 5;
let result = add(a, b);
console.log(result); // Output: 8
display(10, 5, add); // Output: 15
display(10, 5, multiply); // Output: 50
display(10, 5, subtract); // Output: 5
display(10, 5, divide); // Output: 2
- Take one or more functions as
arguments
(callback function) Return
a function as a result
// Take one or more functions as arguments
function hof(func) {
func();
}
// High-order function
hof(sayHello);
function sayHello() {
console.log("Hello!");
}
//Output: "Hello!"
// Return a function as a result
function createAdder(number) {
return function(value) {
return value + number;
};
}
const addFive = createAdder(5);
console.log(addFive(2));
// Output: 7
Parameters are the placeholders
defined in the function declaration.
//a and b are parameters
function add(a,b){
console.log(a+b);
}
Arguments are the actual values passed
to a function when it is invoked or called.
add(3,4);
// 3 and 4 are arguments
function add(a, b) {
console.log(a + b);
}
add(3, 4);
// Output: 7
var person = {
name: "Happy",
role: "Developer"
};
function greet(person) {
console.log(person.name + " " + person.role);
}
greet(person);
// Output: Happy Developer
sum(1, 2, 3);
function sum() {
console.log(arguments[0]); // Output: 1
console.log(arguments[1]); // Output: 2
console.log(arguments[2]); // Output: 3
console.log(arguments.length); // Output: 3
}
In JavaScript, default parameters allow you to specify default values
for function parameters.
// Function with default parameter value
function greet(name = "Happy") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Happy!
greet("Amit"); // Output: Hello, Amit!
- Event handling is the process of
responding to user actions
in a web page. - The
addEventListener
method of JavaScript allows to attach anevent name
and with thefunction
you want to perform on that event.
<button id="myButton">Click me</button>
// Get a reference to the button element
const button = document.getElementById('myButton');
// Add an event listener for the 'click' event
button.addEventListener('click', function() {
alert('Button clicked!');
});
Event Type | Description | Syntax |
---|---|---|
Click | Triggers when an element is clicked. | element.addEventListener('click', handler); |
Mouseover | Triggers when the mouse pointer moves over an element. | element.addEventListener('mouseover', handler); |
Keydown | Triggers when a key is pressed. | document.addEventListener('keydown', handler); |
Keyup | Triggers when a key is released. | document.addEventListener('keyup', handler); |
Submit | Triggers when a form is submitted. | formElement.addEventListener('submit', handler); |
Focus | Triggers when an element gains focus (e.g., when a user clicks on an input field). | element.addEventListener('focus', handler); |
Blur | Triggers when an element loses focus (e.g., when a user clicks outside an input field). | element.addEventListener('blur', handler); |
Change | Triggers when the value of an element changes (e.g., when a user selects a different option from a dropdown list). | element.addEventListener('change', handler); |
Load | Triggers when the page has finished loading. | window.addEventListener('load', handler); |
Resize | Triggers when the window is resized. | window.addEventListener('resize', handler); |
A programming language is said to have First-class functions, if functions in that language are treated like other variables
.
Functions treated like variables
- Assignable
- Passable as Arguments
- Returnable as Values
// 1. Assigning function like a variable
const myFunction = function() {
console.log("Interview, Happy!");
};
myFunction();
// Output: "Interview, Happy!"
function double(number) {
return number * 2;
}
// 2. Passing function as an argument like a variable
function performOperation(double, value) {
return double(value);
}
console.log(performOperation(double, 5));
// Output: 10
// 3. A function that returns another function
function createSimpleFunction() {
return function() {
console.log("I am from return function.");
};
}
const simpleFunction = createSimpleFunction();
simpleFunction();
// Output: "I am from return function."
- Always produces the
same output for the same input
. - Cannot modify the
state
. - Cannot have
side effects
.
//Pure function
function add(a, b) {
return a + b;
}
console.log(add(3,5))
//Output: 8
console.log(add(3,5))
//Output: 8
- Can produce
different outputs for the same input
. - Can modify the state.
- Can have side effects.
let total = 0;
function addToTotal(value) {
total += value;
return total;
}
console.log(addToTotal(5))
//Output: 5
console.log(addToTotal(5))
//Not same Output: 10
-
Currying in JavaScript transforms a function with multiple arguments into a
nested series of functions
, each taking a single argument. -
Advantage:
Reusability, modularity, and specialization
. Big, complex functions with multiple arguments can be broken down into small, reusable functions with fewer arguments.
// Regular function that takes two arguments
// and returns their product
function multiply(a, b) {
return a * b;
}
// Curried version of the multiply function
function curriedMultiply(a) {
return function (b) {
return a * b;
};
}
// Create a specialized function for doubling a number
const double = curriedMultiply(2);
console.log(double(5)); // Output: 10 (2 * 5)
// Create a specialized function for tripling a number
const triple = curriedMultiply(3);
console.log(triple(5)); // Output: 15 (3 * 5)
Call, apply and bind are three methods in JavaScript that are used to work with functions and control how they are invoked
and what context they operate in.
- These methods provide a way to manipulate the
this value
and pass arguments to functions.
// Defining a function that uses the "this" context and an argument
function sayHello(message) {
console.log(`${message}, ${this.name}!`);
}
const person = { name: 'Adarsh' };
// 1. call - Using the "call" method to invoke the function
// with a specific context and argument
sayHello.call(person, 'Hello');
//Output: "Hello, Adarsh!"
// 2. apply - Using the "apply" method to invoke the function
// with a specific context and an array of arguments
sayHello.apply(person, ['Hi']);
//Output: "Hi, Adarsh!"
// 3. bind - Using the "bind" method to create a new function
// with a specific context (not invoking it immediately)
const greetPerson = sayHello.bind(person);
greetPerson('Greetings');
//Output: "Greetings, Happy!"