Dennis Thomas
How to check if a JavaScript variable is an array or an object?
By Dennis Thomas in JavaScript on Jan 29 2018
  • Dennis Thomas
    Feb, 2018 5

    Thank you Dang Dang for the post. jQuery, $.isArray() uses Array.isArray() JavaScript method. But it is not supported by older browsers.

    • 2
  • Đặng Đang
    Feb, 2018 5

    simply using $.isArray()

    • 2
  • Dennis Thomas
    Jan, 2018 29

    Since a JavaScript Array is an object, typeof operator will return object for an array. So we cannot use that in this case.We can use Array.isArray() in browsers that support ECMAScript 5.Array.isArray(myArray); // returns trueBut older versions of browsers doesn't support ECMAScript 5. So, you need to write your own function for this. You can check the prototype of the object to search for the word "Array".function isArray(myVar) {return myVar.constructor.toString().indexOf("Array") > -1; }The above function will return true if the parameter is an array.

    • 2
  • Gajendra Jangid
    Feb, 2018 5

    using $.isArray()

    • 1
  • Jin Vincent Necesario
    Oct, 2020 2

    Two ways to check if an Array

    1. Using the Object.prototype.toString.call([]).
    2. Using the Array.isArray([]).

    Code Samples Below:

    1. const programmingLanguages = ['C#', 'JavaScript', 'Java'];
    2. //old way
    3. console.log(Object.prototype.toString.call(programmingLanguages) === '[object Array]'); //output: true
    4. //new way
    5. 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.

    1. const customer = {};
    2. console.log(typeof(customer)); //output: object;
    3. //but it is better to check if typeof object and not null
    4. console.log(typeof(customer) === "object" && customer !== null); //output: true
    5. const product = null;
    6. //but it is better to check if typeof object and not equal to null
    7. console.log(typeof(product) === "object" && product !==null); //output: false

    • 0
  • Bidyasagar Mishra
    Aug, 2019 2

    $.isArray()

    • 0
  • Neeraj Negi
    Oct, 2018 8

    let obj ={}; let arr = [];check output of console.log in each variable and you can see that they have different proto.console.log(obj.constructor.prototype.hasOwnProperty('push')); // this will give false because and object don't have a push method where as an array have the push method. console.log(arr.constructor.prototype.hasOwnProperty('push')); // will return true

    • 0

Most Popular Job Functions


MOST LIKED QUESTIONS