Skip to content

Latest commit

 

History

History
281 lines (216 loc) · 6.13 KB

File metadata and controls

281 lines (216 loc) · 6.13 KB

JavaScript Functions

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.

Types of Functions

JavaScript provides two main types of functions:

1. Built-in 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 integer

2. User-Defined Functions

The functions which has been created by developer to perform the operation is called as User defined function.

Types of User-Defined Functions

User-defined functions can be categorized based on parameters:

1. Parameterized Function

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!"
2. Non-Parameterized Function

A function that does not accept any arguments.

function greet() {
    return "Hello, World!";
}

console.log(greet()); // Output: "Hello, World!"

Function Definitions

1. Function Declaration (Named Function)

  • Named function, hoisted.
  • Can be called before its definition.

Example:

function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: "Hello, Alice!"

2. Function Expression

  • 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!"

3. Arrow Function (ES6)

  • 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!"

4. Anonymous Function

  • Functions without names, often used as callbacks.

Example:

setTimeout(function() {
    console.log("This is an anonymous function!");
}, 2000);

5. Callback Function

  • 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`);
});

6. IIFE (Immediately Invoked Function Expression)

  • Executes immediately after creation.
  • Anonymous function.

Example:

(() => {
    console.log(`IIFE function`);
})();

7. Default Parameters (ES6)

  • 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

8. Closure

  • 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 vs. Arrow Function

1. Syntax

  • Normal Function: function functionName() { ... }
  • Arrow Function: () => { ... }

2. this Keyword

  • Normal Function: Supports this and 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

3. Arguments Object

  • Normal Function: Has access to arguments.
  • Arrow Function: Does not have an arguments object.

Example:

function getData(a, b) {
    console.log(arguments);
}
getData(10, 12);

4. Return Statement

  • Normal Function: Requires return for output.
  • Arrow Function: Requires return only if the function body has more than one line.

5. Hoisting

  • Normal Function: Function declarations are hoisted.
  • Arrow Function: Not hoisted.

Understanding this Keyword in Different Contexts

1. Global Scope

  • In the global scope, this refers to the global object (window in browsers, global in Node.js).

Example:

console.log(this); // In browser: window object

2. Strict Mode

  • In strict mode, this is undefined in global functions.

Example:

'use strict';
function strictFunc() {
    console.log(this); // Output: undefined
}
strictFunc();

3. Object Methods

  • When used in an object method, this refers to the object itself.

Example:

const person = {
    name: "Vishnu",
    greet: function() {
        console.log(`Hello, ${this.name}`);
    }
};
person.greet(); // Output: Hello, Vishnu

4. Event Handlers

  • In event handlers, this refers to the element that triggered the event.

Example:

document.querySelector("button").addEventListener("click", function() {
    console.log(this); // Output: Button element
});