Home > Enterprise >  How can I write this map function in the pre ES6 format?
How can I write this map function in the pre ES6 format?

Time:11-13

Hi I have this map function I found in a tutorial, and I'm interested as to how I'd write this in the old way - i.e writing the word "function" rather than the "=>" arrow format.

const example = spaceships.map((spaceship) => ({
    homePlanet: spaceship.homePlanet,
    color: spaceship.color
}));

I assumed that I could write it like this, but I get an error when adding the extra brackets.

const example = spaceships.map(function(spaceship) ({
    homePlanet: spaceship.homePlanet,
    color: spaceship.color
}));

CodePudding user response:

You have to add a return

const example = spaceships.map(function (spaceship) {
  return {
    homePlanet: spaceship.homePlanet,
    color: spaceship.color
  }
});

CodePudding user response:

const example = spaceships.map(function(spaceship){
    return {
        homePlanet: spaceship.homePlanet,
        color: spaceship.color
    }
});

CodePudding user response:

The arrow function return when the {} is not provides so this syntax () => ({foo: "bar"}) will return the object {foo: "bar"} but when you use a function you need to explicitly return the object

const example = spaceships.map(function(spaceship){
    return {
           homePlanet: spaceship.homePlanet,
           color: spaceship.color
    }
})

CodePudding user response:

Here's your function in old format:

const example = spaceships.map(function(spaceship) {
  return {
     homePlanet: spaceship.homePlanet,
     color: spaceship.color
  }
});
  • Related