If You Cannot Name All 5 JS Scopes You Need To Watch This Video

Поділитися
Вставка
  • Опубліковано 29 сер 2024

КОМЕНТАРІ • 91

  • @xcoder1122
    @xcoder1122 2 місяці тому +38

    JavaScript does not have a script scope, that's a term made up by Google.
    JavaScript originally had only two scopes, local and global. Local was the scope inside a function and global was the scope outside a function. Note, however, that in JS, `var' identifiers could not exist in "thin air", they always had to be attached to some kind of object. In a local scope, they were attached to the current function (which is why they are available everywhere in the function, no matter in which block they are defined), and in a global scope, they were attached to `window'. This is also why there was no block scope originally, because a block is not an object and therefore you couldn't attach a variable to it.
    As JS evolved from a primitive website control language to a standalone programming language, which is actually correctly called ECMAScript (but the name JavaScript cannot be killed, it seems), things had to change. The first change was that the existence of `window` was no longer a requirement, since there may not even be a window object in your application. But when defining a global `var`, it still had to be attached to some object. This was the birth of `globalThis'. Note that in a global context, `this` always refers to `globalThis`, but inside an object function, it refers to the object, that's why there is `globalThis`. Also note that in a browser context, `globalThis` actually refers to the same object as `window`, but `globalThis` is always there, `window` only in a browser-based context.
    Another change was that there could now be variables that were not attached to an object at all, but only to a scope. This allowed for block scoped variables, which is the third official scope of the language. You declare these variables as `let` or `const`.
    But what if you create a block-scoped variable in a global context? Whether you declare a global variable with `var` or with `let`/`const` is irrelevant, in the language model they are both global variables in global scope. The only difference is that when you use `var` this variable is attached to `globalThis` and when you use `let`/`const` it isn't. When a global variable is attached to `globalThis`, Google calls it "global scope", and when it isn't, Google calls it "script scope", but that distinction doesn't exist anywhere in the language specification. Again, they are both global scope variables, just one is attached to a global object and the other one is not.
    My recommendation is: just never use `var`. There is no reason why you would ever need to use it. Any code can be written to work just fine using `let` and `const`, and if you really need to attach something to `globalThis`, you can always do so explicitly by writing `globalThis.whatever = ...`. By not using `var', there is no longer a local scope, and there is no distinction between global and script scope. You end up with only two scopes: block scope and global scope.

    • @lassebrustad
      @lassebrustad 2 місяці тому +1

      some projects still runs up to ES5, thus requiring "var" to be used. projects like that might even be the most updated version available, like some C# libs. a lib like that is used at my job, because it's literally the one found to fit the backend the best, otherwise, it would most likely require development of a custom solution, which could be extremely expensive compared to just accepting that "var" works, even tho "let" and "const" are better
      old systems, or systems based on advanced libs that doesn't bring the latest features, should not result in unnecessary development, nor does it mean that older standards should be forgotten. it's annoying to go back to old standards, when used to the newer ones, but it's better than needing something that would require a lot of development and would cost a lot for the company

    • @xcoder1122
      @xcoder1122 2 місяці тому +5

      @@lassebrustad If you can only use ES5, then there are still only two scopes, global and local, and in that case you just use `var' anyway because you have to, so the question of what to use doesn't even arise, nor does the question of which scope to use arise, since there will always be only one scope that makes sense (always local, unless you need global access to something). And what libraries use internally doesn't matter; a library can still be ES5 and use `var` everywhere, that doesn't mean you have to if the interpreter that will run the code supports ES6 or newer. There is no requirement that all code in a project use the same ES version, and there is no requirement that new code added to a library that was ES5-compatible still has to be ES5-compatible, unless you really want to use it on a system that truly only supports ES5. Nor do you have to replace all old code, just write new code using a newer standard version.
      Yet keep in mind that there is no browser released after 2016 that does not support ES6 and using a browser that is 8 years old or older puts your computer at huge risk and if it is a corporate computer, it puts your entire company at risk because the amount of unfixed security issues in such an old browser will be huge and by just opening the wrong web address once, an attacker takes over your entire corporate network. Aside from the fact that also modern HTML, CSS or TLS features are missing. Also, the first version of Node.js that supported ES6 was 4.x, released in 2015, and even as an LTS version, it hasn't received any patches since 2018.
      And finally, I would not use JS at all, unless someone really forces you to do so. I'd always use TypeScript. In TypeScript you can always use `const`/`let`, regardless of what JS version you choose to deploy to. If that JS version only supports `var`, the TS compiler will translate that for you. If just replacing `const`/`let` with `var` would lead to problems, it will also fix those problems for you. Keep in mind that TS just is JS with syntactical sugar on top and after compilation, it's just normal JS code but the TS compiler can find a lot of issues at compile time that JS interpreter cannot find unless the code is truly executed, it will emulate new JS features for old JS deployment targets, it has native enums, it supports optional strong typing, and so on.

    • @lionelritchie1195
      @lionelritchie1195 2 місяці тому +2

      Thanks for putting the effort of explaining it in even more depth, such an interesting read 👍

    • @jaypratap3888
      @jaypratap3888 2 місяці тому +5

      This explanation is what I was seeking for. You got in th depth man. Thanks a lot brother, really appreciate your efforts for writing this much. A Hell lot of repect for you.

    • @LeonC0704
      @LeonC0704 Місяць тому

      Hey man, where can I find you on LinkedIn?

  • @Sahil.1
    @Sahil.1 2 місяці тому +45

    Knowledge of Scope is really essential to crack an interview

  • @7heMech
    @7heMech 2 місяці тому +86

    The only things you need to know are:
    Curly braces {} is a different scope, you can't access variables in scopes from outside, but you can do the opposite.
    You shouldn't use var, use only let and const.

    • @NBGTFO
      @NBGTFO 2 місяці тому +7

      No, it's not the only thing you need to know. Did you even watch the video?

    • @user-ik7rp8qz5g
      @user-ik7rp8qz5g 2 місяці тому +11

      Create var 100 scopes deep. Call this var from another file also 100 scopes deep. Profit

    • @visitforthemusic
      @visitforthemusic 2 місяці тому +7

      var was a language mistake, with hindsight.
      There is no justification to use it in any new code, but you might need to read it and be aware of the special rules if reading old code.

    • @FeFeronkaMetallica
      @FeFeronkaMetallica 2 місяці тому +5

      I would suggest use const only

    • @AmodeusR
      @AmodeusR 2 місяці тому +2

      @@NBGTFO What was the last time you needed to know about script and module scopes?

  • @Patrick3974
    @Patrick3974 2 місяці тому +13

    Great video like always. You're forgetting the Closure scope when you have nested functions.

  • @xSYNDICATEDx
    @xSYNDICATEDx 2 місяці тому

    very perfect videos man. Unlike others i saw this makes it easy to digest takes the time by example and dont gloss over it too fast i subscribed and im chekcing your courses now

  • @svetoslavtrifonov6431
    @svetoslavtrifonov6431 2 місяці тому

    You are explaining things very well, thanks for the video. I would like to see a video about augmenting an existing module in typescript. Also inferencing a complicated types from array of values or inferencing types in general. Thanks again. Great video as always

  • @krzysztofprzygoda7635
    @krzysztofprzygoda7635 2 місяці тому

    Quite interesting things happen in that case - if you "redeclare" const anywhere in the innerFunction, you lose then outer scope access:
    // Local/Function Scope
    function testFunction(arg) {
    const aTestConst = 'Local const'
    // Function Scope
    function innerFunction() {
    console.log(aTestConst, 'innerFunction')
    const aTestConst = 'Local/Function const' // Uncaught ReferenceError ReferenceError: Cannot access 'aTestConst' before initialization
    }
    innerFunction();
    }

  • @220syedrazamehdirizvi7
    @220syedrazamehdirizvi7 2 місяці тому +1

    brooooo!!!! You need to make Tamagui Tutorial for react native !!!!!!!! plsssss!!!!!!! i cant find any youtube channel that is providing tutorial with example code!!!

  • @ajiteshmishra0005
    @ajiteshmishra0005 2 місяці тому

    Input=
    [
    { id: 1, value: 20 },
    { id: 2, value: 30 },
    { id: 1, value: 10 },
    { id: 2, value: 20 },
    { id: 3, value: 40 }
    ]
    ```
    Output:
    [
    { id: 1, value: 30 },
    { id: 2, value: 50 },
    { id: 3, value: 40 }
    ]
    From where can we learn these complex array and string manipulation questions on JavaScript??
    All these are being asked in React interviews

  • @noahthonyangelomhn851
    @noahthonyangelomhn851 2 місяці тому

    So to sum that up, scopes in javascript is like a ray fish. it can only look to the side and up, but not below. so access variables on the same level and higher level but now below it's level.

  • @pedllz
    @pedllz 2 місяці тому +1

    @8:00 *Local

  • @Bilo_7
    @Bilo_7 2 місяці тому

    this was truely the pure basics

  • @tj-softwaresolution
    @tj-softwaresolution 2 місяці тому

    really nice and informative tutorial

  • @hajimeippo804
    @hajimeippo804 Місяць тому

    Informative

  • @HeyNoah
    @HeyNoah 2 місяці тому

    Best explanations! 🤙

  • @theisoj
    @theisoj 2 місяці тому +1

    nicely explained!

  • @borstenpinsel
    @borstenpinsel 2 місяці тому +2

    Never thought about the difference of script and global. For your own code it doesn't seem to matter. The only difference is that global contains the DOM etc. Seems semantic. Obviously DOM stuff isn't in your script but there is no actual scope boundaries/difference in visibility.
    About the Kyle/Sally, that surprised me a bit, especially since const is supposed to sace you from overwriting a variable. You're not actually doing that, as outside of the block, it's still Kyle, but it might still cause bugs when you expect Kyle.
    Now I wonder if you can access the Kyle variable with something like "super.name" (php has something like this, at least for class inheritance)

    • @user-eg5cg3lk3e
      @user-eg5cg3lk3e 2 місяці тому +1

      Js also has super in class constructor

  • @gauravraj8728
    @gauravraj8728 2 місяці тому

    Great Video😍, Can you also teach us how we can build something similar to shopify like how they handle different theme templates and provide subdomain .

  • @AlJey007
    @AlJey007 2 місяці тому

    I'm going to try before watching (to test myself later): block scope, function scope, module scope, global scope and object scope

  • @doniaelfouly4142
    @doniaelfouly4142 Місяць тому

    Thanks

  • @ifaizanMK
    @ifaizanMK 2 місяці тому

    please make a video on debugging REACT, we can't debug it straightforward like JS. we con't use debugger in REACT

  • @notsoclearsky
    @notsoclearsky 2 місяці тому

    I read the thumbnail as "Coping is hard" and thought to myself "Damn, even he is making relatable content now"

  • @lakshaynz
    @lakshaynz 2 місяці тому

    Thank you

  • @surajitdas6555
    @surajitdas6555 2 місяці тому

    @kyle: do you have any javascript advance course in Udemy? If yes, could you pls provide me a link. Thanks

    • @WebDevSimplified
      @WebDevSimplified  2 місяці тому

      I do not have any courses on Udemy, but I do have my own course outside of Udemy and it is linked at the top of the description of this video.

  • @zwanz0r
    @zwanz0r 2 місяці тому +12

    Damn! The dude is 29. I feel old

    • @friedrichjunzt
      @friedrichjunzt 2 місяці тому

      yeah, he's smart.

    • @Endrit719
      @Endrit719 2 місяці тому

      @@friedrichjunzt he's smart xDDD

    • @lassebrustad
      @lassebrustad 2 місяці тому +2

      well, as a 26 y/o, self-taught web dev, like Kyle was when beginning, learning web dev, or programming in general, is extremely easy these days. the younger, the easier it is to learn new stuff, and knowledge is extremely accessible now, it just requires willpower, motivation and at least some effort at the beginning

  • @mamadouanne1253
    @mamadouanne1253 2 місяці тому +2

    I wanted to buy your courses but they are too expensive for me. 😭😭😭

  • @tobyharnish8952
    @tobyharnish8952 Місяць тому

    "...variables are only accessible inside of the curly braces that they are defined within, and they are never able to be accessed outside of those curly braces" - that is completely not true. Consider this:
    if(true) {
    var a = "Hi";
    }
    console.log(a); // "Hi"
    As others have pointed out, don't use var to create variables. Basically, `var` is not block-scoped.

  • @nage7447
    @nage7447 2 місяці тому

    soo, "js have scopes like no one does" little bit wrong take
    let me compare with c# (the one that i know)
    blok skope - sure, we have it
    local - same, like function or class level
    script - like internal keyword, project level
    global - same, just public keyboard

  • @aiamfree
    @aiamfree 2 місяці тому

    best exercise for understanding this is to build a dispatcher

  • @oortcloud210
    @oortcloud210 2 місяці тому

    In the real world....
    Don't ever use var so ignore that completely.
    Don't ever create global/script variables so ignore that - except the functions and modules of your app but you shouldn't need to worry about scope with these.
    So you end up with just needing to deal and understand the much more logical block-scoped variables.
    Use LET if you have a variable whose value will be changed after initial assignment.
    Use CONST if the variable will never change after initial assignment.

  • @sarma_sarma
    @sarma_sarma 2 місяці тому

    is it good to use var in js now because it's an older js concept right?

    • @WebDevSimplified
      @WebDevSimplified  2 місяці тому +1

      I still don't recommend ever using var, but it is important to know how it behaves differently than let/const when it comes to scoping.

    • @lassebrustad
      @lassebrustad 2 місяці тому

      @@WebDevSimplified at my job, we're using some libraries in the C# backend that can run ES5, so for whatever we write that should run using that library, we have to use "var", which is annoying. "let" and "const" are ES6+

  • @asagiai4965
    @asagiai4965 2 місяці тому

    I wonder what is the scope of a promise

  • @thepetesmith
    @thepetesmith 2 місяці тому +2

    Dropping “essentially” would help sharpen your presentation

  • @polychad
    @polychad 2 місяці тому

    This topic doesn't really warrant such an explanation. Use const whenever you don't anticipate reuse of the namespace inside the same scope, else use let.
    When you see var in old code, realise that it hoists in a function and replace it.

  • @caceresmauro9767
    @caceresmauro9767 2 місяці тому

    I needed to press the like button because it was "199" and my brain was hurting, someone sould exploit that

  • @joselmedrano
    @joselmedrano 2 місяці тому

    Lost me at why Isprogrammer is a script scope and not a global scope like printAge. Guess this is something I'll have to deep dive into because didn't know script scoping was even a thing.

    • @visitforthemusic
      @visitforthemusic 2 місяці тому +1

      Good point. I don't think that was really addressed in the video.
      The difference is just the use of the “function” keyword.
      If the function was instead defined using fat arrow ()=> {}, then it would also be script scope.

    • @WebDevSimplified
      @WebDevSimplified  2 місяці тому +1

      This is because var variables and functions are globally scoped (this is just how JS works) while let/const variables are script scoped. It has to do with how let/const behave differently when it comes to scoping since var and creating a normal function essentially just assigns your variable/function to the window object (when used at the top level of your file).
      If you write the code var a = 1 you can access that variable by writing window.a. If you used const a = 1 instead, though, it would not be assigned to your window object so window.a would give you undefined instead.

    • @joselmedrano
      @joselmedrano 2 місяці тому

      @@WebDevSimplified Thanks for the reply Kyle

  • @theletterq5660
    @theletterq5660 2 місяці тому

    Bro, why haven't you taught us how to make bots!?!

  • @martijn3151
    @martijn3151 2 місяці тому

    The difference between const, let and var is that you never ever should use var.

  • @tahasoft1
    @tahasoft1 2 місяці тому

    No need to if(true){...} you can write the code in a scope like this {...}

    • @alechansen3036
      @alechansen3036 2 місяці тому

      He’s just using it as an example for an if statement and a following code block, I think he knows that

  • @kheepur
    @kheepur 2 місяці тому +1

    Fourth

  • @seedme
    @seedme 2 місяці тому

    I feel i dont really know javascript after this. lol

  • @omega.developer
    @omega.developer 2 місяці тому

    Hey kyle. How are you bro.

  • @veluinfo2006
    @veluinfo2006 2 місяці тому

    3rd 😂

  • @georgegeorgio70
    @georgegeorgio70 2 місяці тому

    second

  • @Pareshbpatel
    @Pareshbpatel 2 місяці тому

    JavaScript Scoping, clearly explained. Thanks, Kyle
    {2024-06-13}, {2024-07-09}

  • @omega.developer
    @omega.developer 2 місяці тому

    Third 🎉😂

  • @NihaalKnightGaming
    @NihaalKnightGaming 2 місяці тому +2

    Who created code javascript, reactjs, nextjs, vuejs, angluar and more. Framework within framework *. All the programing language does the same thing. Imagine having only javascript for web development and make it better really fast. Its time waste to know new lang. In year 2050 dont worry there will be 100+ langs will be released. It dont make it easy but it makes it harder for beginners and waste time for experienced developer like me. xD

  • @hotchaddi
    @hotchaddi 2 місяці тому

    first

  • @malangope
    @malangope 2 місяці тому

    Javascript is such a broken language after decades of adding and patching stuff.

    • @martijn3151
      @martijn3151 2 місяці тому

      It’s not like other languages don’t suffer from that problem. C++ for instance keeps on adding features to the language, but not always for the better.

  • @bukanalie
    @bukanalie 2 місяці тому

    var