Skip to content

Instantly share code, notes, and snippets.

@ghsatpute
Last active March 20, 2024 07:16
Show Gist options
  • Save ghsatpute/42abb898e9c7d81484522cb363d41499 to your computer and use it in GitHub Desktop.
Save ghsatpute/42abb898e9c7d81484522cb363d41499 to your computer and use it in GitHub Desktop.
Funny JavaScript

Funny JavaScript

> 0==-null
true
> 0==+null
true
> 0==null
false
> parseInt(0.0000005)
5 // Yes, five
"" == 0 // returns true  
0 == "0" // returns true  
"" == "0" // returns false
false == undefined // returns false  
false == null // returns false  
null == undefined // returns true
{} + [] // returns 0  
[] + {} // returns "[object Object]"
```'

```javascript
{} + [] // returns 0
[] + {} // returns "[object Object]"

It's true that [] is not on the falsy list, however == performs implicit type coercion, which doesn't necessarily mean it'll get converted to a boolean.

[] == ""       // true, [].toString() is ""     
[] == 0        // true, Number([]) is 0              

A gotcha that a lot of devs face is that implicit coercion with double equals does not convert to a boolean when comparing to a boolean, it is coerced to a number. This is not very intuitive at all and would recommend avoiding implicit coercion with booleans because of this.

[] == false   // true, Number([]) is 0

Logical operators do have implicit boolean coercion though.

[] && true    // true, Boolean([]) is true

This is why you see this behaviour

if ([]) console.log("Hi");              
// Prints "Hi", logical operator performs Boolean([])
if ([] == true) console.log("Hi");  
// Doesn't print anything, equality coercion performs Number([]) which 

[1, 2, 10].sort()

prints  [1, 10, 2] Reddit discussion link


JavaScript String Index - Bug or feature

> a = []
[]
> a['0'] = 'Hello'
'Hello'
> a
[ 'Hello' ]
> a['3'] = 'Hello3'
'Hello3'
> a
[ 'Hello', <2 empty items>, 'Hello3' ]
> a[0]
'Hello'
> a['0']

'Hello'

When style becomes a syntax

return 
{
   key: "value"
}

is interpreted as

return;
{
   key: "value"
}

Source: https://youtu.be/hQVTIJBZook?t=2067

Weird RegEx output

> console.log(new RegExp({}).test('mom'))
 true
> console.log(new RegExp({}).test('dad'))
  false
> console.log(new RegExp({}).test('man'))
 false
> console.log(new RegExp({}).test('woman'))
 true
> console.log(new RegExp({}).test('boy'))
 true
> console.log(new RegExp({}).test('girl'))
 false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment