While Loop:
A while loop in JavaScript is a control structure that repeats a block of code as long as a specified condition is true.
Syntax:
while (condition) {
// code to be executed
}
condition is checked before each loop iteration.
If the condition is true, the loop runs.
When the condition becomes false, the loop stops.
Example:
let i = 1;
while (i <= 5) {
console.log("Count is: " + i);
i++; // increase i by 1
}
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Arrow function:
Arrow functions are a shorter way to write functions in JavaScript. They were introduced in ES6 (ECMAScript 2015).
Basic Syntax:
const functionName = (parameters) => {
// function body
};
Example: Add two numbers
const add = (a, b) => {
return a + b;
};
console.log(add(2, 3)); // Output: 5
Shortcut (if only one line and return needed):
You can omit the curly braces and return keyword:
const multiply = (a, b) => a * b;
console.log(multiply(2, 4)); // Output: 8
map() in JavaScript:
In JavaScript, map() is a built-in array method used to create a new array by applying a function to each element of the original array.
Syntax:
array.map(function(currentValue, index, array) {
// return something
});
Or with an arrow function:
array.map((value, index) => {
// return something
});
value: The current element
index (optional): Index of the current element
Returns: A new array with the transformed values
Example: Convert an array of names to uppercase
const names = ["john", "jane", "doe"];
const upperNames = names.map(name => name.toUpperCase());
console.log(upperNames); // Output: ["JOHN", "JANE", "DOE"]
Top comments (0)