top of page

Variables in JavaScript

Variables is like boxes that you can store things in. In JavaScript we don't store "things" like in real life, but we store data. This can be for example numbers or text. 

It's possible to store the age of a person or a car. We can name the box which contains the number represent age for, well "age". Simple don't you think?

It can be done just like this:

  • const means that this is a constant. A variable that does not change.

  • age is the name of the variable. Names can contain letters, digits, underscores, and dollar signs. Names are case sensitive (Age and age are two different variables)

  • used to assign what's on the left side with what's on the right side.

  • 10 the value we give the variable. In this case a number. 

  • ; semi-colon. In JavaScript, all code instructions should end with a semi-colon. Your code will probably work if you don't use semi-colon, but you can also end up with weird behavior if don't work. Make sure to make it a good habit using semi-colons to end instructions. 

Const or let, that is the question

  • const means that this is a constant. A variable that does not change.

  • let means that this a variable that can change.

Const is great as it does not change. You can rely on that variable to stay the same. Let can change it's value at any time. It can also change it's type.

JavaScript is a dynamic language. It makes your code flexible and open to changes. 

Let us look at an example:

On the first line we make the variable age a string (text). And on the second line we made age a number. This is possible since JavaScript is a dynamic language and since we used let to declare the variable.

Maybe you noticed that we did not use the word let on the second line?

That is because you can only declare the variable one time.

Doing this:

Would result in Error and you would not be able to run your code.

What would happen if we try to reassign a const variable?

It won't work. You will get an Error and the code will stop running.

So, when should you use const and when should you use let? If you use const as default, you will find out that should change it to let when you later on needs to change the value. Or even better, declare a new variable as let that can take the const value. Like this:

As a general rule

​

Use const when you can, and use let when you have to.

What is var?

You might have seen var in other code or other places on the internet. 

Let and const was introduced to JavaScript in 2015. Before that we had only var to declare variables and it had some side effects that was pretty bad. So if you write JavaScript today, only use const and let, no need for var.

If you think about using var, remember:

​

Var, huh, yeah
What is it good for?
Absolutely nothing, uhh

bottom of page