Variables

JavaScript has 4 ways of defining variables:

General information on variables:

  1. Always define variables
  2. Always use const if the value should not change
  3. Always use const if the type should not be changed (Arrays or Objects)
  4. Use let only if you can’t use const
  5. Use var only if you must support old browser

Automatically

The variable will be defined on first use

x = 5;
y = 6;
// x and y now are defined
z = x + y;

It is considered good programming practice to define the variable before use

Var

The var keyword was added to JavaScript from 1995 to 2015

var x = 5;
var y = 6;
// x and y are already defined
var z = x + y;

let and const were added in 2015, var should be only used when a old browser is used.

Let

let x = 5;
let y = 6;
let z = x + y;

Const

The const is used to define a constant variable, one who’s value doesn’t change once defined.

const x = 5;
const y = 6;
const z = x + y;

Let or Const

It’s prefered to use const for only constant variables (those that won’t be changed), and let for all other variables.

// Pi never changes, so it's a constant
const pi = 3.14;
// x could change
let x = 5;

2025-02-14