Variables

Variables

What is a variable?

You can use a variable to make several references to the same piece of data. Variables are defined in JavaScript using the var keyword.

Variable declaration

var variableName = value;

EXAMPLE

var name = "Zoe";
var postLiked = "false";

Variables can be declared with no value and then with a value. Variables can also be assigned to more variables.

Variable scoping

Scope determines the usage of a variable. There are 3 types of scope:

  • Global scope: This scope can be used throughout the whole code. The global scope uses var.

EXAMPLE

var myGlobalNumber = 6;
  • Local scope: This scope can only be used in the declared location of the code. The local scope uses let.

EXAMPLE

let myLocalNumber = 12;
  • Constant: This scope is similar to the local scope. It cannot be used outside the location. The constant uses const.

EXAMPLE

const myConstantNumber = 24;

DIFFERENCES

varletconst
Can be redeclared and updatedCan be redeclared, but not updatedCannot be redeclared and updated
Hoisted at the top and initializedHoisted at the top, but not initializedHoisted at the top, but not initialized
Global scopedBlock scopedBlock scoped

Summary

You can use a variable to make several references to the same piece of data. There are 3 types of scopes: global scope(var), local scope(let) and constant scope(const).