๐ง Javascript Functions & Scope
โ Why functions matter
- Avoid repeating code
- Make logic reusable
- Improve readability
- Easier debugging
Real use cases:
- Form validation
- Calculations
- API handling
- Button click logic
๐ง What is a function
A function is a block of code designed to perform a task.
Think of it as ๐ Input โ Logic โ Output
โ๏ธ Function Declaration
function greet() {
console.log("Hello World");
}
Call the function
greet();๐ฅ Functions with parameters
function greetUser(name) {
console.log("Hello " + name);
}
greetUser("Deepak");-
name is a parameter-
"Deepak" is an argument๐ Function with return value
function add(a, b) {
return a + b;
}
javascript
let result = add(5, 3);
console.log(result);
-
return sends value back- Function execution stops after return
โก Arrow Functions (Modern JS)
Shorter syntax
Commonly used in React and APIs
const multiply = (a, b) => {
return a * b;
};
Single line shortcut
const square = x => x * x;๐ง What is Scope
Scope defines where a variable can be accessed.
Types of scope you must know:
- Global scope
- Function scope
- Block scope
๐ Global Scope
let city = "Delhi";
function showCity() {
console.log(city);
}
- Accessible everywhere
- Overuse causes bugs
๐ Function Scope
function test() {
let msg = "Hello";
console.log(msg);
}
-
msg exists only inside function๐งฑ Block Scope (let & const)
if (true) {
let age = 25;
}
-
age cannot be accessed outside-
let and const are block scopedโ ๏ธ
var ignores block scope (avoid it)๐ซ Common Beginner Mistakes
- Forgetting
return- Using global variables everywhere
- Confusing parameters and arguments
- Using
var๐งช Mini Practice Task
- Create a function to calculate square of a number
- Create a function that checks if a number is positive
- Create an arrow function to add two numbers
- Test variable scope using
let inside a blockโ Mini Practice Task โ Solution ๐ง
๐ข 1๏ธโฃ Function to calculate square of a number
function square(num) {
return num * num;
}
console.log(square(5));โ๏ธ Output โ 25
โ 2๏ธโฃ Function to check if a number is positive
function isPositive(num) {
if (num > 0) {
return "Positive";
} else {
return "Not Positive";
}
}
javascript
console.log(isPositive(10));
console.log(isPositive(-3));
โ๏ธ Output
- Positive
- Not Positive
โก 3๏ธโฃ Arrow function to add two numbers
const add = (a, b) => a + b;console.log(add(4, 6));โ๏ธ Output โ 10
๐งฑ 4๏ธโฃ Test variable scope using let inside a block
if (true) {
let message = "Hello Scope";
console.log(message);
}
// console.log(message); โ Error
โ๏ธ
message exists only inside the block๐ง Key takeaways
- Functions make code reusable
-
return sends output- Arrow functions are concise
-
let respects block scopeโก๏ธ Double Tap โฅ๏ธ For More