Home > Web Front-end > JS Tutorial > body text

ypes of for Loops in JavaScript

WBOY
Release: 2024-08-22 18:33:06
Original
859 people have browsed it

ypes of for Loops in JavaScript

We all know and love the classic for loop, but did you know that JavaScript has a few other powerful for loop options up its sleeve?

1) for/in: This one is very useful to iterate over the keys of an object and manipulating object properties.

Example:

const obj = {name: "JavaScript", type: "Language"};
for (let key in obj) {
    console.log(key); // outputs "name" and "type"
}
Copy after login

2) for/of: This one is optimal when your focus is on the values rather than the keys or indices of iterable objects, such as arrays or strings.

Example:

const arr = ["JavaScript", "is", "versatile"];

for (let value of arr) {

  console.log(value);

}
Copy after login

3) forEach: This one is a gem, as it offers convenience and readability, helping you iterate over arrays with minimal syntax, so you can focus on the logic within the loop rather than the iteration process itself.

Example:

const arr = ["JavaScript", "is", "versatile"];

arr.forEach(value => console.log(value));
Copy after login

Which of these is your favorite?

The above is the detailed content of ypes of for Loops in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!