Javascript variables and it's data types

How to declare a variable in javascript?

There are 3 types of variable declaration.

First using "var" keyword, which is an old method to declare a variable.

Syntax: - var "Variable Name";
var x;//Now x value is undefined means we not defined the variable yet
var y=5; //Now y value is 5 as we assigned 5 to it

Second, using "let" keyword

let x=5; //Now x value is 5 as we assigned 5 to it

Difference between var and let key-word is variables declared with "let" keyword have block scope but in the case of "var" have function scope.

see the code below

    let i=0;
console.log(i)//Throws ReferenceError:i is undefined

Here scope of i is limited inside the curly braces only. Outside curly braces variable i not available.

    var x=5;


Here the scope of variable x is available inside and outside of the curly braces as variables declared with "var" keyword are hoisted(Only variable declarations moved on top of the function or program) Above code executed like below

var x;

Third, using const, If we declare a variable using the const key-word value which is assigned first will never be updated with other value.

const x=4;
x=5//Throws TypeError: Assignment to constant variable.

Data Types and Type Checking

There are 6 basic data types of variables that can be declared in javascript.


One more data type in ES6 added is "Symbol"[I will cover this data type in my future blogs]. Javascript variables are dynamically typed which means if we declare variable and assign value to it then it will convert that value type.

var x=5;
console.log(x)//Type is Number
x="Ryu" // Type is String

We can check the type of the variables using typeof function

let x=5;
typeof(x) //Number

let x="Ryu";
typeof(x) //String

let x=true;
typeof(x) //Boolean

let x={};
typeof(x) //Object

let x=[];
typeof(x) //Object (In javascript array is also a object)

let x;
typeof(x) //Undefined

let x=null
typeof(x) //Object(It's a Javascript's exception is that typeof null is also a object)

Note:- This blog gives a brief about the variables and it's data types in Javascript. There are a lot of concepts regarding this topic that are not discussed in this blog.

No Comments Yet