Like any other programming language, variables in JavaScript are containers for storing different types of values. A variable can be thought of as a container. We can store data into a variable and can refer the data with the help of that variable later.
Variable declaration
Before using a variable, we need to create it first. Creating a variable is called variable declaration. A variable in JavaScript can be declared by using the ‘var’ keyword.
Consider the example given below
<script>
var x;
var car;
</script>
You can also declare multiple variables in a single statement as follows.
<script>
var x, car;
</script>
Rules for variable declaration
While declaring a variable, you should keep in mind that –
- You can not use a JavaScript reserved keyword for a variable name. For example ‘if’ and ‘else’ are two of the keywords. A list of all of the JavaScript Keywords is given in the next section below.
- A JavaScript Variable name cannot start with a number. It can begin either with a letter or with an underscore (_) symbol. For example 1car is an invalid variable but car1, _car are valid variable names.
- Variable names in JavaScript are case sensitive. For example car and CAR are two different variable names and not the same.
Reserved Keywords in JavaScript
Reserved keywords in a programming language is a set of predefined keywords that are meant for the compiler/Interpreter. JavaScript has the following set of predefined keywords-
abstract | boolean | break | byte | case |
catch | char | class | const | continue |
debugger | default | delete | do | double |
else | enum | export | extends | false |
final | finally | float | for | function |
goto | if | implements | import | in |
instanceof | int | interface | long | native |
new | null | package | private | protected |
public | return | short | static | super |
switch | synchronized | this | throw | throws |
transient | true | try | typeof | var |
void | volatile | while | with |
Variable initialization –
Initializing a variable means storing some data or value in it. You can initialize a variable at the time of creation (declaration) or after declaration later.
For example –
<script>
//Initialization after declaration.
var x;
x = 10;
</script>
and
<script>
//Initialization at the time of declaration.
var x = 10;
</script>