Course Banner


Javascript Data Types

All programing languages in the world have data types. So, JavaScript is not an exception. JavaScript also have pre-defined or built in data types as well as user defined data types.
But JavaScript is loosely typed language. That means, one does not need to mention data types specifically. In case of Java, C++ and C, one have to define data type specifically and only that kind of data can be stored into that variable.

For example


In ‘C’ language Int a=10; / fine
a=”Rajesh” // error because data type different

In Javascript Var a=10 // fine
A =”Rajesh” // fine

There are following types of data types in JavaScript
Boolean: This is the types of data types in which the result is returned either ‘true’ or ‘false’.
Null: When JavaScript variable contain nothing, it called null. For example: var a=null // the value of a is null(nothing). But when you try to know its data type, it should show ‘null’ but its data type shows ‘object’. In fact it’s a big in JavaScript which has never been fixed.

Result :object

Undefined: When a JavaScript variable does not contain any value that means the data is ‘undefined’. JavaScript variable is declared but no value has been assigned. Remember, var a=”” is not null. The value is empty but the data type is string.

Output: undefined

Number: JavaScript has data type number in which whole number as well as decimal number can be stored. Unlike other programing languages which have float, double etc., JavaScript has only one data type.

Example:

var a=10
var 2=45.67

String: String in JavaScript is series of characters like ‘Rajesh Kumar’

Example :var studentName=”Rajesh Kumar”

Object: JavaScript data type is written with starting curly braces and ending curly braces. The content is written in key value pair with colon(:).

Example : Var studentDetails ={‘fname’:’Rajesh’,’lName’:’Kumar’}

Symbol:

A new data type has been introduced in EncmaScript 6 called Symbol. Symbols allow for private properties on objects. Before ECMAScript 6 the properties of object could be accessed through for in.

Example :

animal cat = { mew: true }
for (var property in cat) {
if (cat.hasOwnProperty(property)) {
document.write(property); // result "mew"
}
}
But it can be written in EcmaScript 6 like this
var breed = Symbol("breed");
var cat = { mew: true };
cat[breed] = "Pet Cat";
for (var property in cat) {
if (cat.hasOwnProperty(property)) {
document.write(property); //output : mew and not breed
}
}
document.write(cat[breed]); // logs "Pet Cat"