"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Functions

 

Functions are reusable blocks of code that perform a specific task. They help make your code more organized, readable, and maintainable.


Function Declaration vs Function Expression

Function Declaration – Defined using the function keyword with a name.

function greet() {

  console.log("Hello, World!");

}

greet(); // Output: Hello, World!

Function Expression – A function stored in a variable (can be anonymous).

const greet = function() {

  console.log("Hello, World!");

};

greet(); // Output: Hello, World!


Parameters and Return Values

Functions can take inputs (parameters) and return outputs (return values).

function add(a, b) {

  return a + b;

}

let sum = add(5, 3);

console.log(sum); // Output: 8


Arrow Functions (=>)

Arrow functions provide a shorter syntax and do not have their own this context.

const multiply = (x, y) => x * y;

console.log(multiply(4, 5)); // Output: 20

 

// Single parameter doesn't need parentheses

const square = n => n * n;

console.log(square(6)); // Output: 36


Scope: Local vs Global

  • Global Scope – Variables declared outside any function are accessible anywhere.
  • Local Scope – Variables declared inside a function are accessible only within that function.

let globalVar = "I am global";

 

function testScope() {

  let localVar = "I am local";

  console.log(globalVar); // Accessible

  console.log(localVar);  // Accessible here

}

 

testScope();

console.log(globalVar); // Accessible

// console.log(localVar); // Error: not defined


Hoisting

  • Function Declarations are hoisted – they can be called before they are defined in the code.
  • Function Expressions and Arrow Functions are not hoisted in the same way.

sayHello(); // Works because function declarations are hoisted

function sayHello() {

  console.log("Hello!");

}

 

// greet(); // Error: Cannot access before initialization

const greet = function() {

  console.log("Hi!");

};

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)