Grimoire-
Command
.es

GNU+Linux command memo

JavaScript traps

Quand JavaScript se montre contre-intuitif.

1. Bugs

1.1. Sort

>>  [3, 23, 1].sort()
Array(3) [ 1, 23, 3 ]  (1) (2)
1 Should be [1, 3, 23]. Still buggy on Firefox Nightly ASAN 108.0a1 (2022-10-23) (64-bit)
2 From : https://solarpunk.moe/@alilly/109219021262612201

2. Type conversions

2.1. Boolean

Everything is converted to true except :

    false
    null
    undefined
    NaN
    0
    ""
>> Boolean(-1)
true
>> Boolean('false')
true
>> Boolean(new Boolean(false)) (1)
true
1 typeof new Boolean(false)'object'
>> true + true (1)
2
>> true + true + '' (2)
"2"
>> '' + true + true (3)
"truetrue"
1 true is converted to 1 in this context
2 The expression is successively Boolean, then converted to Number then converted to String
3 The Boolean values gets converted to String
>> !'true' === !'false'
true

2.2. Number

>> Number(undefined)
NaN
>> Number(null)
0
>> Number(false)
0
>> Number(true)
1
>> Number("")
0
>> Number("23.23e+2")
2323
>> Number("23.23s")
NaN
>> typeof(NaN)
"number"

2.3. String

>> String(undefined)
'undefined'
>> String(null)
'null'
>> String(false)
'false'
>> String(true)
'true'
>> String(23.23e+2)
'2323'
>> String(222e22)
'2.22e+24'

2.4. Array

>> let arr = ['a', 'b', 'c']
>> arr.length--
>> arr
[ 'a', 'b' ]
>> arr.length++
[ 'a', 'b', <1 empty slot> ] (1)
1 Firefox Nightly ASAN 108.0a1 (2022-10-23) (64-bit).

3. Comparisons

3.1. Equality

Why should you use === in JavaScript ? Because == implies non evident implicit conversions.

>> 1 == '1'
true
>> null == undefined
true
>> null == false
false
>> NaN == NaN
false
>> "2" == true
false
>> "2" == false
false
>> 1 === 1
true
>> 1 === '1'
false
>> null === undefined
false
>> NaN === NaN
false

3.2. Math

>> Math.max() > Math.min()
false
>> Math.min()
Infinity
>> Math.max()
-Infinity

4. for (… in …)

Iterates through object keys, not values. Use for (… of …) instead.

>> let obj = {
	'0': "1st",
	'1': "2nd",
	'2': "3rd",
	'length': 3
}
>> for (let p = 0; p < obj.length; p++) console.log(obj[p])
1st
2nd
3rd (1)
>>
1 Stops at p === 3

5. undefined

>> undefined = true
true
>> undefined
undefined (1)
1 undefined used to be overridable. Firefox Nightly ASAN 108.0a1 (2022-10-23) (64-bit).

7. Explore later

"Some broken functions in the library: parseInt, Date" - https://eamodeorubio.github.io/thejshorrorshow

Nim can compile to JavaScript.