Home > Enterprise >  foreach Statements with a function
foreach Statements with a function

Time:01-22

ok I am trying to answer a question and learning to code. regarding an array and using foreach statements the function must remain as this "function animalNames" must stay somewhere but apparently, I am doing something wrong because I get it returned as undefined. even through it produces the correct array back could someone look at it and let me know what i have done wrong.

attached is a picture of the code and array and question that i answered. this is how i wrote my function.

     const displayNames = [];
    
    zooAnimals.forEach(function animalNames(element){
        
    var display = "name: "   element.animal_name   ", "   "scientific: "   element.scientific_name
       
     displayNames.push(display);
         
      })
      console.log(displayNames); 

again i get the correct array back and the data looks correct...but animalNames comes back as undefined...i cannot remove this portion i am to keep it there but i do not know what to do with it.

code/question and array

CodePudding user response:

try this, it defines a function animalNames as separate function

    const displayNames = [];
    const zooAnimals = [
     {animal_name:"Jackel",scientific_name:"Canine"}
    ]
    function animalNames({animal_name, scientific_name}){
      return `name: ${animal_name}, scientific: ${scientific_name}`
    }
    zooAnimals.forEach((element)=>{
     displayNames.push(animalNames(element));
    })
    console.log(displayNames); 

  •  Tags:  
  • Related