Тёмный

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

Web Dev Simplified
Подписаться 1,6 млн
Просмотров 58 тыс.
50% 1

Опубликовано:

 

27 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 100   
@xcoder1122
@xcoder1122 3 месяца назад
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 3 месяца назад
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 3 месяца назад
@@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 3 месяца назад
Thanks for putting the effort of explaining it in even more depth, such an interesting read 👍
@jaypratap3888
@jaypratap3888 3 месяца назад
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 2 месяца назад
Hey man, where can I find you on LinkedIn?
@Sahil.1
@Sahil.1 3 месяца назад
Knowledge of Scope is really essential to crack an interview
@7heMech
@7heMech 3 месяца назад
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 3 месяца назад
No, it's not the only thing you need to know. Did you even watch the video?
@АлександрГерасимов-с3щ
Create var 100 scopes deep. Call this var from another file also 100 scopes deep. Profit
@visitforthemusic
@visitforthemusic 3 месяца назад
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 3 месяца назад
I would suggest use const only
@AmodeusR
@AmodeusR 3 месяца назад
@@NBGTFO What was the last time you needed to know about script and module scopes?
@Patrick3974
@Patrick3974 3 месяца назад
Great video like always. You're forgetting the Closure scope when you have nested functions.
@xSYNDICATEDx
@xSYNDICATEDx 3 месяца назад
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
@krzysztofprzygoda7635
@krzysztofprzygoda7635 3 месяца назад
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 3 месяца назад
brooooo!!!! You need to make Tamagui Tutorial for react native !!!!!!!! plsssss!!!!!!! i cant find any youtube channel that is providing tutorial with example code!!!
@Bilo_7
@Bilo_7 3 месяца назад
this was truely the pure basics
@pedllz
@pedllz 3 месяца назад
@8:00 *Local
@borstenpinsel
@borstenpinsel 3 месяца назад
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)
@АндрейМаксименя
@АндрейМаксименя 3 месяца назад
Js also has super in class constructor
@zwanz0r
@zwanz0r 3 месяца назад
Damn! The dude is 29. I feel old
@friedrichjunzt
@friedrichjunzt 3 месяца назад
yeah, he's smart.
@Endrit719
@Endrit719 3 месяца назад
@@friedrichjunzt he's smart xDDD
@lassebrustad
@lassebrustad 3 месяца назад
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
@HeyNoah
@HeyNoah 3 месяца назад
Best explanations! 🤙
@theisoj
@theisoj 3 месяца назад
nicely explained!
@hotchaddi
@hotchaddi 3 месяца назад
lol
@hajimeippo804
@hajimeippo804 2 месяца назад
Informative
@ajiteshmishra0005
@ajiteshmishra0005 3 месяца назад
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
@4990UR05
@4990UR05 10 дней назад
For such cases, I find that the simplest approach is to use the Array.prototype.reduce() function. What you need is to: 1. Loop through the array.| 2. Create an empty array for you output. 3. Check if the current object id is in the output array. 4. If not, simply add it. 5. If yes, modify the value by adding the new one. There are a few ways to go about it, but a simple one is the following (given an Input array) const Output = Input.reduce((acc,cur) => { // this will loop like in step 1. const idIndex = acc.findIndex(({id}) => cur.id === id); // check for the id as in step 3. if (idIndex > -1) { acc[idIndex].value += cur.value; // sum the values if it exists, like in step 5. } else { acc.push(cur); // add it if it does not exist, like in step 4. } return acc; },[]) // this is the empty array of step 2. Checking for the index, and adding the elements in the final array, can be done with other ways, but this is a simple approach to help understand the logic. I hope it helps.
@ifaizanMK
@ifaizanMK 3 месяца назад
please make a video on debugging REACT, we can't debug it straightforward like JS. we con't use debugger in REACT
@AlJey007
@AlJey007 3 месяца назад
I'm going to try before watching (to test myself later): block scope, function scope, module scope, global scope and object scope
@gauravraj8728
@gauravraj8728 3 месяца назад
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 .
@cocadoodledoo6346
@cocadoodledoo6346 3 месяца назад
Kaha se ho...
@mamadouanne1253
@mamadouanne1253 3 месяца назад
I wanted to buy your courses but they are too expensive for me. 😭😭😭
@notsoclearsky
@notsoclearsky 3 месяца назад
I read the thumbnail as "Coping is hard" and thought to myself "Damn, even he is making relatable content now"
@nage7447
@nage7447 3 месяца назад
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
@asagiai4965
@asagiai4965 3 месяца назад
I wonder what is the scope of a promise
@aiamfree
@aiamfree 3 месяца назад
best exercise for understanding this is to build a dispatcher
@lakshaynz
@lakshaynz 3 месяца назад
Thank you
@tobyharnish8952
@tobyharnish8952 2 месяца назад
"...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.
@surajitdas6555
@surajitdas6555 3 месяца назад
@kyle: do you have any javascript advance course in Udemy? If yes, could you pls provide me a link. Thanks
@WebDevSimplified
@WebDevSimplified 3 месяца назад
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.
@sarma_sarma
@sarma_sarma 3 месяца назад
is it good to use var in js now because it's an older js concept right?
@WebDevSimplified
@WebDevSimplified 3 месяца назад
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 3 месяца назад
@@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+
@chiemezienduaguba2126
@chiemezienduaguba2126 16 дней назад
nice
@thepetesmith
@thepetesmith 3 месяца назад
Dropping “essentially” would help sharpen your presentation
@caceresmauro9767
@caceresmauro9767 3 месяца назад
I needed to press the like button because it was "199" and my brain was hurting, someone sould exploit that
@theletterq5660
@theletterq5660 3 месяца назад
Bro, why haven't you taught us how to make bots!?!
@seedme
@seedme 3 месяца назад
I feel i dont really know javascript after this. lol
@veluinfo2006
@veluinfo2006 3 месяца назад
3rd 😂
@omega.developer
@omega.developer 3 месяца назад
Third 🎉😂
@hotchaddi
@hotchaddi 3 месяца назад
nice
@Pacvalham
@Pacvalham 3 месяца назад
🥉
@georgegeorgio70
@georgegeorgio70 3 месяца назад
second
@hotchaddi
@hotchaddi 3 месяца назад
haha
@malangope
@malangope 3 месяца назад
Javascript is such a broken language after decades of adding and patching stuff.
@martijn3151
@martijn3151 3 месяца назад
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.
@hotchaddi
@hotchaddi 3 месяца назад
first
@Pareshbpatel
@Pareshbpatel 3 месяца назад
JavaScript Scoping, clearly explained. Thanks, Kyle {2024-06-13}, {2024-07-09}
@bukanalie
@bukanalie 3 месяца назад
var
@oortcloud210
@oortcloud210 3 месяца назад
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 3 месяца назад
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.
@kheepur
@kheepur 3 месяца назад
Fourth
@noahthonyangelomhn851
@noahthonyangelomhn851 3 месяца назад
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.
@svetoslavtrifonov6431
@svetoslavtrifonov6431 3 месяца назад
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
@martijn3151
@martijn3151 3 месяца назад
The difference between const, let and var is that you never ever should use var.
@tj-softwaresolution
@tj-softwaresolution 3 месяца назад
really nice and informative tutorial
@tahasoft1
@tahasoft1 3 месяца назад
No need to if(true){...} you can write the code in a scope like this {...}
@alechansen3036
@alechansen3036 3 месяца назад
He’s just using it as an example for an if statement and a following code block, I think he knows that
@doniaelfouly4142
@doniaelfouly4142 2 месяца назад
Thanks
@joselmedrano
@joselmedrano 3 месяца назад
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 3 месяца назад
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 3 месяца назад
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 3 месяца назад
@@WebDevSimplified Thanks for the reply Kyle
@NihaalKnightGaming
@NihaalKnightGaming 3 месяца назад
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
@omega.developer
@omega.developer 3 месяца назад
Hey kyle. How are you bro.
Далее
Only The Best Developers Understand How This Works
18:32
Learn useReducer In 20 Minutes
20:12
Просмотров 508 тыс.
Kenji's Sushi Shop Showdown - Brawl Stars Animation
01:55
Being Competent With Coding Is More Fun
11:13
Просмотров 80 тыс.
Why Signals Are Better Than React Hooks
16:30
Просмотров 478 тыс.
`const` was a mistake
31:50
Просмотров 136 тыс.
WTF Do These Even Mean
13:44
Просмотров 88 тыс.
All The JavaScript You Need To Know For React
28:00
Просмотров 619 тыс.
20+ Must Know Array Methods That Almost Nobody Knows
11:47
My 10 “Clean” Code Principles (Start These Now)
15:12