JAVASCRIPT

Stranger Things, JavaScript Edition

Find the explanation to some of the weirdest JavaScript moments here

Image for post
Image for post

Scenario #1: [‘1’, ‘7’, ‘11’].map(parseInt)

['1', '7', '11'].map(parseInt);
[1, 7, 11]
[1,NaN,3]

map()

[1, 2, 3].map(console.log)
1 0 > (3) [1, 2, 3]
2 1 > (3) [1, 2, 3]
3 2 > (3) [1, 2, 3]

parseInt()

Resolving the mistery

['1', '7', '11'].map(parseInt);
['1', '7', '11'].map((currentValue, index, array) => parseInt(currentValue, index, array));
parseInt('1', 0)
1
parseInt('7', 1)
NaN
parseInt('11', 2)
3

Is there a way to get the originally expected result?

['1', '7', '11'].map((currentValue) => parseInt(currentValue));
> (3) [1, 7, 11]

Scenario #2: (‘b’+’a’+ + ‘a’ + ‘a’).toLowerCase() === ‘banana’

('b'+'a'+ + 'a' + 'a').toLowerCase() === 'banana'
true
('b' + 'a' + + 'a' + 'a').toLowerCase()
"banana"
('b' + 'a' + + 'a' + 'a')
"baNaNa"
b + a + NaN + a + a
+ + 'a'
NaN

Scenario #3: Can’t even name it

(![] + [])[+[]] +
(![] + [])[+!+[]] +
([![]] + [][[]])[+!+[] + [+[]]] +
(![] + [])[!+[] + !+[]] === 'fail'
(![] + [])

Scenario #4: To be truthy or to be true, that is the question.

What is truthy and falsy? and why are they different from true or false?

const array = [];
if (array) {
console.log('Truthy!');
}

How do I know what is truthy and what is falsy?

Scenario #5: Array equality

[] == ''   // -> true
[] == 0 // -> true
[''] == '' // -> true
[0] == 0 // -> true
[0] == '' // -> false
[''] == 0 // -> true

[null] == '' // true
[null] == 0 // true
[undefined] == '' // true
[undefined] == 0 // true

[[]] == 0 // true
[[]] == '' // true

[[[[[[]]]]]] == '' // true
[[[[[[]]]]]] == 0 // true

[[[[[[ null ]]]]]] == 0 // true
[[[[[[ null ]]]]]] == '' // true

[[[[[[ undefined ]]]]]] == 0 // true
[[[[[[ undefined ]]]]]] == '' // true

Scenario #6: Math is Math, unless….

3  - 1  // -> 2
3 + 1 // -> 4
'3' - 1 // -> 2
'3' + 1 // -> '31'

'' + '' // -> ''
[] + [] // -> ''
{} + [] // -> 0
[] + {} // -> '[object Object]'
{} + {} // -> '[object Object][object Object]'

'222' - -'111' // -> 333

[4] * [4] // -> 16
[] * [] // -> 0
[4, 4] * [4, 4] // NaN
'3' - 1  // -> 2
'3' + 1 // -> '31'
Number  + Number  -> addition
Boolean + Number -> addition
Boolean + Boolean -> addition
Number + String -> concatenation
String + Boolean -> concatenation
String + String -> concatenation
{
// a code block here
}
+[]; // -> 0
({} + []); // -> [object Object]

Conclusion

Written by

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store