Declaring Variables in JavaScript

In the last chapter we have discussed about the JavaScript introduction. This chapter demonstrates the about the declaring Variables in JavaScript.
In JavaScript Variables can be defined using the var keyword. The ‘var‘ keyword declares a variable, optionally initializing it to a value just like as:

var varname1 [= value1];

Where varname1 is the variable name and value1 is the initial value of the variable varname1.

– A single declaration
You can declare a single variable as:
var count;

– Multiple declarations with a single var keyword
You can also declare multiple variables in single var keyword, like as:
var count, amount, level;

– Variable declaration and initialization in one statement.
You can also declare and initialize the value of the variable in single statement like as:
var count = 0, amount = 100;

If you do not initialize your variable in the var statement, it automatically takes on the value undefined.

Scope of a declare variable

The scope of a variable declared with var is the enclosing function and if the variable is declared outside of the function then the scope of the variable will be global.

Things to Remember

– In JavaScript, variable can be declared after being used. This is an implicit declaration. See the following code:

count= 2
var count;
// ...
 
// is same as:
 
var count;
count = 2;

– You can also initialize the variable with the ‘null’ when you don’t need to assign the specific value. See the following:

var count= null;
var total = 50;

– The first character must be an ASCII letter or an underscore character. Note that a number cannot be used as the first character.

Avoid Reserved keyword

JavaScript has a number of reserved words that you should not use as identifiers for the variables. The following are the list of the reserved keywords:

break
default
function
return
var
case
delete
if
switch

void
catch
do
in
this
while
const
else
instanceof
throw

with
continue
finally
let
try
debugger
for
new
typeof