Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I console.log every element in an array?

Tags:

I'm having trouble with this question related to the forEach method. I've tried every way of writing this code out that I could think of but question one is still wrong every time.

function exerciseOne(names){

// Exercise One: In this exercise you will be given and array called names. 

// Using the forEach method and a callback as it's only argument, console log

// each of the names.
}


// MY CODE: 

function logNames(name){

  console.log(name);
}

 names.forEach(logNames);
like image 889
Cody Hayes Avatar asked May 09 '19 02:05

Cody Hayes


People also ask

How do you console an array in JavaScript?

JavaScript array initialization "use strict"; const nums = [1, 2, 3, 4, 5]; console. log(nums); The example creates a simple array in JavaScript. const nums = [1, 2, 3, 4, 5];

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

What does console log () do?

The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.


2 Answers

In your code you are logging the whole array. Use forEach method on array and log the element.

You need to pass a callback to forEach() the first element inside callback will be the element of array thought which its iterating. Just log that.

function exerciseOne(names){
  names.forEach(x => console.log(x));
}
exerciseOne(['John','peter','mart'])

Arrow function may confuse you. With normal function it will be

function exerciseOne(names){
  names.forEach(function(x){
    console.log(x)
  });
}
exerciseOne(['John','peter','mart'])
like image 95
Maheer Ali Avatar answered Sep 28 '22 18:09

Maheer Ali


Just use console.log as the callback, logging the first parameter (the current item) each time:

function exerciseOne(names) {
  names.forEach(name => console.log(name));
}
exerciseOne(["Jack", "Joe", "John", "Bob"]);
like image 44
Jack Bashford Avatar answered Sep 28 '22 18:09

Jack Bashford