Variables in JavaScript are containers for storing data values. They allow you to store, modify, and use information throughout your program, such as numbers, text, or more complex data types156.
You can declare variables in JavaScript in several ways:
Automatically (not recommended):
x = 5;
This creates a global variable if not declared inside a function, but it’s considered bad practice
Using var
:
var x = 5;
var
is function-scoped and was the traditional way to declare variables before ES6
Using let
:
let y = 6;
let
is block-scoped and is preferred for variables that may change their value
Using const
:
const PI = 3.14;
const
is block-scoped and used for variables whose values should not change
You can assign a value to a variable either when you declare it or later in your code:
let carName;
carName = "Volvo";
Or in one line:
let carName = "Volvo";
Variables can be updated (except those declared with const
)
myVar
and myvar
are different).function
or class
) cannot be used as variable names