0

I'm trying to build some programs for fun and learning. I have the problem below:

function Hero(name) {
this.name = name;

this.addItem = function(item) {
    this.items = this.items || [];
    this.items.push(item);
};

// .... 

this.viewItinerary = function() {
    this.items.map(function(currItem){
        return currItem;
    });
};

}

var alex = new Hero("Alex");
alex.addItem("Sword");
alex.addItem("Shield");
console.log(alex.viewItinerary());
// returns undefined. why does it not return items in array?

If I replace the return statement with a console.log(currItem) it works. So why is my code returning undefined? Any ideas?

Thanks

Ryan Mc
  • 833
  • 1
  • 8
  • 25
  • 1
    you need to do return this.items.map... but with that map that doesn´t change anything, just a return this.items would be fine – juvian Jun 10 '16 at 15:07

2 Answers2

0

Because your function is not returning anything

try:

this.viewItinerary = function() {
    return this.items;
};

Also Array.map return a new array.

kristjan reinhold
  • 2,038
  • 1
  • 17
  • 34
  • Thanks. I used array.map because I wanted to do something with each item in the array. My idea was that I can return the value from each index with some formatting – Ryan Mc Jun 10 '16 at 15:21
  • Well then it's fine to use Array.map but make sure you return it, also make sure you return inside map callback otherwise nothing will show up. return xx.map(item = > { return item.innerArray.map(inside) => {return inside +1 ; } }) Always be returning :D – kristjan reinhold Jun 11 '16 at 05:50
  • You're answer is too complicated for me. What are all the arrows for ? (=>). A simple variation on my code would have helped but this is confusing me. Is it ES6 or something? – Ryan Mc Jun 11 '16 at 07:58
  • x.map(y => y + 1) is equivalent to x.map(function(y) { return y + 1}); Yes this is ES6 – kristjan reinhold Jun 11 '16 at 08:46
  • Ah ok, thanks for clarifying. I'm still learning old skool JS and the world is moving on :P – Ryan Mc Jun 11 '16 at 14:09
0

map returns a new array, unless you return the result of it the return type of viewItinery is undefined, hence why this line

console.log(alex.viewItinerary());

logs undefined. To fix it, simply add a return

this.viewItinerary = function() {
    return this.items.map(function(currItem){
        return currItem;
    });
};
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • If I simply want to return the value of each array index, how would I do that? Is there a better way than using array.map()? Thanks – Ryan Mc Jun 10 '16 at 15:20
  • array.map has 3 arguments (item, index, array). In if u only wanted bunch of numbers (indexes) array.map((item, index) => index); – kristjan reinhold Jun 11 '16 at 08:48