Spex3
    

JavaScript Functions πŸ—οΈ


    

    

JavaScript Functions πŸ—οΈ
Functions are reusable blocks of code that perform a specific task.

1️⃣ Defining Functions
Functions can be declared using function or expressed as variables.

βœ… 1. Function Declaration

 
function greet() {
console.log("Hello, world!");
}
greet(); // Output: Hello, world!

πŸ“Œ Functions declared this way can be called before they are defined (hoisted).

βœ… 2. Function Expression (Stored in a Variable)

JavaScript Functions const greet = function() {
console.log("Hello, world!");
};
greet(); // Output: Hello, world!


πŸ“Œ Function expressions are NOT hoisted (they must be defined before use).

βœ… 3. Arrow Function (ES6+)

const greet = () => {
console.log("Hello, world!");
};
greet(); // Output: Hello, world!


πŸ“Œ Best for shorter, cleaner functions!

2️⃣ Function Parameters and Return Values
Functions can take inputs (parameters) and return outputs.

βœ… 1. Function with Parameters

function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!


πŸ“Œ Parameters let you pass dynamic values.

βœ… 2. Function with Multiple Parameters

function add(a, b) {
console.log(a + b);
}
add(5, 3); // Output: 8
add(10, 2); // Output: 12


βœ… 3. Function with a Return Value
 
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
console.log(result); // Output: 20


πŸ“Œ return stops the function and sends back a value.

3️⃣ Default Parameters (ES6+)
If a parameter is not provided, JavaScript assigns a undefined value.
We can set default values to avoid issues.

 
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Guest!
greet("Sam"); // Output: Hello, Sam!


4️⃣ Arrow Functions with Parameters
βœ… Shorter Syntax for Simple Functions
 
const add = (a, b) => a + b;
console.log(add(3, 7)); // Output: 10


πŸ“Œ No {} or return needed for one-line functions!

5️⃣ Function Scope (Local vs Global Variables)
Variables inside a function are local and can’t be accessed outside.


function example() {
let x = 10; // Local variable
console.log(x);
}
example(); // Output: 10
console.log(x); // ❌ Error: x is not defined

6️⃣ Summary
βœ… Use functions to avoid repeating code.
βœ… Use return to send back values.
βœ… Use default parameters to handle missing values.
βœ… Use arrow functions for cleaner code.


    Date: 2025-03-29 00:00:00.000000