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
- Using
var - 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:
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
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:
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?
-
Always declare variables before using them.
-
Always use const if the value should not be modified.
-
Always use const if the type should not be modified (arrays and objects).
-
Use let only if you cannot use const.
-
Only use var if it MUST support older browsers.
:::
As in algebra
Just like in algebra, variables hold values:
let x = 5;
y = 6;
Just like in algebra, variables are used in expressions:
let z = x + y;
In the previous example, you can guess that the calculated total is 11.
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.
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:
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.)
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:
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:
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:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
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:
<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:
let persona = "Juan Pérez",
nombredelcoche = "Volvo",
precio = 200;
A statement can span multiple lines:
Example:
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:
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:
let x = 5 + 2 + 3;
You can also add strings, but the strings will be concatenated:
Example:
let x = "John" + " " + "Doe";
Try this too:
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:
let x = 2 + 3 + "5";
JavaScript Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:
Example:
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:
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:
-
Declare a variable called city and assign it the value "New York".
-
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.
-
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.
-
Declare two variables length and width, assign them values, and calculate the area of a rectangle. Store the result in a variable called area.
-
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.
-
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.
-
Declare a variable called score and assign it the value 85. Then, decrement the value of score by 5.
-
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.
-
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.
-
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.
-
Create a variable x and assign it the value 10. Then, increment the value of x by 5.
-
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.
-
Create a variable isWeekend and assign it the value false. Then, change the value of isWeekend to true.
-
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.
-
Declare a variable distance and assign it the value 150. Divide this value by 2 and store the result in a variable called halfDistance.
-
Create a variable called
hoursand assign it the value 8. Convert this value to minutes (by multiplying by 60) and store the result in a variable calledminutes. -
Declare a variable
scoreand assign it the value 72. Then, increment the value ofscoreby 28. -
Create a variable
aand assign it the value 5. Then, create another variableband assign it the value 10. Declare a third variableproductand assign it the product ofaandb. -
Declare a variable
numand assign it the value 7. Calculate the cube ofnum(num_num_num) and store the result in a variable calledcube. -
Create a variable
isStudentand assign it the valuetrue. Then, change the value ofisStudenttofalse.
-
The basics:JavaScript Basics
-
JavaScript Operators:Basic JavaScript Operators
-
More about variables:FreeCodeCamp - JavaScript Variables - A Beginner's Guide to var, const, and let.
💻Try these basic JavaScript exercises: