Day 8 : Learning JS fundamentals, Part -3

gauravshekhawat

Gaurav-Shekhawat

Posted on August 21, 2021

Day 8 : Learning JS fundamentals, Part -3

Closures

Closure is when a function "remembers" the variables outside of it, even if you pass that function elsewhere.

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12
Enter fullscreen mode Exit fullscreen mode

The full reference can be found on - MDN

Alt Tefxt

In the above example, the variable question will remian alive, even after 100ms of execution of parent function.

Example - 2

Alt Tdext

Here, the function holdYourQuestion will remember the question, even if it is called at an entire different time on an entire differnet place.

this keyword

It is all about the call, it is not the definition of the function, it is not where the function is, none of that matters, it is only how the function was called that determines where the this keyword will be pointing to.

A this-aware function can thus have a different context each time it's called, which makes it more flexible & reusable.

Alt Texft

Alt dText


DOUBT

Prototypes in js

💖 💪 🙅 🚩
gauravshekhawat
Gaurav-Shekhawat

Posted on August 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Al Shop Fix {Day -27}
100daysofcode Al Shop Fix {Day -27}

September 14, 2021

About Browser {Day - 24}
100daysofcode About Browser {Day - 24}

September 6, 2021

JS Objects {Day -19}
100daysofcode JS Objects {Day -19}

September 1, 2021

Data Types JS {Day -18}
100daysofcode Data Types JS {Day -18}

August 31, 2021