Essential JavaScript

Utilizing Variables

One of the most important features of variables is their ability to change.

Run this example in the editor:

var x = 3;
x = x + 2;
x;

Here, we declare a variable x with a value of 3.

We then assign x a new value. Now x is equal to x + 2.

First JavaScript evaluates the right side of the assignment operator, x + 2, which is 5. Then JavaScript assigns that value to the variable on the left, x.

When we check the value of x, we see that it is equal to 5.

Using a Variable to Sum

Below are two different ways to write a function that receives four number arguments and adds them together. The first one returns the sum of all four numbers in a single expression. The second example uses a variable called total to add the numbers together and returns that variable.

function sumNumbers(num1, num2, num3, num4) {
  return num1 + num2 + num3 + num4;
}
sumNumbers(-3, 0, 2, 7);
function sumNumbers(num1, num2, num3, num4) {
  var total = 0;
  total = total + num1;
  total = total + num2;
  total = total + num3;
  total = total + num4;
  return total;
}
sumNumbers(-3, 0, 2, 7);

In this example, the first function is more readable. However, there will be times when we need to break our code down into individual operations like in the second example.

As we learn more advanced coding techniques, this will be a useful skill to have in your toolbox.

Using a Variable to Count

A perfect example of how variables give us new abilities in programming is using a variable to count something.

The function below accepts four number arguments. It counts how many of those input numbers are even and returns that total as its result:

function countEvenNumbers(num1, num2, num3, num4) {
  var total = 0;
  if (num1 % 2 === 0) {
    total = total + 1;
  }
  if (num2 % 2 === 0) {
    total = total + 1;
  }
  if (num3 % 2 === 0) {
    total = total + 1;
  }
  if (num4 % 2 === 0) {
    total = total + 1;
  }
  return total;
}
countEvenNumbers(2, 4, 6, 9);

Try passing different numbers into the function to check the result. It can range from 0 to 4 depending on how many of the arguments were even.


Learning Goals

Code Editor