Learn JavaScript CLOSURES in 10 minutes! 🔒

Поделиться
HTML-код
  • Опубликовано: 9 июн 2024
  • // closure = A function defined inside of another function,
    // the inner function has access to the variables
    // and scope of the outer function.
    // Allow for private variables and state maintenance
    // Used frequently in JS frameworks: React, Vue, Angular
    00:00:00 intro
    00:00:31 example 1
    00:02:19 example 2
    00:07:00 example 3
    00:10:08 conclusion
    // --------- EXAMPLE 1 ---------
    function outer(){
    const message = "Hello";
    function inner(){
    console.log(message);
    }
    inner();
    }
    message = "Goodbye";
    outer();
    // --------- EXAMPLE 2 ---------
    function createCounter() {
    let count = 0;
    function increment() {
    count++;
    console.log(`Count increased to ${count}`);
    }
    function getCount() {
    return count;
    }
    return {increment, getCount};
    }
    const counter = createCounter();
    counter.increment();
    counter.increment();
    counter.increment();
    console.log(`Current count: ${counter.getCount()}`);
    // --------- EXAMPLE 3 ---------
    function createGame(){
    let score = 0;
    function increaseScore(points){
    score += points;
    console.log(`+${points}pts`);
    }
    function decreaseScore(points){
    score -= points;
    console.log(`-${points}pts`);
    }
    function getScore(){
    return score;
    }
    return {increaseScore, decreaseScore, getScore};
    }
    const game = createGame();
    game.increaseScore(5);
    game.increaseScore(6);
    game.decreaseScore(3);
    console.log(`The final score is ${game.getScore()}pts`);

Комментарии • 30

  • @BroCodez
    @BroCodez  7 месяцев назад +7

    // closure = A function defined inside of another function,
    // the inner function has access to the variables
    // and scope of the outer function.
    // Allow for private variables and state maintenance
    // Used frequently in JS frameworks: React, Vue, Angular
    // ---------- EXAMPLE 1 ----------
    function outer(){
    const message = "Hello";
    function inner(){
    console.log(message);
    }
    inner();
    }
    message = "Goodbye";
    outer();
    // ---------- EXAMPLE 2 ----------
    function createCounter() {
    let count = 0;
    function increment() {
    count++;
    console.log(`Count increased to ${count}`);
    }
    function getCount() {
    return count;
    }
    return {increment, getCount};
    }

    const counter = createCounter();
    counter.increment();
    counter.increment();
    counter.increment();
    console.log(`Current count: ${counter.getCount()}`);
    // ---------- EXAMPLE 3 ----------
    function createGame(){
    let score = 0;
    function increaseScore(points){
    score += points;
    console.log(`+${points}pts`);
    }

    function decreaseScore(points){
    score -= points;
    console.log(`-${points}pts`);
    }

    function getScore(){
    return score;
    }
    return {increaseScore, decreaseScore, getScore};
    }
    const game = createGame();
    game.increaseScore(5);
    game.increaseScore(6);
    game.decreaseScore(3);
    console.log(`The final score is ${game.getScore()}pts`);

    • @volkan9799
      @volkan9799 6 месяцев назад

      you can also write like this. (example 2).
      return {
      increment,
      getCount: () => count,
      };

    • @OFAMidoriya
      @OFAMidoriya 24 дня назад

      if you ever redo this video can you explain ex 2 more I understood everything until 4:00 and the same with ex3 every thing was ok until 9:30

  • @benzflynn
    @benzflynn Месяц назад +3

    This is the only video on closures that I see here which *clearly explains the purpose* of closures.
    Nice tip on shorthand form of return statement.
    It's common to use a functional expression for the outer holding function of the closure, i.e.
    _const game = function() {_
    _. . . . ._
    _. . . . ._
    _. function increaseScore (points){_
    _. .}_
    _. function decreaseScore (points){_
    _. .}_
    _. function getScore (){_
    _. .}_
    _._
    _}_
    Then on the calling code, you just reference each of the inner functions with the prefix of the outer one, i.e.
    > _game.getScore()_

  • @rhaissabgl
    @rhaissabgl Месяц назад +2

    the best explanation ever!!!!

  • @haidermansoor4760
    @haidermansoor4760 4 месяца назад +3

    this is the best channel ever. Thanks alot BRO

  • @MrRe-sj2iv
    @MrRe-sj2iv 2 месяца назад

    Outstanding explanation I've ever seen on RUclips about Closure. Thank you so much bro. Keep up your good work.

  • @vallunacoder.wecodetogether
    @vallunacoder.wecodetogether 4 месяца назад

    the best js tutorial I have ever seen!

  • @collinsestell5969
    @collinsestell5969 Месяц назад

    Just...beautifully explained!

  • @raazyaa
    @raazyaa Месяц назад

    What an explanation and what a VOICE !
    thx bro !!!

  • @user-cm8ds7rx6t
    @user-cm8ds7rx6t Месяц назад

    the best teacher, thanks bro!

  • @Ankitsarwal
    @Ankitsarwal Месяц назад +1

    I like the explaining way

  • @doronfeldman5152
    @doronfeldman5152 4 месяца назад +1

    It the best programming channel!

  • @harshjaiswal1634
    @harshjaiswal1634 6 месяцев назад

    I'm following this playlist

  • @juliannafotheringham7101
    @juliannafotheringham7101 3 месяца назад

    so amazing thank you

  • @gauravshrmai1988
    @gauravshrmai1988 7 месяцев назад +1

    superb bro !!

  • @k00lmoh
    @k00lmoh 6 месяцев назад +3

    that brings back memories ngl, of when i was first learning Classes and i just couldn't get them until i understood closures

  • @hongquannguyen5532
    @hongquannguyen5532 2 месяца назад +1

    if there are 3 or 4 functions stack on eachother, would the deep inner function get access to all the outers ?

  • @uzma_azam
    @uzma_azam 3 месяца назад

    Thanks Bro 😊

  • @Martin958
    @Martin958 2 месяца назад

    @4:17 What did you mean by return the object {increment: increment} ? Why would the function be both the property and the value?

    • @DavidFerreira-ld5gp
      @DavidFerreira-ld5gp Месяц назад +2

      It's a feature of JavaScript ES6 called Shorthand Properties.

  • @nemesisxl6736
    @nemesisxl6736 6 месяцев назад

    React tutorials pls!!

  • @AllHailLordMegatron
    @AllHailLordMegatron 27 дней назад +1

    it seems closure works like a class but JS has classes , so why do we use closure ? does anyone know the difference ?

    • @FahimAhamed-oc8nh
      @FahimAhamed-oc8nh 15 дней назад

      We can use closure for small state managements of the elements ,whereas classes are used for more complex stuff

  • @nebularzz
    @nebularzz 6 месяцев назад +1

    wouldn't this also be a closure
    function some_other_function(closure) {
    closure()
    }
    function some_function() {
    let message = "Hello, world!"
    let closure = function() {
    console.log(message)
    }
    some_other_function(closure)
    }
    some_function()

  • @HikaruAkitsuki
    @HikaruAkitsuki 2 месяца назад

    At this point, I have no idea what's the purpose of class if function have this closure.

  • @Cinemas19
    @Cinemas19 6 месяцев назад +1

    what happens when we create lots of closures in our code?

    • @Cinemas19
      @Cinemas19 6 месяцев назад

      It slow-down our application......

    • @chiggywiggy524
      @chiggywiggy524 Месяц назад

      You answered your own question?