Data types to define what types of data can store values and changed it.
There are following types of data types and strucutre
Some examples are primary data types in JavaScript
var age = 18; // Number var name = "Amit Kumar"; // String var obj = {name:"Raj Kumar"}; // Object
JavaScript is a loosely typed and dynamic language. JavaScript variables not correlated data value so It can change
var a; //a is undefined var a = 18; //a is Number var a = "Amit Kumar"; //a is String
/* In this example 16 is treated as string like "Apple" + "16" */ var a = "Apple" + 16; // Output : Apple16 var a ="3" + 16; // Output : 316
var a = "16" -3; // Output : 13 var a = "16" - "3"; // Output : 13
typeof
operator used to check the type of variable.
This can be used with or without parentheses like (typeof(a)) or (typeof a).
//Strings typeof ''; // Returns "string" typeof ""; // Returns "string" typeof 'ABCD'; // Returns "string" typeof '456'; // Returns "string" typeof "456"; // Returns "string" //Numbers typeof 0 // Returns "number" typeof 456 // Returns "number" typeof 45.3 // Returns "number" typeof (45+6) // Returns "number" typeof (456) // Returns "number" typeof 3.5e-2 // Returns "number" typeof Infinity // Returns "number" typeof NaN // Returns "number" // Booleans typeof true; // Returns "boolean" typeof false; // Returns "boolean" // Undefined typeof undefined; // Returns "undefined" typeof undeclared_variable; // Returns "undefined" // Null typeof null; // Returns "object" // Objects typeof {}; // Returns "object" typeof {name: "ABC"}; // Returns "object" // Arrays typeof []; // Returns "object" typeof [4,5,6]; // Returns "object" // Functions console.log(typeof isNaN); // Returns "function" typeof function(){}; // Returns "function"
A String is set of characters like "Vipin Kumar", it is denoted by single quotes '' or "" double quotes
var name1 = 'Vipin Kumar'; // using single quotes var name2 = "Vipin Katiyar"; // using double quotes
We can use single quotes inside the string
var m = "It's fine"; // single quote inside double quotes var n = 'It\'s fine'; // escaping single quote with backslash var p = 'I am fine and "You"'; // double quotes inside single quotes var q = "I am fine and 'You'"; // single quotes inside double quotes
A Numbers data type is number with or without decimals, positive or negative, or numbers written using exponential notation e.g. 1.8e-4 (0.00018)
typeof 0 // Returns "number" typeof -456 // Returns "number" typeof 456 // Returns "number" typeof 45.3 // Returns "number" typeof (45+6) // Returns "number" typeof (456) // Returns "number" typeof 3.5e-2; // Returns "number" typeof Infinity; // Returns "number" typeof NaN; // Returns "number"
console.log(456 / 0); //Infinity console.log(-456 / 0); //-Infinity console.log(456 / -0); //-Infinity console.log(-456 / -0); //Infinity
console.log('test' / 3); // NaN console.log('test' / 3+4); //NaN