In Javascript, if I make an array using Array(10)
, it creates an array with 10 empty items. If I access any item in that array, it returns undefined
. However, if I create an array with a length of 10 and fill it with undefined
like so: Array(10).fill(undefined)
, and access any item of that array, it also returns undefined
. Similarly, if I were to coerce an empty value to a number using Number()
, it returns 0
. However, if I coerce undefined
to a number by using Number(undefined)
, it returns NaN
. How do I identify an empty value vs. a specifically undefined
value?
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
Any "empty" items you are seeing are just your tools way of showing you have an array with fewer properties than your array length would indicate.
There isn’t really an empty value type in JavaScript, it’s just the absence of a property, which you can detect in a variety of ways, with varying nuances in terms of walking the prototype chain and backwards compatibility with legacy software.
The reason you get
undefined
when you access one of these empty array slots is because that’s the value you normally get when you access a property which does not exist on an object.This should not be happening according to the ES specification, all of these will produce
NaN
:Passing no argument to
Number()
will produce0
though.Let us try to understand it in one by one.
What is undefined:
As per MDN documentation
Which means if you do not assign a value to a variable/property(array index in this case) it will always be
undefined
When you create an array with the below statement.
As per the MDN documentation for this which says
All this statement does is that it creates a variable named
arr
which is declared to be of typeArray
and will contain 10 items. This does not assign any values at all to any of the items of the array nor have you added any items yet.So when the array can contain 10 elements but has none, you see each item as empty(this may vary based on what tool you are using).
This also means that since the array is declared to hold 10 items but none of their values are assigned/defined yet so if you try to access any values you will always get
undefined
For the second query related to
Number
That is simply how the Number constructor is supposed to behave read here Number() constructor.
But when you pass
undefined
since the type of valueundefined
is alsoundefined
and not a validnumber
, also it can not be converted to a valid number hence you getNaN
which means not a number.Read more about NaN here