0

Can anyone help me understand the output of the below small es6 program?

I know the difference between arrow function and normal function.

The Arrow function runs in parent's scope. The Normal function runs in its own scope.

PFB the programme that's confusing me.

function Temp(){
  this.x =99;
  y =88;
  var z =77;

  setTimeout(function(){console.log(this.y+"::",this.x,"--",this.z),5});
  setTimeout(()=>{console.log(this.y+"||",this.x,"--",this.z),5});

  doit(function (){ console.log(this.y+":",this.x,"_",this.z);})
  doit(()=>{console.log(this.y+"|",this.x,"-",this.z);});

  function doit(task){
    this.i =0;
    task();
  }
}

new Temp();

Output

88:: undefined --undefined 
undefined|| 99 --undefined 
88: undefined -undefined 
undefined| 99-undefined

es6 Playground

es6console link Wanted to know the association between variable declaration and function (arrow/normal).

The VOYOU
  • 493
  • 4
  • 12
  • 2
    So what exactly is the question :) – lumio Oct 19 '18 at 20:17
  • Try strict mode (that you always should use) and `y =88` will throw the appropriate error. As well as accessing properties on an undefined `this`. – Bergi Oct 19 '18 at 20:56

1 Answers1

1

If you are not declaring a variable (e.g. not using this.y or one of const, let and var) it is attached to the global scope (for browsers that is window).

When you call an anonymous function, it uses the global scope (window).

I added comments on your code.

function Temp() {
  this.x = 99; // local scope
  y = 88; // global scope (attached on window as it is not declared)
  // this.y is never

  setTimeout(function() { // Scope is window/global
    console.log('log1', this.y + ":::", this.x)
  }, 5);

  setTimeout(() => { // Scope is Temp
    console.log('log2', this.y + "||", this.x)
  }, 5);

  doit(function() { // Because it is an anonymous function
                    // the scope is now that of window
    console.log('log3', this.y + ":", this.x);
  })
  doit(() => { // Arrow function: the scope of Temp
    console.log('log4', this.y + "|", this.x);
  });

  function doit(task) {
    this.i = 0;
    task();
  }
}

new Temp();

So to recap: Always declare variables using const or let. Also for better understanding, use the new class syntax. It is just a syntax sugar, but still helps to make your code better understandable.

lumio
  • 6,606
  • 3
  • 30
  • 50
  • made a small edit to the question can you look again. comments you made regarding the declaration of "y" is really helpful. though one doubt if "y" is declared with-in global scope then it should be accessed by arrow function. shouldn't it? – The VOYOU Oct 19 '18 at 20:36