Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why ! + [] = 'true', I can't test '!' in any way [duplicate]

Tags:

javascript

I want to know the logic of the following operators

let test = ! + [];
console.log(test); //true  

Why?
I can't test ! in any way

typeof ! //ERROR

! && true //ERROR
like image 992
Zhang YH Avatar asked Jan 03 '23 03:01

Zhang YH


1 Answers

! is an operator like +.
If you're going to do typeof + you'll get the same error.

Operators can't be used like that.

The reason why let test = ! + []; worked is because of the order of operation (operator precedence), and it determined the following order:

  1. evaluate [];
  2. convert it to a number with +[] //0;
  3. negate that conversion with !0 //true.

So, in expr !+[], +[] was executed first, that is why Quentin pointed to that dupe

Read more about expressions and operators on JS MDN

like image 175
Adelin Avatar answered Jan 05 '23 17:01

Adelin