📦 Day 6 — Functions & Scope in JavaScript

📦 Day 6 — Functions & Scope in JavaScript

Welcome to Day 6 🎯 So far, you’ve learned how to perform actions and loops. Now it’s time to **organize your code into reusable pieces** using functions. Functions make code cleaner, reduce repetition, and make debugging easier.

🔹 1️⃣ What Is a Function?

A function is a block of code designed to perform a specific task. You define it once and use it multiple times by calling it.

function greet() {
  console.log("Hello Krishna!");
}

greet(); // Calling the function

🔸 2️⃣ Function with Parameters

Parameters let you pass values into functions so they can work with different data.

function greetUser(name) {
  console.log("Hello " + name + "!");
}

greetUser("Krishna");
greetUser("Radha");

🧩 3️⃣ Function with Return Value

Functions can return results for later use.

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

let result = add(5, 10);
console.log("Sum is:", result);

💡 4️⃣ Function Expressions

You can store functions in variables — these are called **function expressions**.

const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 3));

⚡ 5️⃣ Arrow Functions (ES6)

Arrow functions are a modern, shorter way to write functions.

const greet = (name) => console.log(`Hello ${name}!`);
greet("Rahul");

🌐 6️⃣ Scope in JavaScript

Scope determines where variables can be accessed in your code.

Types of Scope:

  • Global Scope: Accessible anywhere in the script.
  • Local (Function) Scope: Declared inside a function — can’t be accessed outside.
  • Block Scope: Variables inside { } using let or const.
let globalVar = "Global";

function showScope() {
  let localVar = "Local";
  console.log(globalVar); // Accessible
  console.log(localVar);  // Accessible inside function
}

showScope();
console.log(globalVar); // Accessible
// console.log(localVar); ❌ Error

🧠 7️⃣ Practice Task

  1. Create a function that multiplies three numbers.
  2. Write an arrow function to find the square of a number.
  3. Experiment with global and local variables.

🎯 Summary

Functions help you write clean, reusable, and structured code. You also learned about variable scope — a critical concept in modern programming. Next up, we’ll move to **Arrays & Array Methods** where data management gets fun!

Comments