# Function in JavaScript

## Function:

function in simplest word that you write code once and used it many place where u wanted without rewritting it again in again.

```plaintext
function dushyantPratap(a, b) {
return a + b ;
}
console.log(dushyantPratap(7, 4)); // 11
console.log(dushyantPratap(7, 9)); // 16
```

here in this eg we have a function in which dushyantPratap is a function naem , we ca call the whole function with this fn name , in the bracket we gave parameter , like valiues now in curly brackeet we wroyte the whole code , now if u want to call it use function name.

we just

A function is a reusable block of code that perform a specific task.

### Why we need functions

1.  **Reuse code** – write once, use many times.
    
2.  **Avoid repetition** – keeps code clean.
    
3.  **Organize logic** – break big problems into smaller parts.
    
4.  **Make code easier to maintain.**
    

* * *

## Function declaration:

```plaintext
function functionName(parameters) {
   // code to run
}
```

### Example

```plaintext
function greet() {
  console.log("Hello");
}
```

### What each part means

**1.** `function`

This keyword tells JavaScript:

> “Hey, I’m creating a function.”

* * *

**2.** `greet`

This is the **name of the function**.

Like naming a person or machine.

* * *

**3.** `( )`

These hold **parameters (inputs)**.

Example:

```plaintext
function greet(name) {
  console.log("Hello " + name);
}
```

`name` is the input.

* * *

**4.** `{ }`

This is the **body of the function**.

The code inside runs when the function is called.

* * *

## note:

**Writing a function does NOT run it.**

You must **call it**.

Example:

```plaintext
function greet() {
  console.log("Hello");
}

greet();
```

Output:

```plaintext
Hello
```

* * *

## funtion expression:

A **function expression** means:

> You create a function and **store it inside a variable**.

Think of it like this:

A function is just a **value**, and you are **saving that value in a variable**.

### Basic Syntax

```plaintext
let variableName = function(parameters) {
  // writr your code here
};
```

2\. Simple Example

```plaintext
let add = function(a, b) {
  return a + b;
};

console.log(add(5, 3)); // 8

```

What is happening:

*   `add` → variable
    
*   `function(a, b)` → function stored inside the variable
    
*   `add(5,3)` → calling the function
    

So the variable **holds the function**.

## 3\. Real-Life Analogy

Think of a **box**.

```plaintext
add  →  [ function ]
```

When you run:

```plaintext
add(5,3)
```

You are basically saying:

> "Hey add, run the function inside you."

* * *

## 3\. Difference Between Function Declaration and Expression

### Function Declaration

```plaintext
function add(a,b){
  return a+b;
}
```

Characteristics:

*   The function is **fully hoisted**
    
*   You can call it **before it is defined**
    

Example:

```plaintext
console.log(add(2,3));

function add(a,b){
  return a+b;
}
```

This works because JavaScript **moves the function to the top during execution**.

* * *

### Function Expression

```plaintext
let add = function(a,b){
  return a+b;
};
```

Characteristics:

*   The function is **stored in a variable**
    
*   It **cannot be used before the variable is initialized**
    

Example:

```plaintext
console.log(add(2,3));

let add = function(a,b){
  return a+b;
};
```

This will throw an error:

```plaintext
ReferenceError: Cannot access 'add' before initialization
```

The reason is that the variable `add` is not ready yet.

* * *

## Hoisting

this is interviewer favourite question

they will ask:

if `let` is hoisted or not

if u say yes - rejected

if u say no - rejected

now whats the corrected ans - yes + explanation

Before running your code, JavaScript quickly scans the whole file and **writes down all the function declarations and variables at the top of the page**.

This process is called **hoisting**.

But here's the catch:

**It only moves the declarations, not the values.**

* * *

### Example 1 — Function Declaration

Code:

```plaintext
console.log(add(2,3));

function add(a,b){
  return a+b;
}
```

What JavaScript internally sees:

```plaintext
function add(a,b){
  return a+b;
}

console.log(add(2,3));
```

So it works.

Because the function was **registered before execution started**.

* * *

### Example 2 — Variable with `var`

code:

```plaintext
console.log(x);

var x = 10;
```

What JavaScript sees:

```plaintext
var x;

console.log(x);

x = 10;
```

Output:

```plaintext
undefined
```

Because the **variable name moved up**, but the value `10` stayed where it was.

* * *

### Example 3 — `let` and `const`

Your code:

```plaintext
console.log(x);

let x = 10;
```

This crashes.

Error:

```plaintext
ReferenceError
```

Because `let` and `const` exist in something called the **Temporal Dead Zone**.

Simple meaning:

> The variable exists, but JavaScript refuses to let you touch it yet.

## Temporal Dead Zone (TDZ)

The **Temporal Dead Zone** is the time between:

```plaintext
when a variable is created
and
when it is initialized
```

During this time, **JavaScript will not let you use the variable**.

This happens with `let` **and** `const`.

* * *

### Example

```plaintext
console.log(a);

let a = 10;
```

This will crash with:

```plaintext
ReferenceError: Cannot access 'a' before initialization
```

Why?

Because `a` exists, but it is inside the **Temporal Dead Zone**.

* * *

# when to use which one

## Function Declaration

A function declaration defines a function using the `function` keyword.

```plaintext
function add(a, b) {
  return a + b;
}
```

**Key point:**

Function declarations are **hoisted**, which means you can use them before they are written in the code.

Example:

```plaintext
console.log(add(2,3));

function add(a,b){
  return a+b;
}
```

### When to use it

Use **function declaration** when:

*   the function is **important or reusable**
    
*   it will be used in **multiple places**
    
*   it is part of the **main logic**
    

Example:

```plaintext
function createUser(name){
  return { name };
}
```

* * *

## Function Expression

A function expression is when a function is **stored in a variable**.

```plaintext
const add = function(a, b) {
  return a + b;
};
```

Function expressions are **not usable before they are defined**.

### When to use it

Use **function expression** when:

*   the function is **used once**
    
*   the function is **passed as an argument (callback)**
    
*   the function is **temporary**
    

Example:

```plaintext
setTimeout(function(){
  console.log("Hello after 2 seconds");
}, 2000);
```

* * *

## When to Use `let`, `var`, and `const`

### `const` (Most Recommended)

Use `const` when the variable **should not be reassigned**.

```plaintext
const pi = 3.14;
```

Most variables in modern JavaScript use `const`.

* * *

### `let`

Use `let` when the variable **will change later**.

```plaintext
let score = 10;
score = 20;
```

* * *

### `var`

`var` is the **old way** of declaring variables and is mostly avoided today because it can cause bugs.

```plaintext
var name = "John";
```

Modern JavaScript mainly uses:

*   **const**
    
*   **let**
    

* * *

**Simple rule**

```plaintext
const → default choice
let   → when value will change
var   → avoid in modern JavaScript
```

In case you are not able to understand these here is the video link in which i explain in detail

%[https://youtu.be/_ZjkifF7QD8]
