JavaScript Let vs Var vs Constant | Mosh

แชร์
ฝัง
  • เผยแพร่เมื่อ 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

ความคิดเห็น • 186

  • @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 4 ปีที่แล้ว

      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 ปีที่แล้ว +108

    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.

  • @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?

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

  • @milos5247
    @milos5247 4 ปีที่แล้ว

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

  • @TheRonron1994
    @TheRonron1994 4 ปีที่แล้ว +1

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

  • @samithakulatilaka
    @samithakulatilaka 4 หลายเดือนก่อน

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

  • @abhishekshah11
    @abhishekshah11 4 ปีที่แล้ว

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

  • @kevinpatel5106
    @kevinpatel5106 4 ปีที่แล้ว

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

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

  • @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?

  • @evans_2103
    @evans_2103 2 ปีที่แล้ว

    The best explanation ever! Thank you very much!

  • @maulikgevariya3059
    @maulikgevariya3059 2 ปีที่แล้ว

    Finally I understood the differance thanks Mosh !

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

  • @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 :)

  • @pouyajabbarisani
    @pouyajabbarisani 4 ปีที่แล้ว +1

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

  • @techlightdev
    @techlightdev ปีที่แล้ว

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

  • @ga7853
    @ga7853 5 ปีที่แล้ว

    Thank you so much, that was crystal clear.

  • @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?

  • @driassasofiane2839
    @driassasofiane2839 ปีที่แล้ว

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

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

  • @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.

  • @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?

  • @SamuelHauptmannvanDam
    @SamuelHauptmannvanDam 3 ปีที่แล้ว

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

  • @petersuba1125
    @petersuba1125 2 ปีที่แล้ว

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

  • @tochachochi
    @tochachochi 5 ปีที่แล้ว

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

  • @xxsaifxx2450
    @xxsaifxx2450 4 ปีที่แล้ว

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

  • @rupamsutar9299
    @rupamsutar9299 ปีที่แล้ว

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

  • @jerryrobinson958
    @jerryrobinson958 3 ปีที่แล้ว

    This video was well done. Mosh, you tha man

  • @theweb_developer
    @theweb_developer ปีที่แล้ว

    Super helpful you explained it very well.

  • @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.

  • @priyamganguly
    @priyamganguly 3 ปีที่แล้ว

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

  • @znoran
    @znoran 2 ปีที่แล้ว

    Very good and clear explaination my friend!!

  • @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 :)

  • @shanmugapriya8562
    @shanmugapriya8562 4 ปีที่แล้ว

    how to enable window and global object in node environment?

  • @LucasAlmeida-fx6eb
    @LucasAlmeida-fx6eb 4 ปีที่แล้ว

    thanks :D quick and well explained!

  • @milindkhadse556
    @milindkhadse556 4 หลายเดือนก่อน

    helpful information thank you

  • @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😅

  • @braco0000
    @braco0000 3 ปีที่แล้ว

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

  • @krishnamalik5563
    @krishnamalik5563 3 ปีที่แล้ว

    Whats your color theme in VS Code ??

  • @sumonchandrashil8406
    @sumonchandrashil8406 5 ปีที่แล้ว

    Awesome. I understood very well.

  • @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.

  • @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".

  • @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.

  • @muhdamin340
    @muhdamin340 3 ปีที่แล้ว

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

  • @eduardohernandez552
    @eduardohernandez552 6 ปีที่แล้ว +1

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

  • @OfoeNelson
    @OfoeNelson 3 ปีที่แล้ว

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

  • @appstocks5956
    @appstocks5956 ปีที่แล้ว

    What theme is he using?

  • @pranavpatil5849
    @pranavpatil5849 5 ปีที่แล้ว +1

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

  • @gautambedi591
    @gautambedi591 ปีที่แล้ว

    Mosh, You are the best man

  • @naveedurrehman2931
    @naveedurrehman2931 3 ปีที่แล้ว

    love it SIr thank you

  • @petrchutny
    @petrchutny 4 ปีที่แล้ว

    Thanks Mosh!

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

  • @lukehatcher98
    @lukehatcher98 4 ปีที่แล้ว

    god tier explanation thank you, sm

  • @iftikharulmulk4405
    @iftikharulmulk4405 3 ปีที่แล้ว

    Marvelous bro marvelous

  • @gaminginn6072
    @gaminginn6072 3 ปีที่แล้ว

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

  • @siddharthashankarbarik6370
    @siddharthashankarbarik6370 5 ปีที่แล้ว

    nice explanation ..

  • @sarthakgaba1583
    @sarthakgaba1583 4 ปีที่แล้ว

    Thank you!

  • @naadir9680
    @naadir9680 4 ปีที่แล้ว

    thanks a lot

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

  • @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.

  • @yekularajasekhar2206
    @yekularajasekhar2206 3 ปีที่แล้ว

    Great video

  • @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..

  • @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.

  • @iq0578
    @iq0578 3 ปีที่แล้ว +1

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

  • @code-island
    @code-island 4 ปีที่แล้ว

    well explained

  • @ytmrdk
    @ytmrdk 4 ปีที่แล้ว

    THANKS!

  • @cicerofonseca8604
    @cicerofonseca8604 5 ปีที่แล้ว

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

  • @mudasirh1404
    @mudasirh1404 3 ปีที่แล้ว

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

  • @moazelsawaf2000
    @moazelsawaf2000 5 ปีที่แล้ว

    Thanks a lot

  • @bigbadcatbigbcy2933
    @bigbadcatbigbcy2933 6 หลายเดือนก่อน

    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

  • @mohitnegi724
    @mohitnegi724 5 ปีที่แล้ว

    Finally. I got it.

  • @petrospetrosyan1414
    @petrospetrosyan1414 4 ปีที่แล้ว +1

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

  • @1988naveensaini
    @1988naveensaini ปีที่แล้ว

    Love You bro

  • @equality9304
    @equality9304 5 ปีที่แล้ว

    10/10 your performance

  • @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;

  • @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/

  • @mounirkanane8083
    @mounirkanane8083 3 ปีที่แล้ว

    What about constant?

  • @suhedaerturk215
    @suhedaerturk215 4 ปีที่แล้ว

    Mosh is the best!!!

  • @mnageh-bo1mm
    @mnageh-bo1mm 5 ปีที่แล้ว

    what if you just used
    test = 'color';

  • @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'.

  • @urielhd1516
    @urielhd1516 2 ปีที่แล้ว

    thx

  • @sayantaniguha8519
    @sayantaniguha8519 3 ปีที่แล้ว

    for(var i=1;i

  • @virCottoQ37
    @virCottoQ37 4 ปีที่แล้ว

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

  • @yamaikaguyachi
    @yamaikaguyachi 4 หลายเดือนก่อน

    its uniqueee

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

  • @shashikumar-ut6uu
    @shashikumar-ut6uu 6 ปีที่แล้ว +1

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

  • @sanjothomas3813
    @sanjothomas3813 3 ปีที่แล้ว

    Const??

  • @konstantinstefanov365
    @konstantinstefanov365 2 ปีที่แล้ว

    I think you forgot the constant from your title :)