This site runs best with JavaScript enabled.
Do you love what we do?Become a patronat Patreon❤️

How JavaScript scoping works with var, let and const variables — in 10 minutes

Raymon

Video Blogger

In this blog you will learn how the scope works with the "global scope", "functions", "var", "let", "const" variables. What you can do with it and why it is important to learn this concept.

TLDR

For those who don't like to read, use this list when your doubting which one to choose. If you want to learn this topic in detail, I highly recommend to scroll down.

  • const: try to use this const variable everywhere and always. Except if the variable needs to be changed.
  • let: If the value of the variable needs to be changed, use the let variable.
  • var: Avoid this variable, it can make your application messy and unpredictable because they can be overwritten from everywhere. let and const prevent this by default 👍

Type of scopes

What is the scope? A function is used to create a scope which decides the accessibility and visibility of variables, functions, and objects.

In JavaScript, we have 2 types of scopes.

  • Global scope
  • Local scope

What is the global scope

The global scope is the window object. Which is accessible from everywhere in your application. If you want to make a variable, function or object visible for all other scopes than put it in the global scope.

But be aware not to put everything in the global scope. The window object is already packed with a lot of information. So if you don't need it everywhere put if in a local scope.

What is the local scope

A local scope is created by a function. That function can make variables, objects and inner functions hidden or visible from outside the function.

How to create a scope

To create a scope you only need a function. Where you can put in variables, functions, and objects which then are not accessible outside the function. The only way to make it visible and accessible is by returning them with the return statement.

The "var" variable

The var keyword can be used everywhere. It can contain Strings, Int, Object, Array, Function.

Variables can be used for everything, but also everywhere. You can access a var from inside a function, object, if-else statement, really everywhere!

That maybe sounds cool but can have a big effect on the predictability of a website or web-application.

Globally scoped

A var is or can be globally scoped. Cool to access everything from inside anything! But is that good? There are a few alternatives ahead. They are called let and const and have different behavior than var. But let's talk about that later.

"var" can be changed later

A variable can be defined with a string, later on, reassigned to an integer and later it could be a function. That is the power but also a weakness.

var globalVariable
globalVariable = 'I Love Pizza!'
console.log(globalVariable) // Will be 'I Love Pizza!'
SyntaxError: Unexpected token (1:1) 1 : (var globalVariable ^

Now I defined a global variable (yes I do love pizza :-)), right after it I added a string to it. So you can see, you can define it and later on change it to the other value.

gist:raymonschouwenaar/8b6cd3722179e5c30ab52bdd9b01f6e4?file=var-global.js&highlights=1-3

So guess what, the globalVariable is changed. Sounds cool right! Well If you intended to change it, yes! But if you didn't know that you already used that variable, then it is a problem! There is the weakness!!

Can be locally scoped

Now you can see the danger of globally scoped variables. So if I may advise you, never use globally scoped variables.

;(function() {
  var var1 = 'variable 1 value in parent scope'
  ;(function() {
    // Scope 1
    var1 = 'variable 1 value in scope 1'
    console.log('scope 1: ', var1) // Is 'variable 1 value in scope 1'
  })()
  ;(function() {
    // Scope 2
    var1 = 'variable 1 value in scope 2'
    console.log('scope 2: ', var1) // Is 'variable 1 value in scope 2'
  })()

  console.log('Parent scope: ', var1) // Is 'variable 1 value in parent scope'
})()
console.log('Global scope: ', var1) // Is undefined
SyntaxError: Unexpected token (1:1) 1 : (;(function() { ^

You can make the variable locally scoped, by putting it inside a function. Like the example here, if you execute the function in your console, the last console.log() with "Parent scope" in it, will be changed by the one before it!

The "let" variable

"let" is block scoped

A let variable is block scoped. You can create a scope by any {}. With a function, for and while loop and a lot more.

Finally, a variable type that is not globally but locally scoped! 🎉

"let" can be changed later

A let variable can be changed later, but only if it is in the same scope as where it is declared! It is declared in the other scope, it is just a new variable that is defined.

This example will run in the latest version of Google Chrome (not in Safari)

;(function() {
  let letVar1 = 'Let variable 1 value in parent scope'
  ;(function() {
    // Scope 1
    let letVar1 = 'Let variable 1 value in scope 1'
    console.log('scope 1: ', letVar1) // Is 'Let variable 1 value in scope 1'
  })()
  ;(function() {
    // Scope 2
    let letVar1 = 'Let variable 1 value in scope 2'
    console.log('scope 2: ', letVar1) // Is 'Let variable 1 value in scope 2'
  })()

  console.log('Parent scope: ', letVar1) // Is 'Let variable 1 value in parent scope'
})()
console.log('Global scope: ', letVar1) // Is undefined
SyntaxError: Unexpected token (1:1) 1 : (;(function() { ^

If you tried to paste this snippet into the dev tools console you will see that the parent scope, scope 1 & 2 give different values. That is because it is block scoped. The global scope will give an error that it is undefined.

With the normal var you can just give letVar1 a new value. But since a let can't be redefined later, this is not possible for the let.

If we would forget to assign letVar1 in scope 1, then the console in scope 1 would output "Let variable 1 value in parent scope". Because it will look up to the parent scope.

"let" can't be hoisted

If you try to hoist let variables, then you will get errors. To define a let and give it a value. If you first try to define it and give it a value later, you will end with errors!

The "const" variable

The things that you read about const is that they are immutable. Most people think that it means that you can't change the value, but instead you can change the value. But you can't re-assign the reference to the const itself.

"const" is block scoped

A const is block-scoped, the same as the let variable. In the other scope, you can define the const again. But you can't re-assign the same const in the other scope.

;(function() {
  const constVar1 = 'const variable 1 value in parent scope'
  ;(function() {
    // Scope 1
    const constVar1 = 'const variable 1 value in scope 1'
    console.log('scope 1: ', constVar1)
    // scope 1:  const variable 1 value in scope 1
  })()

  console.log('Parent scope: ', constVar1)
  // Parent scope:  const variable 1 value in parent scope
})()
SyntaxError: Unexpected token (1:1) 1 : (;(function() { ^

In this example, you can see that it is possible to assign a constant with the same name in a different scope with the other value.

"const" can't be re-assigned

;(function() {
  const constVar1 = 'const variable 1 value in parent scope'
  ;(function() {
    // Scope 1
    console.log('scope 1: ', constVar1)
    // scope 1:  const variable 1 value in parent scope
    constVar1 = 'const variable 1 value in scope 1'
    // Is Identifier 'constVar1' has already been declared
    console.log('scope 1: ', constVar1)
  })()
})()
SyntaxError: Unexpected token (1:1) 1 : (;(function() { ^

In this example, you can see that it is not possible to re-assign the same constant with a different value.

"const" can't be hoisted

Because you can't re-assign a const, you know it is not possible to hoist them. For hoisting, you need to re-assign.

Good luck!

If you are learning JavaScript right now, I can imagine that you

If something is not clear or confusing about var, let or const please add your questions to the comments!

Do you love what we do?Become a patronat Patreon❤️
Share article

Subscribe to the Mr Frontend weekly newsletter

Every week I will send you a email to help you: stay motivated, learn new things and the best 3 article's on the web