#javascript #tutorial #beginner

Day 3: Functions & Scope

Day 3: Reusable Logic (Functions)

A function is a block of code designed to perform a particular task. Instead of writing the same code twice, you write a function once and call it whenever you need it.

1. Function Declaration (The Classic Way)

function greet(name) {
    return `Hello, ${name}!`;
}

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

2. Arrow Functions (The Modern Way)

Introduced in ES6, these are shorter and cleaner. They are standard in modern frameworks like React.

const add = (a, b) => {
    return a + b;
};

// Implicit return (one-liner)
const multiply = (a, b) => a * b;

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

3. Scope

Scope determines where variables are accessible.

Global Scope

Variables defined outside any function are global.

let globalVar = "I am everywhere";

function test() {
    console.log(globalVar); // Works!
}

Block Scope (Local)

Variables defined inside a block { } (like a function or if statement) using let or const cannot be accessed from outside.

function secret() {
    const code = "1234";
}

// console.log(code); // Error: code is not defined

Default Parameters

You can set default values for arguments.

function welcome(user = "Guest") {
    console.log(`Welcome, ${user}`);
}

welcome();          // Welcome, Guest
welcome("Admin");   // Welcome, Admin

Homework for Day 3:

  1. Write an Arrow Function called convertToCelsius that takes fahrenheit as an input.
  2. Formula: (F - 32) * 5/9.
  3. Call it with a few values and log the result.

Day 4: We tackle Objects & Arrays!