JavaScript: Arrow Functions and Looping Methods

1. Arrow Functions

Arrow functions are a concise way to write functions in JavaScript. They do not bind their own this, arguments, or super, making them suitable for callbacks and short functions.

🔹 Syntax and Examples

// Traditional function
function square(num) {
    return num * num;
}

// Arrow function (explicit return)
const square = (num) => {
    return num * num;
}

// Arrow function (implicit return)
const square = num => num * num;

console.log(square(5)); // Output: 25

🔹 Key Features

2. Looping Methods

2.1. Normal for Loop

Best when you need to access or manipulate the index directly.

const fruits = ['Apple', 'Mango', 'Banana'];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

2.2. for...of Loop

Best when you want to iterate through values in an array or iterable.

for (const fruit of fruits) {
    console.log(fruit);
}

2.3. for...in Loop

Used for iterating over object keys.

const person = {
    name: "Girija Devi",
    age: 40,
    education: "8th passout"
};

for (const key in person) {
    console.log(key + ": " + person[key]);
}

2.4. forEach() Method

forEach is a method of the Array object. It executes a provided function once for each array element.

fruits.forEach(function(fruit, index) {
    console.log(index + " → " + fruit);
});

🔹 Key Facts About forEach

3. When to Use Which Loop?

4. Difference Table

Loop Type Use Case Data Type Can Break? Return Value Best For
for Indexed loop Array, String Yes None Manual index control
for...of Value iteration Iterable (Array, String, Set) Yes None Reading array values
for...in Key iteration Object (also Arrays, but not recommended) Yes None Reading object properties
forEach Array iteration with function Array only No undefined Logging / DOM updates / side effects