[solved] Why does it say undefined when I log the value [ts][ionic2]?

public lvl:number = 6;
constructor(public navCtrl: NavController) {   
  console.log('Start Page Constructor');
  setTimeout(function(){
        for(var i=0;i<4;i++){
            console.log(this.lvl);
        }
   }, 5000);
}

I expected the log to be:

6
6
6
6
6

But I’m getting:

undefined
undefined
undefined
undefined
undefined

I do not understand what i’m doing wrong here.

Because your this changes when you use function () {} syntax for callbacks. Use arrow functions to get the correct this:

setTimeout(() => {
    for(var i=0;i<4;i++){
        console.log(this.lvl);
    }
}, 5000);
1 Like