Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement updates variable

var text = 'abc';
if(text = '' || text != '')
    console.log(text);
else
    console.log('in else');

It is just a useless code snippet, but it gives the strange result which I was not expecting at all. So my curiosity brought me here.

It prints true only.

Why does it updates the text value to true rather than setting it as empty?

like image 630
Shaharyar Avatar asked Jan 08 '23 08:01

Shaharyar


1 Answers

The expression

text = '' || text != ''

is parsed as

text = ('' || text != '')

The value of

('' || text != '')

is the boolean value true because text != '' is true.

like image 77
Pointy Avatar answered Jan 26 '23 02:01

Pointy