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

Sdílet
Vložit
  • čas přidán 1. 07. 2024
  • JavaScript Simplified Course: javascriptsimplified.com/?utm...
    Scoping in JavaScript seems simple at first glance, but JavaScript actually has 5 different levels of scope that can be incredibly difficult to keep track of. In this video I explain everything you need to know about scoping across all 5 layers of scope so you can master scoping for your next project.
    📚 Materials/References:
    JavaScript Simplified Course: javascriptsimplified.com/?utm...
    Scoping Article: blog.webdevsimplified.com/202...
    Debugging Crash Course Video: • The Most Important Ski...
    Let vs Const vs Var Video: • Differences Between Va...
    Let vs Const vs Var Article: blog.webdevsimplified.com/202...
    ES6 Module Video: • JavaScript ES6 Modules
    ES6 Module Article: blog.webdevsimplified.com/202...
    🌎 Find Me Here:
    My Blog: blog.webdevsimplified.com
    My Courses: courses.webdevsimplified.com
    Patreon: / webdevsimplified
    Twitter: / devsimplified
    Discord: / discord
    GitHub: github.com/WebDevSimplified
    CodePen: codepen.io/WebDevSimplified
    ⏱️ Timestamps:
    00:00 - Introduction
    00:37 - Scoping Basics
    06:41 - JavaScript Scoping Levels
    12:23 - How Var Is Different
    #Scoping #WDS #JavaScript

Komentáře • 86

  • @Sahil.1
    @Sahil.1 Před 20 dny +43

    Knowledge of Scope is really essential to crack an interview

  • @xcoder1122
    @xcoder1122 Před 18 dny +21

    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 Před 18 dny +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 Před 18 dny +2

      @@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 Před 10 dny +1

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

    • @jaypratap3888
      @jaypratap3888 Před 6 dny +2

      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.

  • @7heMech
    @7heMech Před 20 dny +78

    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 Před 20 dny +6

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

    • @user-ik7rp8qz5g
      @user-ik7rp8qz5g Před 20 dny +11

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

    • @visitforthemusic
      @visitforthemusic Před 20 dny +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 Před 20 dny +5

      I would suggest use const only

    • @AmodeusR
      @AmodeusR Před 19 dny +2

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

  • @Patrick3974
    @Patrick3974 Před 20 dny +13

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

  • @xSYNDICATEDx
    @xSYNDICATEDx Před 16 dny

    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

  • @HeyNoah
    @HeyNoah Před 19 dny

    Best explanations! 🤙

  • @svetoslavtrifonov6431
    @svetoslavtrifonov6431 Před 18 dny

    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

  • @tj-softwaresolution
    @tj-softwaresolution Před 12 dny

    really nice and informative tutorial

  • @theisoj
    @theisoj Před 20 dny +1

    nicely explained!

  • @noahthonyangelomhn851
    @noahthonyangelomhn851 Před 10 dny

    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.

  • @Bilo_7
    @Bilo_7 Před 7 dny

    this was truely the pure basics

  • @zwanz0r
    @zwanz0r Před 20 dny +12

    Damn! The dude is 29. I feel old

    • @friedrichjunzt
      @friedrichjunzt Před 20 dny

      yeah, he's smart.

    • @Endrit719
      @Endrit719 Před 19 dny

      @@friedrichjunzt he's smart xDDD

    • @lassebrustad
      @lassebrustad Před 18 dny +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

  • @lakshaynz
    @lakshaynz Před 20 dny

    Thank you

  • @pedllz
    @pedllz Před 20 dny +1

    @8:00 *Local

  • @ajiteshmishra0005
    @ajiteshmishra0005 Před 11 dny

    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

  • @gauravraj8728
    @gauravraj8728 Před 20 dny

    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 .

  • @krzysztofprzygoda7635
    @krzysztofprzygoda7635 Před 18 dny

    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();
    }

  • @borstenpinsel
    @borstenpinsel Před 20 dny +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)

  • @surajitdas6555
    @surajitdas6555 Před 19 dny

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

    • @WebDevSimplified
      @WebDevSimplified  Před 19 dny

      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.

  • @notsoclearsky
    @notsoclearsky Před 19 dny

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

  • @AlJey007
    @AlJey007 Před 19 dny

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

  • @sarma_sarma
    @sarma_sarma Před 20 dny

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

    • @WebDevSimplified
      @WebDevSimplified  Před 19 dny +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 Před 18 dny

      @@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+

  • @mamadouanne1253
    @mamadouanne1253 Před 20 dny +2

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

  • @ifaizanMK
    @ifaizanMK Před 19 dny

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

  • @arberstudio
    @arberstudio Před 17 dny

    best exercise for understanding this is to build a dispatcher

  • @asagiai4965
    @asagiai4965 Před 20 dny

    I wonder what is the scope of a promise

  • @220syedrazamehdirizvi7

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

  • @nage7447
    @nage7447 Před 18 dny

    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

  • @caceresmauro9767
    @caceresmauro9767 Před 20 dny

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

  • @thepetesmith
    @thepetesmith Před 20 dny +2

    Dropping “essentially” would help sharpen your presentation

  • @oortcloud210
    @oortcloud210 Před 16 dny

    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.

  • @polychad
    @polychad Před 19 dny

    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.

  • @martijn3151
    @martijn3151 Před 19 dny

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

  • @kheepur
    @kheepur Před 20 dny +1

    Fourth

  • @joselmedrano
    @joselmedrano Před 20 dny

    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 Před 20 dny +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  Před 19 dny +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 Před 19 dny

      @@WebDevSimplified Thanks for the reply Kyle

  • @tahasoft1
    @tahasoft1 Před 19 dny

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

    • @alechansen3036
      @alechansen3036 Před 16 dny

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

  • @theletterq5660
    @theletterq5660 Před 14 dny

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

  • @seedme
    @seedme Před 18 dny

    I feel i dont really know javascript after this. lol

  • @omega.developer
    @omega.developer Před 20 dny

    Hey kyle. How are you bro.

  • @georgegeorgio70
    @georgegeorgio70 Před 20 dny

    second

  • @omega.developer
    @omega.developer Před 20 dny

    Third 🎉😂

  • @veluinfo2006
    @veluinfo2006 Před 20 dny

    3rd 😂

  • @hotchaddi
    @hotchaddi Před 20 dny

    first

  • @NihaalKnightGaming
    @NihaalKnightGaming Před 20 dny +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

  • @malangope
    @malangope Před 19 dny

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

    • @martijn3151
      @martijn3151 Před 19 dny

      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.

  • @Pareshbpatel
    @Pareshbpatel Před 18 dny

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

  • @bukanalie
    @bukanalie Před 19 dny

    var