Functions in JS

1) Why do we need functions?

Functions are used for reusability and to get rid of redundancy code.

In JS functions are treated by type one citizens. It can be declared in variables objects etc.

2) How do we declare a function?

1) Function Declaration
// Function defination
function name(parameters) {
    // Executable code 
}

name // Function Reference
name(arguments) // Function Call


// 2nd Way Function Expression
let name = function(parameters) {
    // Executable code
}

name(arguments)

3) What to do when you don’t know how many parameters will come in a function?

Example: Shopping Cart

function calculatePrice(item1, item2, ...item) {
    // return item // [3, 4, 5]
    // return item1, item2 // 2
    // Below is the syntax two return multiple items
    // You can flaten the output array and run a for loop and can calculate the price.
    // return [item1, item2, item] // [ 1, 2, [ 3, 4, 5 ] ]
}

let result = calculatePrice(1, 2, 3, 4, 5)

// Return Datatype is intresting its an array.
console.log(result) // [3, 4, 5]

4) How to pass an array to functions?

function returnSecondValue(anyarray) {
    console.log(anyarray[1]);    
}

returnSecondValue([1, 'pramod', 2])

Note :

Code written in global scope can be accessed in the block scope, but the reverse is not true

Global Scope in the console and Node.js environment (production code) is different

5) What is hoisting?

Hoisting refers to the language's behavior where variable and function declarations are seemingly "moved" to the top of their scope before code execution. This allows you to use functions and variables before they are formally declared in the code.

// Hoisting: The function is hoisted, meaning it can be called before its declaration in the code.
console.log(addOne(5)) // Function will return 6 
function addOne(num1) {
    return num1 + 1
}

console.log(addOne(5)) // Function will return 6

//  Not hoisted: Cannot be called before its declaration (since it's a variable assignment).

// console.log(addTwo(10)); // ReferenceError: Cannot access 'addTwo' before initialization
const addTwo = function(num) {
    return num + 2
}

console.log(addTwo(7));

6) What is an arrow function in JS?

Arrow functions in JavaScript provide a concise way to write function expressions. Introduced in ECMAScript 6 (ES6), they provide a more concise syntax compared to traditional function expressions.

Limitations:

  • Arrow functions are not suitable for methods that require their own this context, such as object methods.

  • They cannot be used as constructors.

// Traditional Function

function addOne(num) {
    return num + 1
}

// Arrow Function
// Cut the function name and after paranthesis place the arrow => 

// Explicit Return
// When you use return keyword Explicitly
const addTwo = function (num) => {
    return num + 2
}

// Implicit Return
// No need use the return keyword and remember curly braces we are not using.

const addThree = function(num) => num + 3
or 
const addThree = function(num) => (num + 3)

// Question let's assume If you want to return object when you passes two numbers 
const addTwoNumbers = (num1, num2) => ({username : "hitesh"})
console.log(addTwoNumbers(1, 2));

7) What are IIFE Functions in JS?

Immediately Invoked Function Expressions used

  1. When you want to close a file immediately

  2. Start DB connection immediately

  3. To avoid pollution from the global scope

// (function definition)(execution call)

function chai() {
    console.log(`DB CONNECTED`)
}
chai()

// IFFE
(function chai() {
    console.log(`DB CONNECTED`)
})(chai()) // It won't work


// Writing two IIFE Functions

// Named IIFE
// (function definition)(execution call)
(function chai() {
    console.log(`DB CONNECTED`)
})(); // Here you need to put the semicolon to indicate the IFFE is completed

// How to pass a parameter in the IIFE 
((name) => {
    // SIMPLE IFFE
    console.log(`DB CONNECTED 3 ${name}`);
    // console.log(this); // {}
})('pramod')

// After writing IIFE you need end ; Where to stop context
0
Subscribe to my newsletter

Read articles from Pramod Reddy Ambati directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pramod Reddy Ambati
Pramod Reddy Ambati