javascript - Logical AND (&&) and OR (||) operators -


logical , (&&) , or (||) operators --- knew trick :)

their definition, js (according this explanation), following:

expr1 && expr2 => returns expr1 if can converted false; otherwise, returns expr2. thus, when used boolean values, && returns true if both operands true; otherwise, returns false.

expr1 || expr2 => returns expr1 if can converted true; otherwise, returns expr2. thus, when used boolean values, || returns true if either operand true; if both false, returns false.

testing it, indeed works definition, here's problem:

false || ""  //returns "" "" || false  //returns false 

so, obviously:

(false || "") ==  ("" || false) // true 

but, sadly

(false || "") === ("" || false) // false 

to main 2 questions:

  1. is bug, or why javascript forcing use == operator or pay attention order when using && , || operators?
  2. why javascript unable convert expr1 true in expression ("" || false)?. mean, isn't simple prepending "" not (!) operator?

it's how work. it's not bug:

returns expr1 if can converted false; otherwise, returns expr2

this means can use "default values", this:

function somefunc(passedparameter){     var newvalue = passedparameter || 1337 } 

or run functions when conditions met:

var mybool = true; mybool && somefunc(); // somefunc evaluated if `mybool` truthy 

more info on truthy / falsy


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -