logo
logo

Variables Cheatsheet

What are Variables?

A variable is a placeholder that stores some data or information. In programming, variables are used all the time to store and manipulate data. JavaScript variables are pretty easy because you don't have to worry about types. You can assign variables the same way in JavaScript regardless of the data type.

Declaration and Assignment of Variables

Prior to ES6 (the latest Javascript standard), variables in JavaScript were declared using the
var
keyword, followed by the variable name. To assign a value to a variable, use the equal sign
=
. The syntax for declaring and assigning a variable looks like this:
var myVariable = "value";

Note that the value can be of any data type. Once a variable is declared and assigned, it can be used anywhere else in the code.

Data Types in JavaScript Variables

JavaScript variables can hold different types of data, such as strings, numbers, arrays, and objects. Data types are not explicitly declared in JavaScript, and variables can hold any type of data. Here are some examples:

Strings

var myName = "Chris";

Numbers

var myFavNum = 24;

Booleans

A Boolean variable can have one of two values: true or false. This type of variable is useful when you need to check if something is true or false, such as whether an app has started or a counter has started.

To declare a Boolean variable, use the
var
keyword followed by the variable name and either true or false. For example:
var isAppStarted = true;
var counterStarted = false;

Arrays

var myArray = [1, "two", 3];

Objects

var myObject = {
  name: "Chris",
  age: 34
};

Null

A null variable is a variable that has no value. It can be used to initialize a variable, or you can declare a variable without assigning a value. To declare a null variable in JavaScript, use the
var
keyword followed by the variable name and
null
. For example:
var myVariable = null;

Undefined

An undefined variable is similar to a null variable, but it is not explicitly set to null. Instead, it has no value assigned to it. To declare an undefined variable in JavaScript, use the
var
keyword followed by the variable name without assigning a value. For example:
var myVariable;
You can later assign a value to this variable with
=
.

Reassignment and Coercion of Variables

In JavaScript, variables can be reassigned to a different value of the same or different data type. This can be done using the assignment operator
=
.
var myName = "Chris";
myName = "Bob";

In addition, JavaScript can convert data types automatically, also known as coercion. For example, if you concatenate a string and a number, JavaScript will convert the number to a string.

var myString = "Hello";
var myNum = 1;
var myStringNum = myString + myNum;
// Output: "Hello1"

Variable Scope in JavaScript

In JavaScript, variables can have different scopes. A variable's scope determines where the variable can be accessed in your code.

Global Scope

A variable declared outside of a function has global scope. This means it can be accessed from anywhere in your code, including inside functions.

For example:

var myName = "Bob";

function sayName() {
  console.log(myName);
}

sayName(); // Outputs "Bob"

Local Scope

A variable declared inside a function has local scope. This means it can only be accessed within that function.

For example:

function sayName() {
  var myName = "Bob";
  console.log(myName);
}

sayName(); // Outputs "Bob"

console.log(myName); // Throws an error because myName is not defined

It's important to note that it is not a good practice to re-declare variables with the same name. This can lead to confusion and errors in your code.

Reserved Keywords

There are several keywords in JavaScript that are reserved and cannot be used as variable names. These include:

  • class
  • const
  • let
  • var
  • true
  • false
  • null
  • undefined

If you try to declare a variable with one of these reserved keywords, your code will throw an error.

Naming Rules for Variables in JavaScript

In JavaScript, variable names can only contain letters, numbers, underscores, and dollar signs. Variable names cannot start with a number, and they cannot be a reserved keyword.

For example, the following variable names are valid:

var myName = "Bob";
var _myName = "Bob";
var $myName = "Bob";
var myName123 = "Bob";

And the following variable names are invalid:

var 123myName = "Bob"; // Invalid: cannot start with a number
var class = "Bob"; // Invalid: reserved keyword

Function Scope in ES5 and Earlier Versions of JavaScript

In ES5 and earlier versions of JavaScript, variables are function-scoped. This means that no matter where you declare your variable inside your function, you always have access to that variable even if you shouldn't. This can cause headaches down the road, especially if you have a complicated function with nested if statements or accidentally reassign the variable.

The Problem with Function-Scoped Variables

To demonstrate the problem with function-scoped variables, let's write a simple function that declares a variable and an if statement. We'll use
var
to declare the variable:
function sayHi() {
  var shouldSayHi = true;
  if (shouldSayHi) {
    var myName = 'Chris';
    console.log('Hi ' + myName);
  }
  console.log('This should be out of scope: ' + myName);
}

sayHi();
If we run this code, we'll see that it works just fine. However, if we try to access the variable
myName
outside of the if statement, it still works even though it shouldn't. This is because variables declared with
var
are function-scoped.

Block Scope in ES6 with let and const

To solve this problem, ES6 introduced
let
and
const
.
let
is similar to
var
but is block-scoped, meaning that the variable is only accessible within the block it is declared in. Let's rewrite the above function using
let
:
function sayHi() {
  let shouldSayHi = true;
  if (shouldSayHi) {
    let myName = 'Chris';
    console.log('Hi ' + myName);
  }
  console.log('This should be out of scope: ' + myName);
}

sayHi();
If we run this code, we'll see that it throws an error because
myName
is out of scope. This is because we declared
myName
with
let
, which is block-scoped.

Differences between let and const

const
is similar to
let
in that it is also block-scoped. However, it cannot be reassigned once it is declared. This makes it useful for storing data that you don't ever want to reassign. Here's an example of using
const
:
const myName = 'Chris';
console.log('My name is ' + myName);

myName = 'Bob'; // This will throw an error
If we try to reassign
myName
, it will throw an error because it is a constant.

Mutating Data with Const

Although
const
variables cannot be reassigned, the data inside a
const
variable can be mutated. This means that we can modify the properties of an object or the elements in an array that is stored in a
const
variable. This is because the variable is pointing to the memory location of the data structure, rather than the data structure itself.

Let's take a look at an example:

const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]

const myObject = { name: "Chris" };
myObject.name = "Bob";
console.log(myObject); // Output: { name: "Bob" }
It is important to note that while we can mutate the data inside a
const
variable, we cannot reassign the variable to a new value. This is because
const
variables are assigned to a fixed memory location, which cannot be changed.
However, it's important to exercise caution when using
const
variables, especially with complex data structures such as objects and arrays. Modifying the properties of an object or elements in an array can lead to unexpected behavior if not done carefully.

For example, consider the following code:

const person = { name: 'John', age: 30 };
person.age = 31;

console.log(person); // Output: { name: 'John', age: 31 }
In this example, we declare a
const
variable
person
and initialize it with an object containing
name
and
age
properties. We then modify the
age
property of the object to
31
. This works because we are not reassigning the
person
variable, but rather modifying the data structure it points to.
However, if we try to reassign the
person
variable to a new object, it will throw an error:
const person = { name: 'John', age: 30 };
person = { name: 'Jane', age: 25 }; // Error: Assignment to constant variable.
In this example, we are trying to reassign the
person
variable to a new object. Since
person
is a
const
variable, we cannot do this and it will throw an error.
In general, it is good practice to use
const
for variables that should not be reassigned, and
let
for variables that may need to be reassigned. By following this convention, we can write more maintainable and less error-prone code.