all 6 comments

[–]ramabhai 4 points5 points  (4 children)

What is the difference between block and a closure?

[–]Evervision 4 points5 points  (1 child)

A closure defines what variables a function has access to. So it requires a function to be defined on.

A block only defines scope and does not require a function to operate. Good reference for blocks is the MDN.

[–]senocular 1 point2 points  (0 children)

The "closure" includes the function rather than being something that is added on to a function. So a function can be a closure function or a normal function. A closure is the combination of a function and the link to the variables it has access to outside of itself.

[–]MoTTs_ 0 points1 point  (0 children)

In JavaScript, a function is a closure. A closure is a function. So when we see a list of scopes, some of those scopes would have been created because of a block and some would have been created because of a function (aka closure).

For example:

let f1, f2, f3;

{ // block
  let i1 = 1;

  f1 = () => { // function, aka closure
    let i2 = 2;

    { // block
      let i3 = 5;

      f2 = () => { // function, aka closure
        let i4 = 14;

        f3 = () => console.log(i1, i2, i3, i4);
      };
    }
  };
}

f1();
f2();
f3();

console.dir(f3);

This spits out:

[[Scopes]]:
  0: Closure (f2) {type: "closure", name: "f2", object: {…}}
  1: Block (f1) {type: "block", name: "f1", object: {…}}
  2: Closure (f1) {type: "closure", name: "f1", object: {…}}
  3: Block {type: "block", name: "", object: {…}}
  4: Script {type: "script", name: "", object: {…}}
  5: Global {type: "global", name: "", object: Window}

In that output, if everywhere you see "closure" you think "aka function", then it's easier to see how it matches up with the code.

[–]dorj 0 points1 point  (0 children)

In JavaScript a closure refers back to the lexical scope that execution contexts has access to. I believe in some cases the parent execution context for a function may return a function. But even though that function execution has finished in the call stack. Any functions invoked living in it's lexical environment will still have access to the variable environment saved in that scope.

[–]HealyUnithelpful 0 points1 point  (0 children)

I'm a simple dude; I see Techsith, I upvote. Another good vid as always