Bootcamp Notes – Day 13 (Tues) – Bootstrap: JavaScript Variables: Var, Let, Const
JavaScript Variables: Var, Let, Const
In ES6 (the version of JavaScript released in 2015 with major updates, also known as ECMAScript 2015 or ES2015 but most commonly as ES6), two new variable declaration keywords were introduced: let and const. Previous to this, the only option was var. As noted before, JavaScript is a loosely typed language and you do not specify the data type of a variable when you create the variable with variable declaration.
Let and const are quite similar in many ways, but the one major way in which they are different is that const cannot be reassigned. Let can be reassigned!
Now we type these in below and see what happens:
- it is required to initialize variables declared with const at the time of declaration.
- Let, on the other hand, can be declared without initialization then assigned a value later.
- In general, it is a good idea to use const to declare your variables unless you know that the variable will need to have its value reassigned at some point, in which case you should use let.
- With let and const, they will let you know that the variable name has been used before.
- Scope refers to where a variable is accessible, where it exists.
- Variables declared outside of any code blocks are available from anywhere in the current script, regardless of if they are declared using var, let, or const — this is called global scope.
VAR has function scope!
LET and CONST have block scope!
The scope of variable means where is this variable accessible, where does it exist?
A variable declared outside of any code block has global scope, regardless of if you use let, var, or const
Global scope means it’s available from anywhere in the script.
Any variables that are declared outside of a code block exist inside the code block. But variables that are declared inside of a function block do not exist outside of it.
Best practice is to limit your declarations on the global scope, especially when declared with let or var.
Always Declare Your Variables
JavaScript is unfortunately very forgiving if you forget to declare a variable. Instead of throwing an error as you might expect, it will simply create the variable for you – but regardless of what scope you created it in, it will put that variable in the global scope.
There is a feature in JavaScript called “strict mode” that will prevent you from being able to accidentally use variables without declaring them, among other restrictions. We will not use strict mode in this bootcamp, but you are welcome to read about it here.
So you learned about several differences between var, let, and const, including that the value of const must be initialized at declaration and cannot be reassigned, that var has function scope vs. let and const having block scope, the meaning of global scope and that child scopes inherit the variables of their parent scope, and more.
Additional Resources: