Logical operator && and two strings in javascript

前端 未结 4 1296
北海茫月
北海茫月 2020-12-05 06:57

When I use the logical operator && between two strings, why does it give me the second string as output:

4条回答
  •  萌比男神i
    2020-12-05 07:37

    I think this is because of nature of logical operator &&. Javascript executes expression "cat" && "Dog" in following way:

    Checks the value "cat" - it returns something else than "", 0, null, undefined or false and is truthy. Javascript sees && and so it continues expression and faces string "Dog", which is something else than "", 0, null, undefined or false and is truthy, expression ends and expression returns the last value it checked.

    If you replace && with || expressions ends at first truthy value and thats way

    var boolean = "cat" || "dog"
    

    returns first value: cat

提交回复
热议问题