02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

var, let, and const: Understanding Variable Scope in ES6

Tutorial: Understanding var, let, and const in ES6

In this lesson, we dive into the essential concepts of variable declarations in ES6: var, let, and const. Each has unique characteristics and use cases, which are fundamental for writing efficient, modern JavaScript.


1. Overview of Variable Scopes

  • var: Traditionally used in JavaScript, var is function-scoped. Variables declared with var are accessible within the function where they are defined but are not confined to block scopes (e.g., within loops or conditionals). This can lead to unexpected behaviors.
  • let: Introduced in ES6, let is block-scoped. It ensures the variable exists only within the nearest enclosing curly braces ({}), such as in a loop or conditional statement, making it safer for block-level declarations.
  • const: Like let, const is block-scoped but has the added restriction that its value cannot be reassigned after initialization. This makes const ideal for defining constants or values that shouldn’t change.

2. When to Use Each Declaration

  • Use var sparingly, as it has function-level scope and can lead to hard-to-find bugs when used in larger codebases.
  • Use let for variables whose values will change, such as counters in loops or flags in conditionals.
  • Use const for immutable values or references, such as configuration settings or constant data.

3. Practical Examples

  1. var Scope:

    function demoVar() {
        if (true) {
            var message = "Hello, var!";
        }
        console.log(message); // Accessible outside the block
    }
    demoVar();
    
  2. let Scope:

    function demoLet() {
        if (true) {
            let message = "Hello, let!";
            console.log(message); // Accessible inside the block
        }
        // console.log(message); // Uncaught ReferenceError: message is not defined
    }
    demoLet();
    
  3. const for Constants:

    const API_URL = "https://api.example.com";
    // API_URL = "https://api.newexample.com"; // Uncaught TypeError: Assignment to constant variable.
    

4. Key Differences

Featurevarletconst
ScopeFunctionBlockBlock
ReassignmentYesYesNo
HoistingYes (undefined initially)Yes (uninitialized)Yes (uninitialized)
Best Use CaseLegacy codeReassignable variablesConstants and references

5. Why let and const Are Preferred

ES6 encourages the use of let and const due to their block-scoping behavior. This leads to:

  • More predictable and manageable code.
  • Reduction of bugs caused by variable shadowing or unintended global scope leakage.
  • Clear intention when declaring variables (const for immutables, let for mutables).

6. Wrap-Up

By understanding the differences between var, let, and const, developers can write cleaner, safer, and more modern JavaScript code. As a best practice, always prefer let and const unless you have a specific reason to use var.

In the next lesson, we’ll explore ES6 string enhancements, such as template literals and multi-line strings, to further enhance your coding skills!

Video Transcript

