How to Use Loops and Functions in Object-Oriented JavaScript?

Estimated read time 1 min read
  1. Loops in JavaScript: Loops are used to repeat a block of code multiple times. In JavaScript, you can use the for loop, the forEach loop, and the while loop to accomplish this.

Example of using a for loop:

for (let i = 0; i < 10; i++) {
  console.log(i);
}

Example of using a forEach loop:

const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
  console.log(number);
});

Example of using a while loop:

let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}
  1. Functions in JavaScript: Functions are blocks of reusable code that can be executed by calling the function’s name and passing in arguments, if needed. Functions can return a value and can be assigned to variables.

Example of a function:

function sum(a, b) {
  return a + b;
}

const result = sum(2, 3);
console.log(result); // 5

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply