JavaScript Let vs Var vs Constant | Mosh

Поделиться
HTML-код
  • Опубликовано: 14 май 2018
  • JavaScript Let vs Var vs Constant -
    🔥Get the COMPLETE course (83% OFF - LIMITED TIME ONLY): bit.ly/2KZea52
    Subscribe for more videos:
    / @programmingwithmosh
    Want to learn more from me? Check out my blog and courses:
    programmingwithmosh.com
    / programmingwithmosh
    / moshhamedani

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

  • @sanket_sy
    @sanket_sy 4 года назад +186

    1) "var" is function-scoped, whereas "let" is block-scoped.
    2) Using "var" attaches the variable to the window, whereas "let" prevents it.

    • @Cool94_4u
      @Cool94_4u 3 года назад

      for 2nd point , i think we dont have window object so how does it attaches to it?
      plz correct me if im wrong, im just beginner

    • @Victory_Accomplished
      @Victory_Accomplished 3 года назад

      @@Cool94_4u are you a beginner now I started 3 month ago and your post was 3 month so I just want to know where you are right.

    • @turbo6266
      @turbo6266 3 года назад +2

      also, const is also block-scoped like "
      let"

    • @deepakkumaryadav6009
      @deepakkumaryadav6009 2 года назад

      @@Cool94_4u
      you are bigineer so why you are doing finger bro in hot burner .

    • @harshagarwal00
      @harshagarwal00 Год назад +1

      @@Cool94_4u node uses "global" instead of "window" object

  • @m.u.550
    @m.u.550 6 лет назад +94

    Mosh is the best teacher, calm and friendly voice, perfect speed and flow of speach. There are only a few software teacher, who increases my mood when following the tutorials and he is one of them!

    • @forexdragon
      @forexdragon 5 лет назад

      I cannot agree more with you! Mosh is the best!

    • @yutaitadori7318
      @yutaitadori7318 2 года назад

      @@programmingwithmosh I have seen your full sql course

    • @yutaitadori7318
      @yutaitadori7318 2 года назад

      It's just awesome

    • @plasmaastronaut
      @plasmaastronaut 11 месяцев назад

      yes, he nails it: just the right amount of info, nice pace; creating an easy to understand yet densely packed and concise lesson.

  • @flyingbirds4235
    @flyingbirds4235 6 лет назад +31

    Finally, I understood the difference between var and let. Great video.

  • @memaimu
    @memaimu 4 года назад +105

    I came here to learn about const. I left without that knowledge.

    • @crepkey
      @crepkey 4 года назад +17

      Here is the detailed explanation:
      The 'const' is keyword what we use to declare variables with immutable value. Therefore a const type variable must be initialized during declaration because you can't modify its value later. But this is not true in every cases. For example: If you declare a const type variable which is an object actually you can modify its properties' value and you can add and remove properties (elements) from it, but can't replace the data type of this variable. So you can't change the object to an array. Don't forget: it will stay an object until it is alive. (Same situation with the arrays)
      Const has exactly same scope as 'let' so it has block scope. Therefore it is available between the (next) curly braces where you declared. You can't re-declare it and you can't re-assign (update) its value. The hoist is working with const but it isn't initialized.

    • @ciceroaraujo5183
      @ciceroaraujo5183 4 года назад

      Go back to it and Google all the terminology in videos that will make a great difference sir.

    • @charankumar9897
      @charankumar9897 4 года назад +1

      Will if you declare something with const then you can't change the value in the entire program. Whatever you declare in const it will be constant throughout the code

    • @semisubmersible
      @semisubmersible 3 года назад +1

      Late, but const is just let but you can’t change the value afterwards.

    • @Victory_Accomplished
      @Victory_Accomplished 3 года назад

      The point is this video is talking about let and var not const

  • @codinginflow
    @codinginflow 2 года назад +6

    Short and to the point explanation! Thank you very much! I'm learning JS right now 😁

  • @pranjalijambhule6729
    @pranjalijambhule6729 4 года назад +1

    I was searching everywhere to understand the difference and finally found this video. Really helpful! Thanks for making this video. :D

  • @mikepalazzo
    @mikepalazzo 5 лет назад

    Great video, thank you. So if I declare a variable using let in the global scope, does that have the same scope as the window object?

  • @hardik.motwani
    @hardik.motwani 5 лет назад +1

    The best explanation of let and var keyword so far, Thanks

  • @janus7156
    @janus7156 5 лет назад +130

    You didn't explain what const does.

    • @skalippanbalippan6972
      @skalippanbalippan6972 4 года назад +3

      same as let => block scoped

    • @insideTheMirror_
      @insideTheMirror_ 4 года назад +16

      @@skalippanbalippan6972 nop. const is a constant, it's not a variable.

    • @philheathslegalteam
      @philheathslegalteam 4 года назад +11

      @@insideTheMirror_
      It is a variable. With immutable binding not value.

    • @insideTheMirror_
      @insideTheMirror_ 4 года назад +2

      @@philheathslegalteam Well I am not God here. Unlike you ;)

    • @crepkey
      @crepkey 4 года назад +13

      Here is the detailed explanation:
      The 'const' is a keyword what we use to declare variables with immutable value. Therefore a const type variable must be initialized during declaration because you can't modify its value later. But this is not true in every cases. For example: If you declare a const type variable which is an object actually you can modify its properties' value and you can add and remove properties (elements) from it, but you can't replace the data type of this variable. So you can't change the object to an array. Don't forget: it will stay an object until it is alive. (Same situation with the arrays)
      Const has exactly same scope as 'let' so it has block scope. Therefore it is available between the (next) curly braces where you declared. You can't re-declare it and you can't re-assign (update) its value. The hoist is working with const but it isn't initialized.

  • @TheRonron1994
    @TheRonron1994 4 года назад +1

    What's the concern with var if you really need it althrough out the function scope?

  • @abhishekshah11
    @abhishekshah11 4 года назад

    Where can I find more info about the function encapsulation? Now I'm curious

  • @pouyajabbarisani
    @pouyajabbarisani 4 года назад +1

    Hi Mosh,
    what is the name of your VSCode theme?

  • @MrRossss1
    @MrRossss1 5 лет назад

    Hi Mosh. If var attaches variables to the window/global object where are those declared with let/const attached to if they're not declared inside a block? Thanks, great videos btw

  • @milos5247
    @milos5247 4 года назад

    Hi, what color theme are you using for VSCode? Thanks

  • @Shiva-zy7jq
    @Shiva-zy7jq 4 года назад

    Thanks for this video. Finally understood the difference between var and let

  • @blub579
    @blub579 2 года назад

    Packed with information, but short and concise. great video

  • @ga7853
    @ga7853 5 лет назад

    Thank you so much, that was crystal clear.

  • @kicn
    @kicn 4 года назад

    What a wonderful way to explain. loved it.

  • @RanVargas
    @RanVargas 5 лет назад

    I have to commend you. I have searched for the use of the Var or Let keyword. Currently am ongoing a course but got curious as to why in my course there is only Let and no use of Var nor Conts.

  • @dijiflex
    @dijiflex 4 года назад

    Clear and straight to the point

  • @djBulba
    @djBulba 6 лет назад

    I have a question. I am a UI dev for a web based application company. Now majority of our clients are using very old machines and old browsers which were not updated. If I start converting my JS code from ES5 to ES6, will it cause issues running in those old computers? What is the solution?

  • @kevinpatel5106
    @kevinpatel5106 4 года назад

    first time watching your video, great explanation! Thank you for your help!

  • @RezaMohseni
    @RezaMohseni 5 лет назад +5

    Mosh jan, you should add WHY bloating the "window" let say or other objects with variables and functions is bad. watching your video, a novice would think, "well, why would having access to data outside of a scope bad?!", which is a valid and good question. Otherwise, a very nice video, thanks :)

  • @evans_2103
    @evans_2103 2 года назад

    The best explanation ever! Thank you very much!

  • @tracetv8115
    @tracetv8115 3 года назад

    You spoke at 5:37 about function encapsulation/modules and another video, that will explain this concept. I didn't find this video? Can you please link it or i have to buy the full course first?
    Thanks in advance

  • @xxsaifxx2450
    @xxsaifxx2450 4 года назад

    so should we use them in some cases or avoid using them forever

  • @rohitkumarshrivastava9693
    @rohitkumarshrivastava9693 3 года назад

    Hi Sir!! You said that the variables declared with let keyword is not attached to window object, then where is is stored ? If it is stored is script scope, can you explain the script scope as global scope?

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

    A great and simple explanation of var vs. let. Thank you Mosh.

  • @maulikgevariya3059
    @maulikgevariya3059 2 года назад

    Finally I understood the differance thanks Mosh !

  • @frankvee
    @frankvee 3 года назад +8

    CONST is a 'variable' that cannot be changed. It is a CONSTant. This is useful as a control so that you don't inadvertently make a change to a variable. You can define all your variables as CONST and change them as needed if you find you do need to update them.

  • @tochachochi
    @tochachochi 5 лет назад

    Great content loko. I subscribed by the 3rd video.

  • @sumonchandrashil8406
    @sumonchandrashil8406 4 года назад

    Awesome. I understood very well.

  • @LucasAlmeida-fx6eb
    @LucasAlmeida-fx6eb 4 года назад

    thanks :D quick and well explained!

  • @VOGTLANDOUTDOORS
    @VOGTLANDOUTDOORS Год назад

    ALOT of "javascript gurus" have all made 5-minute videos on the history and distinction between var and const and let, then NEVER actually DEFINED any of these terms, but instead launched into some over-caffeinated babble of code examples where utterly NOTHING was explained, but they're oh-so-proud of themselves.
    YOU alone (so far) took the time to actually DEFINE these terms first: "const", "var", "let" and even "function" and "block" AND even "function-scoped" and "block-scoped". Then you examples were simple enough to make your target audience - PEOPLE NEW TO JAVASCRIPT WHO DON'T UNDERSTAND SOME OF THE CONCEPTS - actually understand the distinction between "function-scoped" and "block-scoped" variables.
    Well done you - you just EARNED yourself another subscriber.
    Cheers,
    -Mark Vogt in North Aurora IL (USA)

    • @Eshwar_nigga
      @Eshwar_nigga Год назад

      Waste of time typing this long😅

  • @SamuelHauptmannvanDam
    @SamuelHauptmannvanDam 3 года назад

    So for, for loops, I should still use var?

  • @jerryrobinson958
    @jerryrobinson958 3 года назад

    This video was well done. Mosh, you tha man

  • @berniecat8756
    @berniecat8756 5 лет назад +6

    Variables in Python also have the same scope as var in JS. I never thought of it as a real problem but I agree that it can sometimes result in bugs.

    • @jathebest2835
      @jathebest2835 Год назад

      Thank you for pointing it out!
      I experimented with the Python code below and it worked.
      def start():
      if x >= 21:
      print("You can drink.")
      else:
      print("You can't drink.")
      x = 23
      start() # You can drink.
      However, I found one interesting thing to notice the subtle difference.
      def start():
      for i in range(5):
      print(i)
      print(i)
      start()
      # Output :
      0
      1
      2
      3
      4
      4
      The difference I found is logically same-written JavaScript code showed "5" at the last, but Python showed "4".

  • @techlightdev
    @techlightdev Год назад

    Great tutorial, I've more understand with it. Thank you

  • @theweb_developer
    @theweb_developer Год назад

    Super helpful you explained it very well.

  • @znoran
    @znoran 2 года назад

    Very good and clear explaination my friend!!

  • @driassasofiane2839
    @driassasofiane2839 Год назад

    i was not good at all in the variables but now im proud of myself thank MR mosh

  • @rupamsutar9299
    @rupamsutar9299 Год назад

    This was an indepth ans to the question.
    Thanks Mosh ❤❤

  • @wotanman7711
    @wotanman7711 4 года назад

    I hate to sound stupid but why if the loop terminates at i < 5 is the sixth var 5 and not 4? I thought the loop terminate. Does this mean the i++ is the last bit of information at the end of the loop however it wouldn't display it on the console? (meaning the value of i at 5 is assigned but not printed?

  • @pranavpatil5849
    @pranavpatil5849 4 года назад +1

    Sir can you please make a video on Closures in JS..

  • @dodgersv3
    @dodgersv3 5 лет назад

    You are awesome Mosh!!!

  • @human151
    @human151 6 лет назад +13

    I bought his js course recently. I’ve tried several courses and can honestly say this is one of the best.
    His explanations are very clear, for the most part. I love his explanations and upbeat attitude.
    I just wish there was some way to ask questions. There is no area for that on teachable, as there is on Udemy.

  • @eduardohernandez552
    @eduardohernandez552 6 лет назад +1

    Really good tutorials!! You should make some courses on udemy! Thank you very much

  • @rolypolyyy
    @rolypolyyy Год назад

    How do I get this view with VSCode and live output to Chrome console? Is this simply tied to an HTML file that's not being shown?

  • @milindkhadse556
    @milindkhadse556 4 месяца назад

    helpful information thank you

  • @prashanttiwari120
    @prashanttiwari120 3 года назад

    Hi Mosh please make tutorial on spring boot and especially spring security .It will be very useful for lots of people , especially of you are doing :)

  • @lukehatcher98
    @lukehatcher98 4 года назад

    god tier explanation thank you, sm

  • @shanmugapriya8562
    @shanmugapriya8562 4 года назад

    how to enable window and global object in node environment?

  • @krishnamalik5563
    @krishnamalik5563 3 года назад

    Whats your color theme in VS Code ??

  • @priyamganguly
    @priyamganguly 3 года назад

    The reference point to the Window object is quite significant. It may cause leaks and overrides. Good thing to know.

  • @OfoeNelson
    @OfoeNelson 3 года назад

    Great video but it would have been nice to have it numbered since it appears to be part of a series.

  • @sarthakgaba1583
    @sarthakgaba1583 4 года назад

    Thank you!

  • @naveedurrehman2931
    @naveedurrehman2931 3 года назад

    love it SIr thank you

  • @petrchutny
    @petrchutny 4 года назад

    Thanks Mosh!

  • @siddharthashankarbarik6370
    @siddharthashankarbarik6370 5 лет назад

    nice explanation ..

  • @petersuba1125
    @petersuba1125 2 года назад

    what if i want to declarate global variable inside of function?

  • @hollenjf
    @hollenjf 4 года назад

    Global and private initialization. Good stuff

  • @gautambedi591
    @gautambedi591 Год назад

    Mosh, You are the best man

  • @gizmo928
    @gizmo928 4 года назад

    So using let is more secure? I’m curious, you would only want to limit the variables scope to only where it will be used/accessed?

    • @drcl7429
      @drcl7429 4 года назад

      Yes. Better Encapsulation.

  • @braco0000
    @braco0000 3 года назад

    Seeing the examples it's all clear... We must NEVER use var. Amazing how easy you make it look

  • @SimarpreetKaur-er1dw
    @SimarpreetKaur-er1dw 2 года назад

    let variables cannot be read/written until they have been fully initialized, which happens when they are declared (if no initial value is specified on declaration, the variable is initialized with a value of undefined).
    This differs from var variables, which will return a value of undefined if they are accessed before they are declared.

  • @Steffi5376
    @Steffi5376 3 года назад

    I don't have time to watch all the other lectures or watch till I find what he said so can someone tell me how to prevent a 'function' from being added into window? Thanks in advance

  • @iftikharulmulk4405
    @iftikharulmulk4405 3 года назад

    Marvelous bro marvelous

  • @ytmrdk
    @ytmrdk 4 года назад

    THANKS!

  • @Brian-bo2fu
    @Brian-bo2fu 5 лет назад +2

    The question is where do those variables declared using let or const go?? Somewhere in the memory?

    • @speedysense5061
      @speedysense5061 5 лет назад +1

      Yes, JavaScript are stored in two places: stack (local context) and heap (store dynamically).

    • @speedysense5061
      @speedysense5061 5 лет назад

      You can subscribe our new post or follow us on speedysense.com/var-vs-let-vs-const-in-javascript/

  • @moazelsawaf2000
    @moazelsawaf2000 4 года назад

    Thanks a lot

  • @Levelonesucks
    @Levelonesucks 4 года назад

    I'm at complete beginner level, been learning only for a couple hours. So I don't know enough to know why you would even want to have variables be block scoped instead of having all variables be global and each of them having a different name. To me seems like the latter would be easier to work with so I can remember what each variable does better but I since i'm so new I will just trust you.

  • @appstocks5956
    @appstocks5956 Год назад

    What theme is he using?

  • @naadir9680
    @naadir9680 4 года назад

    thanks a lot

  • @kondasomu
    @kondasomu Год назад

    Hi sir,I have a doubt when using const keyword value will not change but when I use like this value is changing for 'const' keyword. code is: const x = { name: "scott"}; x.name = "john"; console.log(x); Result:john. Why const is printing john instead of scott. Can you please give me reason.

  • @code-island
    @code-island 4 года назад

    well explained

  • @muhdamin340
    @muhdamin340 3 года назад

    what is his apps ? what name of that apps? i

  • @yekularajasekhar2206
    @yekularajasekhar2206 3 года назад

    Great video

  • @iq0578
    @iq0578 3 года назад +1

    Very clear explanation, but I don't understand the why var is a problem at 3:13

  • @Markkkkkkkkkkkkkkkkk
    @Markkkkkkkkkkkkkkkkk 4 года назад +2

    I know it is VERY confusing because var and let are EXTREMELY THE SAME
    But they are a difference
    That for example, var x="john" ;
    x is defined in your whole code, not only in this block
    And you may change it depends on how you want and you can't use x in other functions
    let x="John"
    Defines x only in your code block
    And you can only make it work by putting the method for example console.log inside of the curly braces of the function they're in it

  • @petrospetrosyan1414
    @petrospetrosyan1414 4 года назад +1

    What's the difference between using “let” and “var”?

  • @mohitnegi724
    @mohitnegi724 5 лет назад

    Finally. I got it.

  • @manuelcasares7270
    @manuelcasares7270 3 года назад

    For some reason
    var apple = 'apple';
    console.log(window.apple)
    throws undefined, like It is not attaching apple to the window object..

  • @suhedaerturk215
    @suhedaerturk215 4 года назад

    Mosh is the best!!!

  • @gaminginn6072
    @gaminginn6072 3 года назад

    why we even have var then? What's their purpose/adventage of it if any

  • @equality9304
    @equality9304 5 лет назад

    10/10 your performance

  • @mudasirh1404
    @mudasirh1404 3 года назад

    const is also block-scoped, but It can't be reassigned. You can modify them but can't reassign them.

  • @cicerofonseca8604
    @cicerofonseca8604 5 лет назад

    Awesome...you explained it so simple. Finally, I got the difference!

  • @1988naveensaini
    @1988naveensaini Год назад

    Love You bro

  • @bigbadcatbigbcy2933
    @bigbadcatbigbcy2933 5 месяцев назад

    3:35 I dont know why is that a problem. I mean I know when the codes get complex it will be hard to manage the window stuff but sometimes if it's neccesary to use it, it can be used in my opinion

  • @mounirkanane8083
    @mounirkanane8083 2 года назад

    What about constant?

  • @mnageh-bo1mm
    @mnageh-bo1mm 5 лет назад

    what if you just used
    test = 'color';

  • @urielhd1516
    @urielhd1516 2 года назад

    thx

  • @chandankumarthakur7182
    @chandankumarthakur7182 5 лет назад +4

    let sayHi =function() { console.log('hi');}

    • @Himanshu_Sharma..
      @Himanshu_Sharma.. 4 года назад

      Nice one my friend 👍👊👌 I understood what you were communicating

  • @yamaikaguya5550
    @yamaikaguya5550 4 месяца назад

    its uniqueee

  • @pilotandy_com
    @pilotandy_com 6 лет назад +1

    So what if I just say:
    color = 'red';
    No var, let, or const?

    • @coastalsandwich
      @coastalsandwich 6 лет назад +4

      Andrew Craner it becomes pretty much global

    • @pilotandy_com
      @pilotandy_com 6 лет назад

      Thanks! I just tried it, and you're right. I didn't see any difference between var and no qualifier.

    • @coastalsandwich
      @coastalsandwich 6 лет назад

      The difference is that var is limited to the function scope, while without it the variable will become global inside and out the functions scope. I might be incorrect there, so double check :) not using let or var is a bad idea

    • @ayazhussain7109
      @ayazhussain7109 6 лет назад

      Now color will be available to the whole execution environment.

  • @yuriaugusto1084
    @yuriaugusto1084 2 года назад

    After watching this and searching a lil bit, i think it's wrong to try to use let for everything, since var is function-scoped and let it's block-scoped so you should use both and not only one, like two for inside of one you need to know the two loops indexs and using let you'll not have this information and not even any result outside of them which is bad since we may need the result of others scope functions inside others functions, we don't have thoose "problems" using C# but i don't agree with using let in every situation, it may give even more bugs than just using var which is like most of the languages work which was what a lot of people were saying about let, let should be only used when you know that you'll not need that variable anymore outside of that situation, btw amazing tutorial, js it's preety cool.
    global variables and function-scoped variables;

  • @virCottoQ37
    @virCottoQ37 4 года назад

    no const :(
    but this video helped me little bit, so thanks anyway :)

  • @taospencer1403
    @taospencer1403 5 лет назад

    Do you know why my event listener is not fireing or console logging Lenny?
    'use strict';
    function intia(){
    window.onload = function(e){
    var submitAdvert = submitAdvert;
    submitAdvert = document.getElementById('Btn2');
    submitAdvert.addEventListener('onClick', function(e){
    console.log('Lenny');
    }) //Second event listener closing ) & function } //
    console.log("Jimmy");
    console.log('Timmy');
    }; //1st Closing function bracket//
    }; //Window onload Closing Bracket//
    intia();
    if anyone else knows please comment....

    • @JoEx2k11
      @JoEx2k11 4 года назад

      It may be late, but if someone else is reading this, I think the problem is that 'onClick' is a method itself (e.g. _submitAdvert.onclick_ ) while in the _addEventListener_ method the 'event' parameter has to be 'click'.

  • @sanjothomas3813
    @sanjothomas3813 3 года назад

    Const??

  • @shashikumar-ut6uu
    @shashikumar-ut6uu 6 лет назад +1

    Please put this course in udemy. I love your videos. You're the best