Why we are use the for-in loop. What are difference between the foreach and for-in loop?

0 votes
26 views
Ravi Vishwakarma asked 10 days ago in Web Application by Ravi Vishwakarma

Why we are use the for-in loop. What are difference between the foreach and for-in loop?

1 Answer

0 votes
Ethan Karla answered 8 days ago by Ethan Karla
forEach is an Array method that we can use to execute a function on each element in an array. It can only be used on Arrays, Maps, and Sets. A simple example would be to display each element of an array. Here’s what this might look like with for loop.
Example:
const arr = ['cat', 'dog', 'fish'];

arr.forEach(element => {
  console.log(element);
});
let text = '';

const fruits = ['apple', 'orange', 'cherry'];
fruits.forEach(myFunction);
function myFunction(item, index) {
  console.log('index : '+index+' , item : '+item);
}
For-in loop
For-in is used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable.
for (variable in object) { 

// do something
}
Example:
const obj = {  

  a: 1,
  b: 2,
  c: 3,
  d: 4
}
for (let elem in obj) {
  console.log( obj[elem] )
}