If the variable updates instructions

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

This is just a useless piece of code, but it gives a strange result that I did not expect at all. Therefore, my curiosity brought me here.

It prints only true.

Why does it update the value textto true, and not set it to empty?

+4
source share
2 answers

Expression

text = '' || text != ''

analyzed as

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

Value

('' || text != '')

- this is a logical meaning true, because text != ''- true.

+7
source

The condition '' || text != ''is evaluated as true. and this value is then assigned to the variable text.

'' - , || (OR). text , text != '' true, text.

+2

Source: https://habr.com/ru/post/1611972/


All Articles