0

What is the rols of "object array" here:

var  is_array = function(input){
    if(toString.call(input)==="[object array]")//what is role of "object array" here?
       return true   
    return false
}
console.log(is_array('welcome'))
console.log(is_array([1,2,3,4,5]))

1
  • What might it be, based on the rest of the code? What happens if you run "toString.call" with various data types? See if you can work through this. It's just a string: what it means is discoverable in the console in a few minutes. Commented Mar 20, 2021 at 18:05

1 Answer 1

1

The code is intended to know whether the argument is an array. Historically there are several ways to do that, although in modern days, the Array.isArray function really makes all those tricks obsolete.

First of all, it really should check for "[object Array]" (with a capital "A"). I suppose that was a typo in your question?

Anyway, here the trick is to use the global function toString, which is the toString method of the global object (globalThis.toString). You might think that you could just have called input.toString(), but that function has been overriden by the Array prototype and does not return the same result. It will return the array elements as a comma separated string. The global toString function however, will essentially do what Object.toString does: provide a generic string in the format "[object type]".

By using call we can provide the object which should be stringified. And so we get "[object Array]", which is a good indication that we have an array.

Again, nowadays the preferred method is to just call Array.isArray(input).

Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer your question? Could you give feed-back?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.