0

I am trying to get the value of this.userId while inside the second for loop, it throughs undefined. Have a look at the code below:

 //the following variable gets undefined inside the second for loop
  this.userId = localStorage.getItem('userId');

  this.reviews.forEach(function(element1){

    element1.usersWhoLike.forEach(function(element2) {

   if(element2 == this.userId){
       //this throughs undefined !!
       console.log('UserID is : ',this.userId)
   }

  });

  });
Hamza L.
  • 1,783
  • 4
  • 25
  • 47

3 Answers3

2

You missed scope of function inside forEach Let's try:

this.reviews.forEach(function(element1){

    element1.usersWhoLike.forEach(function(element2) {

   if(element2 == userId){
       //this throughs undefined !!
       console.log('UserID is : ',this.userId)
   }

  }, this);

  }, this);
taile
  • 2,738
  • 17
  • 29
  • It worked! But how ? – Hamza L. Apr 23 '17 at 16:10
  • 1
    @HamzaL. The 2nd argument given to `.forEach()` controls the value of `this` inside the iterator `function`s. Passing `this` as that argument ensures that all 3 functions (2 iterators and the function surrounding the snippet) use the same value. – Jonathan Lonowski Apr 23 '17 at 16:18
  • @JonathanLonowski Got it, thank you! – Hamza L. Apr 23 '17 at 16:24
  • For more detail. You can see the list parameters here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=example#Parameters – taile Apr 23 '17 at 22:29
0

this.userId in the second one is referring to the function scope itself. Try adding a var self as a reference

    this.userId = localStorage.getItem('userId');

    var self = this; // Referencing
    this.reviews.forEach(function(element1){

        element1.usersWhoLike.forEach(function(element2) {

            if(element2 == userId){
                //this throughs undefined !!
                console.log('UserID is : ',self.userId)
            }

        });

    });
Noobit
  • 411
  • 3
  • 8
0
this.userId = localStorage.getItem('userId');

Put this line inside first loop

Osama
  • 2,912
  • 1
  • 12
  • 15