00:01ES six comes with three distinct data types.
00:04The first data type is var, which I'm sure you already know
00:07how to work with, which has a function scope.
00:11So it basically is available to anything within the scope
00:14of the current function that you're in.
00:18Contrary to that, the let
00:20and cons, which are new, are bounded
00:22by the curly bracket scope, really in many ways.
00:25So they're bounded by internally into the scope
00:28of the whatever element that they're in.
00:30If it's a for loop, if it's an if condition,
00:33or if it's a function for that matter.
00:35The difference between let
00:36and cons is let, is more like a variable besides that fact.
00:40And a constant is for constants, which for things
00:42that you're not going to change once you assign them.
00:45So let's see them in action.
00:49Before we move on, I wanna talk about one more ES six thing
00:52that is really cool, won't take us too long,
00:54but incredibly powerful
00:55and useful to make your application even more efficient.
00:58So to, to showcase this, I'm just gonna go into our client.
01:01So far, we were using our VAR and our VAR per se,
01:05and you know, let me, let me do this.
01:07Inside of our portfolio, our VAR per se,
01:09is basically a variable that we define.
01:11In this case, anything that we define within our
01:14module is private.
01:16So only this has access to it,
01:17no one could gain access to it.
01:19So if I create your VAR and I call it, um, name
01:22and I set it to be, or let's do version right version,
01:26and our version is gonna be 1.0 0.1, let's say,
01:29now there's version by default is completely unavailable.
01:34But the problem with our version is that our version itself
01:38might be changeable
01:39because well changeable, which is a good thing if,
01:42if you want it to be changeable.
01:44But in our case, once I set my version to be version one,
01:47I'm really kind of saying I don't want it to change anymore.
01:50And I wanna show you how do you actually create a situation
01:52where no one could change it.
01:54Now, in, in, in this case, for example, in our version,
01:57I'm just gonna go ahead and I
01:59want to expose it first of all.
02:00So let's go ahead and I'm gonna expose it by publishing it,
02:03by exporting it, export.
02:07Now first of all, if I go to my version and I export it
02:09and I go into my client and I'm just gonna go ahead
02:12and do your console log, console log and I'm gonna try
02:17and gain access to it.
02:18So first of all, if it's exported, I, first of all,
02:21I'm gonna need to gain access to it.
02:23So to do that, I'm gonna go ahead and,
02:25although right now I was, I was loading portfolio
02:27and portfolio item, but portfolio item
02:29doesn't exist anymore.
02:31So let me go ahead here and load in version.
02:34Now if I take in my version
02:35and let me make double check that I wrote it correctly,
02:38version, version that, there we go.
02:41So I, I'm importing my version, right?
02:43Because it's not one of the defaults, it's imported.
02:45Now if I go ahead and I just log that version
02:48and I go ahead into
02:50and look to see what's gonna come out, I'm gonna see
02:53that version 1.01 comes out.
02:56If I go into that version and I say, oh by the way version,
02:59I want you to be version 2.1 from now on.
03:02Now if I do that just before I called that version,
03:05then what's actually gonna happen is, first of all,
03:07because we're working in separate,
03:10because we're moving things from one area to another,
03:14by default they're constants.
03:16So I'm gonna get an error telling me, whoa,
03:18you're not allowed to do that.
03:19Now, in a situation that works perfectly,
03:22that's protecting me from overriding
03:24and changing that version because this is a variable
03:26and if a variable is being exposed, it's treated
03:29as something that shouldn't be changed.
03:31Makes a lot of sense. But what would happen if I tried
03:34to change this variable within my application?
03:37So if I go inside of your end, I type your version
03:39and I completely forgot and in my version I went ahead
03:42and I called it two version two for example,
03:45and it runs again this time around
03:48and lemme just make sure that uh, um,
03:51everything here is kosher.
03:53So automatically because I set it
03:56and assigned it to be with a version, it did not protect me.
04:00So in this case, we could see that we're going
04:01to version two even though I really don't want it to change.
04:05And for that was born, the cons
04:08and cons will basically make sure that if I try
04:10to change it even within my application, it's going
04:13to make sure that it's not, that it is not changeable,
04:16it's gonna throw an error, it's gonna tell me, whoa buddy,
04:19you're not allowed to change this version, which is exactly
04:22what we wanted it to do.
04:24Now there's a few cool things related to to these types
04:28of variables that are different.
04:29So I wanna show them to you.
04:30So if I have your a variable
04:32and I'm just gonna call it um, name
04:35and I'm gonna call it Ben for example,
04:38and I do my console call log of name,
04:42then obviously I have access to the scope.
04:44Now what would happen if I would put a bracket opening
04:48and closing bracket, which really doesn't mean too much
04:51for us and I'm creating here a variable.
04:53If I go ahead and say this
04:55and run my application, I'm still gonna have access to Ben.
04:59Why? Because our variable is defined based on the function
05:03scope that is near it
05:04and the function scope
05:05that is near it is our full portfolio area.
05:09On contrary, if I would use something that's called let,
05:12let is defined based on the last opening
05:15and closing brackets, it literally,
05:17it's a self enclosed area.
05:20So a let on contrary to uh, VAR will not gain access.
05:25So if I try to run that, you'll see
05:26that we don't have a value in there,
05:28we don't have the value Ben inside of it
05:30because we created a let and not a var.
05:33Now the same applies oso for cons.
05:35So if I have your A cons,
05:37A cons is only available within the bounds of the last block
05:41that it was in contrary to variables, VARs
05:45that are available within the function block.
05:47So even if I define here a cons
05:49and I define here a var name two and I set that Ben two
05:55and I try to log it out,
05:56Our name too will be available
05:59but our name shouldn't be available
06:01because it, it is only within the scope
06:04of the black that it's within.
06:05And by the way, you could have it other blacks within here
06:08and they would still have access to the cons,
06:10they would still have access to the var,
06:11but in the case of the var live outside
06:14of that scope as well.
06:15'cause it will live within the this scope really.
06:18So if we give it a try and we run it, we'll see that our,
06:21once it runs, we'll see that Bend two is coming through
06:23'cause it's a var but our first bend is not
06:25because it's a cons same as applies for a let.
06:28So again, cons we never changes let does change,
06:32but its scope is a little bit different.
06:33And this comes really useful mainly in situations such
06:37as we've just worked in where for example,
06:39we're setting here a var but we really don't need a var.
06:42You know, Alet is more than enough
06:44because Alet will make sure
06:45that our variable is scoped only within this area,
06:47which works perfectly for us.
06:50Same is true for our children. Alet is more than enough.
06:54Now generally speaking, our let is enough
06:57because it's within this block, this, this,
06:59this function scope really for that matter.
07:02And in the side of this function scope,
07:03we have access all the way to our children
07:05and that's all we really needed.
07:07Um, and that is really the difference
07:09between become constant Let and var.
07:15In this lecture we saw var constant and let in action.
07:19And in the next lecture we want to just wrap up some
07:22of these E es six topics.
07:23So let's explore a little bit of ES six strings there.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!