Essential JavaScript

Variables

You might be familiar with variables from math equations.

They work the same way in JavaScript, only the computer does all the work:

var x = 5;
var y = x - 2;
console.log(y); // 3

Above, we declared two variables: x and y:

  • x is equal to 5.
  • y is equal to x minus 2.
  • Since x is 5, y is 5 - 2, or 3.

Declaring Variables with Names

We have passed values into functions as arguments like this:

function checkIfYearIsOdd(year) {
  return year % 2 === 0;
}

Notice how arguments allow us to organize pieces of data by giving them names. Naming the argument "year" helps us remember what kind of data is inside it.

Naming our data helps us organize our code better and understand it when we read through it. This is important because we often come back to code later to change it or add new code.

Fortunately, we can name our own variables anywhere in our code using the keyword var and an equals sign (the assignment operator).

Changing Variables

Variables are like boxes with labels. You can put anything in the box. You can even change what's in the box.

Take this example:

var name = 'John'
name = name + ' Doe';
console.log(name);

Above, we declared a variable called name with a value of "John".

We then added " Doe" to that variable. See how the variable changed values?

They are called variables because their values vary or change. We can assign a value to a variable, but we can also change that value later.


Learning Goals

Code Editor