javascript interview question #51: for each key

What happens here and what’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

The first line of code defines a user object that has two fields: name and age.

At the first glance it looks the foreach loop will log to the console the values of the all the fields in user.

It won’t happen, however.

In JS, foreach isn’t a standalone keyword. It’s a function that you can call on any array. And it’s spelled a bit differently: forEach.

For example, you can log all array elements to the console with it:

const arr = [1, 2, 3];

arr.forEach(item => console.log(item));

The fastest way to fix the provided code sample is to remove the each part. It will give us the proper for .. in loop.

We’ll loop through every key in user and log the values Jill and 25 to the screen.

  const user = { name: 'Jill', age: 25 };

  for (key in user) {
    console.log(user[key]);
  }

ANSWER: There’s an error in the code snippet which would be shown in console if we were to run this code. The most reasonable fix is to use the for .. in loop.