DEV Community

loading...
Cover image for JS Test #7: Is this an array?

JS Test #7: Is this an array?

Coderslang: Become a Software Engineer
Teaching you to code at js.coderslang.com - JavaScript, HTML, CSS, Node.js, React.js, React Native
Originally published at learn.coderslang.com ・1 min read

Is array an array?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

At line one we create an array and bind it with the array constant. Then the type of the value of this constant is evaluated by the typeof operator.

There’s no such type as array in JS, so it’s impossible to see the message ARRAY! on the screen. In fact, all JS arrays are objects, so the execution goes into the else branch, and SOMETHING WEIRD is printed on the screen.


ANSWER: SOMETHING WEIRD will be logged to the screen as all JS arrays have the type object.

Discussion (3)

Collapse
lionelrowe profile image
lionel-rowe

Array.isArray(array) or array instanceof Array would both work 😉

Collapse
coderslang profile image
Coderslang: Become a Software Engineer Author

Thanks for pointing it out! The main point of these code snippets is to show beginner devs their weaknesses. In my experience, at least half of the newbie devs don't know how exactly typeof works.

Collapse
shashankgopannagari profile image
Shashank

Object.prototype.toString.call([]).slice(8,-1);
will also work