DEV Community

Godti Vinod
Godti Vinod

Posted on

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
Enter fullscreen mode Exit fullscreen mode

Second, using "let" keyword

let x=5; //Now x value is 5 as we assigned 5 to it
Enter fullscreen mode Exit fullscreen mode

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

see the code below

{
    let i=0;
}
console.log(i)//Throws ReferenceError:i is undefined
Enter fullscreen mode Exit fullscreen mode

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

{
    var x=5;
}

console.log(x);//5
Enter fullscreen mode Exit fullscreen mode

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;
{
    x=5;
}
console.log(x)//5
Enter fullscreen mode Exit fullscreen mode

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

const x=4;
x=5//Throws TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

Data Types and Type Checking

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

1.Number
2.String
3.Boolean
4.Object
5.Undefined
6.Null
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

Follow me on my (twitter)[https://twitter.com/GodtiVinod] and connect me on (LinkedIn)[https://www.linkedin.com/in/godti-vinod-37bb46a9/]

Discussion (0)