Variables

Basics
Rodrigo Ehlers
29/12/2017

You can think of variables as little bags in which you'll be able to store values.

They're called variables because (in most cases) the value stored in them, is.. well.. variable. For example, you could have a variable which initially stores the value 1 and later on in the sequence of the script that value changes to 2.

The most current version of JavaScript (ES2015 or ES6) supports 3 different types of variables.

  • let
  • const
  • var

All of these can store any value of any data type JavaScript provides or supports and even change the type of data it is holding dynamically. It could for example first store a number and later on a text. You can find more on this on the data types page.

Let's take a closer look at the mentioned variables.

let

This is the type of variable you should and will be using most of the times.

..

const

A constant is a special type of variable whose value cannot be changed after it was initially set.

The constant should be used whenever you know that it won't need to be changed anyway.

// Some examples of constants. 
const WEBSITE_TITLE = 'JS Bible'; 
const FACEBOOK_FOUNDER = 'Mark Zuckerberg'; 
const PI = 3.141;

You may have noticed that I made all constant names upper case. This is a syntax style many developers do. It helps distinguishing constants from variables.

I however only do it if the constant is available to the global scope. Don't worry about scopes yet, we'll come to that later on.

var

This type of variable was the standard one for many years. It did however show some weird behaviour with scopes, which is why let has mostly replaced it.

If we forget scope, var and let behave very similarly. I'll explain the exact difference between the two on the scopes page.

You should not use this type of variable unless you definitely know what you're doing, which I guess you don't.. at least at this point.

© Rodrigo Ehlers 2020 - Built with Gatsby and hosted on Netlify.