Introduction
[wp_ad_camp_5]
Okay, JavaScript is a loosely-typed language, which means you do not declare the data type of a variable explicitly. In a basic variable assignment expression, e.g., var i = 4;, the value that assigns to the variable determines the data type of the variable. As you assign different types of data to the same variable, its data type changes as well. Given the nature of JavaScript, finding out what data type a variable represents before using it is very important.
JavaScript Codes
To determine the data type of a variable (or value to be assigned to it), we use typeof. Here are some examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var myFunction = function() { }; console.log(typeof null); // Displays 'object' console.log(typeof 'turreta.com'); // Displays 'string' console.log(typeof undefined); // Displays 'undefined' console.log(typeof {}); // Displays 'object' console.log(typeof []); // Displays 'object' console.log(typeof 35.55); // Displays 'number' console.log(typeof 10); // Displays 'number' console.log(typeof NaN); // Displays 'number' console.log(typeof false); // Displays 'boolean' console.log(typeof myFunction); // Displays 'function' console.log(typeof setTimeout); // Displays 'function' |
Outputs:
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 9 10 11 | object string undefined object object number number boolean function function number |
As you can see, typeof against an array and object results to ‘object’. To check whether a variable (or value) is an array or object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var my_array = []; /* Check if my_array is truly an array object */ if(my_array !== null && my_array.constructor === Array) { console.log("It's an array!"); } /* Another way to check if my_array is truly an array object */ if(Array.isArray(my_array)) { console.log("Again, it's an array!"); } /* Check if my_object is truly an object */ var my_object = {}; if(my_object !== null && my_object.constructor === Object) { console.log("It's an object!"); } // Sample custom class for OOP function Person() { }; var my_person = new Person(); // Check if my_person is truly a Person object if(my_person !== null && my_person.constructor === Person) { console.log("It's Person!"); } |
Outputs:
[wp_ad_camp_2]
1 2 3 4 | It's an array! Again, it's an array! It's an object! It's Person! |