In JavaScript, an arrow function is a more concise way to write function expressions. Introduced in ES6 (ECMAScript 2015), arrow functions use the =>
syntax and have some differences compared to regular functions, especially in how they handle the this
keyword.
Basic Syntax
const add = (a, b) => a + b;
This is equivalent to:
function add(a, b) {
return a + b;
}
Key Features
- Shorter syntax
-
Lexical
this
binding (doesn’t have its ownthis
) -
No
arguments
object (use rest parameters if needed) -
Cannot be used as constructors (i.e., no
new
keyword)
Key Point:
Arrow functions are shorter and do not have their own this value — they use the this from their surrounding code.
map()
function in JavaScript:
The map()
function is used to create a new array by applying a function to each element of an existing array.
Syntax:
array.map(function(element, index, array) {
// return new value for each element
});
-
element
– current item -
index
(optional) – current item’s index -
array
(optional) – the original array
Example:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
What map()
Does:
- It does not change the original array.
- It returns a new array with transformed items.
Common Use Cases:
- Modify array values
- Extract specific properties from objects
- Convert data formats
--
### while
Loop in JavaScript
The while
loop is a control flow statement that allows code to be executed repeatedly based on a given condition.
Syntax:
while (condition) {
// code to run as long as condition is true
}
Simple Example:
let i = 0;
while (i < 5) {
console.log("Count:", i);
i++;
}
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Key Points:
- The loop continues as long as the condition is true.
- Make sure to update the loop variable (
i++
in the example), or it could become an infinite loop. - Use
break
to exit early if needed.
Top comments (0)