Featured
- Get link
- X
- Other Apps
π¦ 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
letorconst.
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
- Create a function that multiplies three numbers.
- Write an arrow function to find the square of a number.
- 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!
Popular Posts
π Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
π¨ Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment