Supported Data Types in Javascript
Published on: January 25 2018
Standard JavaScript data types include:
-
Boolean
-
Null
-
Undefined
-
Number
-
String
-
Object
Boolean
Booleans are true and false, often used for conditional statements. they are standard across all languages,
Example:
function isNotEmpty(array){
let len=array.length;
if(len>0){
return true;
}else{return false;}
}
The code above can also be written as :
function isNotEmpty(array){
let len=array.length;
return len>0;
}
or
function isNotEmpty(array){
return array.length>0;
}
Null and Undefined
Null and undefined sometime seem to be the same, but this is not actually true. Lets look at the differences and similarities between null and undefined in JavaScript.
null?
You need to understand that:
-
null is an empty or non-existent value.
-
null must be assigned.
Example:
let number= null;
console.log(number);
output:
// null
Undefined?
Undefined is scenario where you declare a variable , without not defining it. For Example:
var name;
console.log(name);
output:
// undefined
or
var name = undefined;
console.log(c);
output:
// undefined
Numbers
Number data type consists of integers and float, it handles normal numbers
(1, 12, 304, 41), negative numbers and decimal places.
Example:
let data = 55;
console.log(typeof data);
output:
// number
let data = -278;
console.log(typeof data);
output:
// number
let data = 1220.3;
console.log(typeof data);
output:
// number
Strings
Strings in JavaScript and other languages are a group of characters.
They are written inside quotes. You can use single ' ' or double " "quotes:
Examples of strings are:
var theString= "I love coding ";
var theString1= "Javascripts, is interesting";
var theString2= 'This is a long strings';
Objects
Objects are a little bit of a complex data type;
In most cases, objects will look like the structure below:
var color = {
'red': [255, 0, 0];
'blue': [0, 0, 255];
'green': [0, 0, 255]
};
var c = new color();
console.log(c.red)
output:
// [255, 0, 0];
One can make a copy of the color object as below:
var color_copy= color;
document.getElementById('demo').innerHTML=color_copy;
output:
// { "red": [ 255, 0, 0 ], "blue": [ 0, 0, 255 ], "green": [ 0, 0, 255 ] };
Then we can change the content of the color object (Because, objects are mutable) as below:
color_copy.black = [0, 0, 0];
document.getElementById('demo').innerHTML=color_copy;
output:
{ "red": [ 255, 0, 0 ], "blue": [ 0, 0, 255 ], "green": [ 0, 0, 255 ], "black": [ 0, 0, 0 ] }