Javascript Variables

In any programming language, we use variables to store information or data. The Data might be any data that is strings, integer, float etc. As Javascript is Dynamically Typed programming were we don’t specify the type of value to be stored in it. Because it is Dynamically Typed variable data takes many forms and types from initialization till the end of the program.

Initialization of variable is very easy we simple declare var keyword followed by the variable name.


var name="Rakesh";

Variable created with the name name it has Rakesh as data stored in the variable name.
Similarly, we’ll be looking at some more examples.

var student_name="Lohit";
var roll_no=10;
var total_marks=126.5;

We can also declare multiple variables in a single line we just need to separate them using comma and end with a semicolon.

var student_name="Lohit", roll_no=10, total_marks=126.5;

Variable declare with no initial value has to value undefined.

Javascript variable is undefined

Javascript variable is undefined

The undefined in a reserve-word, in javascript, that means the variable is declared but the value is not defined.

Naming Conventions of Variable

  • Variable must not have any special characters except underscore.
  • If a variable name is long then underscored is used to separate the words.
  • Example : student_name, permanent_address etc.
  • Empty spaces between names are not allowed.

New Standard of Variable declarations or EcmaScript Variable declarations

EcmaScript also called as ES in short sets the standard for javascript. Time to time it will introduce new concepts to Javascript.
Till now we know that through var we can define variables. But there are also types of variables such as Global, local and constants variables.

EcmaScript has introduced let and const keyword through which we can also declare variables.

Declare using let

Variable declared using let keyword specifies block-level scope or local variables. These can be accessed inside a function block which outputs
an error if called outside of their scope.

let car="volvo";

We have initialised car="volvo" and updating the value of the variable car="BMW".

Declare using const

Variables declared using const cannot be updated like regular variables. They are constants and variable must be declared and initialised once.
If not then Uncaught SyntaxError: Missing initializer in const declaration the error will be given.

const y
VM1085:1 Uncaught SyntaxError: Missing initializer in const declaration //error
const x = 10; //this is correct way

Top Posts