How to check if a JavaScript variable is an array or an object?
Dennis Thomas
Select an image from your device to upload
Two ways to check if an Array
Code Samples Below:
const programmingLanguages = ['C#', 'JavaScript', 'Java'];//old wayconsole.log(Object.prototype.toString.call(programmingLanguages) === '[object Array]'); //output: true//new wayconsole.log(Array.isArray(programmingLanguages)); //output: true
const programmingLanguages = ['C#', 'JavaScript', 'Java'];
//old way
console.log(Object.prototype.toString.call(programmingLanguages) === '[object Array]'); //output: true
//new way
console.log(Array.isArray(programmingLanguages)); //output: true
To check if object you can use the typeof operator and check if it is not equal to null. The reason you need to check if not null is because null when passed into the typeof operator returns an “object” result.
const customer = {};console.log(typeof(customer)); //output: object; //but it is better to check if typeof object and not nullconsole.log(typeof(customer) === "object" && customer !== null); //output: trueconst product = null;//but it is better to check if typeof object and not equal to nullconsole.log(typeof(product) === "object" && product !==null); //output: false
const customer = {};
console.log(typeof(customer)); //output: object;
//but it is better to check if typeof object and not null
console.log(typeof(customer) === "object" && customer !== null); //output: true
const product = null;
//but it is better to check if typeof object and not equal to null
console.log(typeof(product) === "object" && product !==null); //output: false
$.isArray()