They allow you to store data values in them for future use. Think about it this way, the variable is like a container where you can put a fruit. In the blue container, you can place an apple; in the yellow container, you can place an orange. When you need to find your orange, you refer to the yellow container.
Variables in JavaScript are declared using var
, let
or const
.
var num;
let num1;
const num2; //Error. It must be initialized
The assignment operator =
is used to give the variable a value. Note = does not mean equal to as in arithmetic.
The semicolon (;) is used in JavaScript like a sentence’s full stop (.). Did you see what I did there? 🙂
It indicates the end of that line of code. The code will run without the semicolon, but it is standard practice to include it.
The keyword var
was used before 2015, and coding for older browsers
var x;
x = 1;
var y = 3;
var num = 100;
Variables can also be declared using a newer convention introduced in 2015, let
and const
The keyword let
is used if the value is likely to change.
let x;
x = 2;
let y = 24;
let num1 = 120;
The advisable method to declare a variable is using the keyword const
. In this case, the value does not change.
const a = 3;
const b = 5;
const num2 = 150;
If you try to change the value of num2, it would result in an error.
num2 = 200 // Error
More than one variable can be declared on the same line of code.
let x = 1; y = 2; z = 3;
Alternatively, it can be written as such
let x, y, z;
x = 1;
y = 2;
z = 3;
Variable names can be simple or more elaborate. Ideally, they should be descriptive. It should describe the value stored in it. For example, if you want to store the price of an apple in a variable. Instead of declaring it as x, which is ambiguous.
const x = 1;
Use
const price = 1;
Even better
const priceOfApple = 1; // The variable is written in camelCase
Variables can store numbers, characters, strings or Boolean values. We will talk about these in the future. Let’s take a look at some more examples.
const firstName = 'John'; // String
let age = 24; // Integer
const loggedIn = true; // Boolean
Rules for naming variables:
- They must start with a letter, an underscore (_) or the dollar sign ($)
- They cannot begin with a number.
- They are case-sensitive; A is not the same variable as a.
- JavaScript uses camelCase.
Top comments (0)