Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Essential JavaScript
Introduction
JavaScript Basics
Numbers
Strings
Logic
Variables
Loops
Objects
Arrays
Going Further
Variables with Const
Both let
and const
keywords were added to JavaScript to fix problems with var
.
The const
keyword is identical to let
with one exception:
let
will let a variable changeconst
will keep a variable constant
Think of it this way: if let
creates an open box that you can take things out of and drop other things in, then const
creates a box with something glued inside it.
Once you const
something, you can't reassign it. If you try to reassign it, you'll get an error.
const x = 5; x = 7; // Uncaught TypeError: Assignment to constant variable.
Is a constant still a variable?
You may wonder how the keyword const
still creates variables. Aren't variables supposed to vary? Isn't that the point?
In reality, const
variables can vary. Check out this example:
function sum(num1, num2) { const result = num1 + num2; console.log(result); return result; } sum(2, 3); sum(10, 5);
The variable result
can't change once it is declared. However, each time this function runs the result
variable will still have a different value.
When to use const
Unless we plan on changing a variable, we should define it with const
to help prevent programming mistakes.
If we try to re-declare or re-define a const variable, JavaScript will throw an error so we know that something went wrong. This is good because it gives us a chance to fix our code.
Learning Goals
I know the difference between
let
andconst
I know when I should use
const
instead oflet
Code Editor
Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.
Console Output
0 output lines