Overview
Midori-san is just a humble Pythonista, but since she's running a blog, she uses JavaScript too. You could say it's her sub-weapon. And she can handle it pretty well. This time, I'll show you how I wield my sub-weapon. Let's get hyped tonight with JavaScript numbers.
What's Up with JavaScript Numbers?
node -v
# --> v22.9.0 Let's do our experiments with this version.
node -e 'console.info( typeof NaN )'
# --> number This is kind of funny. It's called Not-a-Number, yet it's a number.
node -e 'console.info( 1 instanceof Number )'
# --> false Huh?
node -e 'console.info( Number(1) instanceof Number )'
# --> false What??
node -e 'console.info( new Number(1) instanceof Number )'
# --> true
sigh... (Crumples up JavaScript and tosses it away.)
Let's Break It Down
node -e 'console.info( typeof NaN )'
# --> number
# It's by design that NaN is of type number. Fair enough.
node -e 'console.info( 1 instanceof Number )'
# --> false
# 1 isn't a Number object but a primitive number.
- Object: The ones that return
object
withtypeof
, like Number or String. - Primitive: The ones that return
number
,string
,boolean
,undefined
, etc., withtypeof
.
node -e 'console.info( typeof Number )'
# --> function
# Number, without "new", acts as a casting function.
node -e 'console.info( Number(1) instanceof Number )'
# --> false
node -e 'console.info( typeof Number(1) )'
# --> number
# Since it's just a casting function, it returns 1, which is a number.
node -e 'console.info( new Number(1) instanceof Number )'
# --> true
node -e 'console.info( typeof new Number(1) )'
# --> object
# The result of new Number(1) is a Number object.
That's a Wrap
So, what got us hyped this time was JavaScript's specification for objects and primitive types.
- Object: Number, String …
- Primitive: number, string, boolean …
Well, I guess it's easy enough to grasp.