Javascript ES6 import + forEach()

Hi

Could somebody help please.

In the ES6 Java Script import lesson we had to import a module from airplane.js into missionControl.js. All ok on that part. I’m struggling with the iterator forEach() in the next part:

Inside the airplane.js module was an object that contained two airplanes with their name and fuelCapacity key pairs.

We then had to iterate over this object in missionControl.js. I will post the code from both files below. My question is what specifically is being passed into the ‘element’ parameter in the function when it is run? Is it Airplane from Airplane.js?

Thank you!

Airplane.js code:

let Airplane = {
  
};

Airplane.availableAirplanes = [
  {
    name: 'AeroJet', 
    fuelCapacity: 800
    }, 
    
    {
      name: 'SkyJet', 
      fuelCapacity: 500
      }
    ];

    export default Airplane;

missionControl.js code:

import Airplane from './airplane';

function displayFuelCapacity() {
  Airplane.availableAirplanes.forEach(function(element)
  {
    console.log('Fuel Capacity of ' + element.name + ': ' + element.fuelCapacity)
    });
};

displayFuelCapacity()

The forEach() iterator method is an array method. You are calling it on the array, Airplane.availableAirplanes. That array has 2 elements. Each one is an object with 2 properties. With the first iteration of the forEach() method, the first element which is this object: {name: 'AeroJet', fuelCpacity: 800} is assigned to the parameter, element, followed by the second object in the array on the second iteration. Since element is assigned to each of the objects in the array, you can access the properties of those objects as you did here:

1 Like

Ah ok, so for example element in element.name in the function is not becoming availableAirplanes.name, but just a place holder for an unnamed object ( {name: 'AeroJet', fuelCpacity: 800} )?

2 Likes

Yes.