JavaScript(JS) array method - constructor

The constructor property is a property of the Array object in JavaScript that returns a reference to the function that was used to create the array.

Here's an example of how to use the constructor property:

ref‮ot re‬:theitroad.com
let arr = [1, 2, 3];
console.log(arr.constructor); // returns Array()

In this example, we create an array called arr and use the constructor property to return a reference to the Array() function that was used to create the array.

The constructor property can be useful in situations where you need to check whether an object is an array. For example:

function isArray(obj) {
  return obj.constructor === Array;
}

console.log(isArray([1, 2, 3])); // returns true
console.log(isArray({foo: "bar"})); // returns false

In this example, we define a function called isArray() that takes an object as a parameter and returns true if the object is an array, and false otherwise. We use the constructor property to check whether the object is an instance of the Array constructor function. If it is, the function returns true; otherwise, it returns false.

Note that the constructor property can be changed, so it's not a reliable way to check whether an object is an array. For example, you could do the following:

let arr = [1, 2, 3];
arr.constructor = Object;
console.log(arr.constructor); // returns Object()

In this example, we change the constructor property of the arr array to reference the Object() function instead of the Array() function. As a result, the isArray() function we defined earlier would now return false for this array, even though it's still an array.