Skip to main content

Concepts about variables in JavaScript

Concepts about variables in JavaScript

Learn what variables are in JavaScript, how to declare them correctly using var, let, and const, and their importance in programming. This tutorial teaches you how to use variables efficiently to store and manipulate data in your scripts.

Variables are Containers for Storing Data

JavaScript variables can be declared in 4 ways:

  • Automatically
  • Usingvar
  • Wearing let
  • With const

In this first example, x, y, and z are undeclared variables.

They are automatically declared the first time they are used:

JS
x = 5;
y = 6;
z = x + y;

:::Tip NOTE It is considered good programming practice to always declare variables before using them.

:::

From the examples, you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11
JS
var x = 5;
var y = 6;
var z = x + y;

:::Tip NOTE The var keyword was used throughout JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

:::

Example:

JS
const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variablesprice1 and price2They are declared with the keywordconst

These are constant values and cannot be modified.

The total variable is declared with the keywordlet

The total value may be modified.

:::Tip NOTE When to use var, let, or const?

  1. Always declare variables before using them.

  2. Always use const if the value should not be modified.

  3. Always use const if the type should not be modified (arrays and objects).

  4. Use let only if you cannot use const.

  5. Only use var if it MUST support older browsers.

:::

As in algebra

Just like in algebra, variables hold values:

JS
let x = 5;
y = 6;

Just like in algebra, variables are used in expressions:

JS
let z = x + y;

In the previous example, you can guess that the calculated total is 11.

NOTE

Variables are containers for storing values.

JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing variable names (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.

  • Names must begin with a letter.

  • Names can also begin with $ and _ (but we won't use them in this tutorial).

  • Names are case-sensitive (y and Y are different variables).

  • Reserved words (like JavaScript keywords) cannot be used as names.

NOTE

JavaScript identifiers are case-sensitive.

The assignment operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equals to" operator.

This is different from algebra. The following does not make sense in algebra:

JS
x = x + 5;

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

NOTE

The "equal to" operator is written as == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called strings.

JavaScript can handle many data types, but for now, just think of numbers and strings.

Strings are written in double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a string.

Example:

JS
const pi = 3.14;
let persona = "Juan Pérez";
let respuesta = "¡Sí, soy yo!";

Declaring a Variable in JavaScript

Creating a variable in JavaScript is called "declaring" a variable.

A JavaScript variable is declared using the keyword var or let:

JS
var carNombre;
// o
let nombrecoche;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equals sign:

JS
carName = "Volvo";

You can also assign a value to the variable when you declare it:

JS
let nombredelcoche = "Volvo";

In the following example, we create a variable called carname and assign it the value "Volvo".

Next, we "print" the value within an HTML paragraph with id="demo":

Example:

HTML
<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = nombredelcoche;
</script>

:::Tip NOTE It's good programming practice to declare all variables at the beginning of a script.

One statement, many variables :::

You can declare many variables in one statement.

Start the statement with let and separate the variables with a comma:

Example:

JS
let persona = "Juan Pérez",
nombredelcoche = "Volvo",
precio = 200;

A statement can span multiple lines:

Example:

JS
let persona = "Juan Pérez",
nombredelcoche = "Volvo",
precio = 200;
Valor = indefinido;

In computer programs, variables are often declared without a value. The value can be something that needs to be calculated, or something that will be provided later, such as user input.

A variable declared without a value will have an undefined value.

:::Tip NOTE You cannot redeclare a variable declared with let or const.

:::

This will not work:

JS
let nombredelcoche = "Volvo";
let nombredelcoche;

Arithmetic in JavaScript

Just like with algebra, you can perform arithmetic operations with JavaScript variables using operators like = and +:

Example:

JS
let x = 5 + 2 + 3;

You can also add strings, but the strings will be concatenated:

Example:

JS
let x = "John" + " " + "Doe";

Try this too:

JS
let x = "5" + 2 + 3;

:::Tip NOTE If you put a number in quotation marks, the rest of the numbers will be treated as strings and concatenated.

:::

Now try this:

JS
let x = 2 + 3 + "5";

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Example:

JS
let $ = "Hola Mundo";
let $$$ = 2;
let $myMoney = 5;

The use of the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function of a JavaScript library.

In the jQuery JavaScript library, for example, the main function $ is used to select HTML elements. In jQuery, $("p"); means "select all elements 'p'".

Underscore (_) in JavaScript

Since JavaScript treats the underscore as a letter, identifiers containing \_ are valid variable names:

Example:

JS
let \_apellido = "Johnson";
let \_x = 2
let \_100 = 5;

Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.

Exercise:

  1. Declare a variable called city and assign it the value "New York".

  2. Create a variable num1 and assign it the value 15. Then, create another variable num2 and assign it the value 30. Declare a third variable total and assign it the sum of num1 and num2.

  3. Declare a variable temperature and assign it the value 25. Multiply this value by 9, divide the result by 5, and then add 32 to convert the temperature to Fahrenheit. Store the result in a variable called temperatureF.

  4. Declare two variables length and width, assign them values, and calculate the area of a rectangle. Store the result in a variable called area.

  5. Declare a variable radius and assign it a value. Calculate the area of a circle (π * radius^2) and store the result in a variable called circleArea.

  6. Create a variable called name and assign it your name. Then, create a variable called greeting that contains the string "Hello, " followed by your name.

  7. Declare a variable called score and assign it the value 85. Then, decrement the value of score by 5.

  8. Create a variable called isRaining and assign it the value true. Then, create a variable called weatherMessage that contains the string "It's raining" if isRaining is true, or "It's not raining" if isRaining is false.

  9. Declare a variable called price and assign it the value 100. Then, apply a 20% discount and store the new value in a variable called discountedPrice.

  10. Declare a variable called yearOfBirth and assign it your birth year. Calculate your age by subtracting yearOfBirth from the current year and store the result in a variable called age.

  11. Create a variable x and assign it the value 10. Then, increment the value of x by 5.

  12. Declare a variable num and assign it the value 4. Calculate the square of num (num * num) and store the result in a variable called square.

  13. Create a variable isWeekend and assign it the value false. Then, change the value of isWeekend to true.

  14. Declare a variable firstName and assign it your first name. Then, declare another variable lastName and assign it your last name. Create a third variable fullName that contains the concatenation of firstName and lastName.

  15. Declare a variable distance and assign it the value 150. Divide this value by 2 and store the result in a variable called halfDistance.

  16. Create a variable called hours and assign it the value 8. Convert this value to minutes (by multiplying by 60) and store the result in a variable called minutes.

  17. Declare a variable score and assign it the value 72. Then, increment the value of score by 28.

  18. Create a variable a and assign it the value 5. Then, create another variable b and assign it the value 10. Declare a third variable product and assign it the product of a and b.

  19. Declare a variable num and assign it the value 7. Calculate the cube of num (num_num_num) and store the result in a variable called cube.

  20. Create a variable isStudent and assign it the value true. Then, change the value of isStudent to false.

Exercises

💻Try these basic JavaScript exercises: