A variable provides us with named storage that our programs can manipulate. Variables are used to store information to be referenced and manipulated in a computer program.
In programming, a variable is a value that can change, depending on conditions or on information passed to the program.
Why do we need variables? Answer: To store data
Some example of data types in JavaSript is:
String
The Number type (includes Integers, floating-point numbers, exponential notation, and so on.)
Booleans (true & false)
Undefined type
Null data type
Object data type.
Arrays
The typeof Operator
Naming conventions for variables in JavaScript
The rules for creating an identifier in JavaScript is:
JavaScript variables must be identified with unique names.
Names must begin with a letter
Reserved words (like JavaScript keywords) cannot be used as names
The name of the identifier should not be any pre-defined keyword.
The first character must a letter, an underscore(_), or a dollar sign ($).
Subsequent characters may be any letter, digit, underscore, or any character. Variables are Case sensitive. (y and Y are different variables)
Using let and const
Before 2015, using the var keyword was the only way to declare a JavaScript variable.
But now, JavaScript ES6 (ES6 - ECMAScript 2015) allows the use of the const keyword to define a variable that cannot be reassigned, and the let keyword to define a variable with restricted scope.
Safari 10 and Edge 14 were the first browsers to fully support ES6.
The Assignment Operator
In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
let name = 'Mike'
The "equal to" operator is written like == in JavaScript.
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the let or const keyword:
let carName;
After the declaration, the variable has no value (technically it has the value of undefined).
To assign a value to the variable, use the equal sign:
carName = 'Tesla'
You can also assign a value to the variable when you declare it:
const age = 18
Remember that JavaScript identifiers (names) must begin with:
- A letter (A-Z or a-z)
- A dollar sign ($)
- Or an underscore (_)
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names.