DEV Community

Chithra Priya
Chithra Priya

Posted on

Day-8 in JS: Looping(while), Arrow function, Map method..

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Enter fullscreen mode Exit fullscreen mode

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
};
Enter fullscreen mode Exit fullscreen mode

Example: Add two numbers

const add = (a, b) => {
  return a + b;
};

console.log(add(2, 3)); // Output: 5
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

Or with an arrow function:

array.map((value, index) => {
  // return something
});
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)