Search code examples
javascriptarraysreactjsobjecttypeof

is this method object.keys returning an array or keep it an object


I'm learning JavaScript, so pardon any mistakes in how I phrase the question.

let nan={
    n:3,
    j:4
};

let nag = Object.keys(nan)

> nag
(2) ["n", "j"]0: "n"1: "j"length: 2__proto__: Array(0)

> typeof nag
"object"

Why is nag an object and not an array? And that makes difference when you want to access, you will be not able to access with dot notation I think we need in that case square bracket


Solution

  • This is because internally javascript engines store Arrays as objects. Therefore, when you ask for the typeof an array, it returns an object since that is what it is. Essentially, in javascript, Array is an abstraction over native object (an indexed collection object).

    If you want to know whether a variable is an Array and not an object you should use Array.isArray(nag). This returns a boolean.

    You can lookup the docs here:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

    or if you are in the mood, lookup the typeof spec at:

    https://www.ecma-international.org/ecma-262/#sec-typeof-operator

    tip: With JS, whenever in doubt, lookup the specs. It's probably the best place to clear up confusions