Variables

In JavaScript, variables must be declared to be used. Here is an example:

let firstName; // declare
firstName = "Alex"; // initialize
console.log(firstName); // use

let lastName = "Bob"; // declare and initialize
console.log(lastName); // use

Unlike in languages like Java and C++, where you declare a variable by indicating its type, in JavaScript, you must use a variable declaration keyword:

  • let
  • const
  • var

JavaScript is a dynamically-typed language, which means a variable is assigned a type at runtime based on the variable's value at the time.

Dynamic typing means you can also change a variable's type at any time:

let num;
num = 2; // num is a Number
num = "two"; // now num is a String
num = { value: 2 }; // now num is an Object!

If you declare a variable but do not give it a value, its type and value are undefined.

let num;
console.log(num);
console.log(typeof num);

You can use the typeof operator to check the type of a value.

let

A variable declared with let behaves for the most part the way you expect; for example:

  • It throws an error if you use it before it is declared:
    console.log(num);
    let num = 2;
    
  • It throws an error if you redefine it:
    let num = 2;
    let num = "two";
    console.log(num);
    
  • It has a block scope:
    for (let num = 1; num < 10; num++) {
      // do something with num
    }
    console.log(num);
    

const

Declares a read-only named constant.

let firstName = "Alex";
firstName = "John"; // Ok

const lastName = "Bob";
lastName = "Doe"; // Error!

Constants are block-scoped, like variables defined using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared.

An initializer for a constant is required.

const lastName; // Error!
lastName = "Bob";

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable (just that the variable identifier cannot be reassigned).

const numbers = [1, 2, 7, 9];
numbers[2] = 4; // Ok

Prefer const over let: it provides an extra layer of protection against accidentally reassigning your variables.

var

The variable declaration keywords let and const are relatively new additions to JavaScript. The old way of declaring a variable in JavaScript is using var:

var firstName = "Alex";

Variables declared with var are not block scoped (although they are function scoped). Also, no error is thrown if you declare the same variable twice using var.

Don't use var!

Undeclared Variables!

Technically, you can declare a variable in JavaScript without using a variable declaration keyword. Variables defined as such become global variables. This is another cruft from the early days of JavaScript, and it must be avoided.

firstName = "Alex";
console.log(window.firstName);

Using an undeclared variable throws ReferenceError under JavaScript's "strict mode", introduced in ECMAScript 5.

Resources