Day 5: Functions in JavaScript

Day 5: Functions in JavaScript

Welcome back to our JavaScript series! Today, we'll learn about functions, which are essential for organizing and reusing your code.

Functions

Functions are block of code that is used to perform a specific task. We can call the same function whenever we need to execute the same code multiple times.

1. Function Declaration

A function declaration defines a function with a name.

function greet() {
    console.log('Hello, World!');
}

// Calling the function
greet(); // Output: Hello, World!

2. Function Expression

A function expression defines a function inside a variable.

let greet = function() {
    console.log('Hello, World!');
};

// Calling the function
greet(); // Output: Hello, World!

3. Arrow Functions

Arrow functions provide a shorter syntax for writing functions.

let greet = () => {
    console.log('Hello, World!');
};

// Calling the function
greet(); // Output: Hello, World!

Parameters and Arguments

Functions can take parameters, which are like placeholders for the values you pass to the function. Arguments are the actual values passed to the function when it's called.

function greet(name) {
    console.log('Hello, ' + name + '!');
}

greet('Alice'); // Output: Hello, Alice!
greet('Bob');   // Output: Hello, Bob!

Return Values

Functions can return a value using the return statement. This value can be used wherever the function is called.

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

let sum = add(3, 4);
console.log(sum); // Output: 7

Scope

Scope determines the accessibility of variables. There are three types of scope in JavaScript:

  1. Global Scope: Variables declared outside any function have global scope. They can be accessed from anywhere in the code.

     let globalVar = 'I am global';
    
     function showGlobalVar() {
         console.log(globalVar);
     }
    
     showGlobalVar(); // Output: I am global
    
  2. Local Scope: Variables declared inside a function have local scope. They can only be accessed within that function.

     function showLocalVar() {
         let localVar = 'I am local';
         console.log(localVar);
     }
    
     showLocalVar(); // Output: I am local
     // console.log(localVar); // Error: localVar is not defined
    
  3. Block Scope: Variables declared with let or const inside a block (like an if statement or a loop) have block scope. They can only be accessed within that block.

     if (true) {
         let blockVar = 'I am block scoped';
         console.log(blockVar); // Output: I am block scoped
     }
     // console.log(blockVar); // Error: blockVar is not defined
    

Summary

Today, we covered functions in JavaScript , that is used to organize our code, make it reusable, and keep it clean & modular.

Tomorrow, we'll explore objects and arrays, which are essential for managing and organizing data in JavaScript.