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.
// 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
this
(lexical this)new
arguments
objectfor
LoopBest 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]);
}
for...of
LoopBest when you want to iterate through values in an array or iterable.
for (const fruit of fruits) {
console.log(fruit);
}
for...in
LoopUsed 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]);
}
forEach()
MethodforEach 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);
});
forEach
forEach
is a method, not a global functionArray.prototype
break
or continue
)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 |