简体   繁体   中英

What is the correct use of the || in javascript

In the code below, because s is null d = "test" but if s = "hello" then d would = "hello".

Is this correct as it works? what is the correct way to use ||

var s = null;

var d = s || "test";

alert(d);

|| is "or" ; and understanding what happens here is a bit trickery

var a=false;
var b=true;
result=a||b

will give "result" true (as b is true). What happens is:

  • 'a' is checked - it is false
  • 'b' is checked AFTERWARDS (as no "true" result has been obtained yet, and ONE "true" result would suffice to make the whole || operator be true) - the value of it will be assigned to the left side

if you had

   var a=true;
   var b="test";
   result=a||b

result will yield true; as no other value needs to be checked by the logic of "||"

with

var a=null;
var b="test";
result=a||b;

a will be checked first - it is null, which converts to "false". b is "test", which is non-null, and converts to "true". so the value of b will be assigned.

And yes, this is a correct way to use || ; the feature you use is also called short-circuit evaluation (as it stops evaluating the boolean expression as early as possible)

This works, but if s evaluates to a 'falsy' value, you'll get your default, which might not be what you intended. A more robust, but wordy idiom is

d = (typeof s === "undefined") ? "test" : s;

Yes it is correct unless s is allowed to be blank or 0 which are also falsy values

var s = null;
var d = s || "test";

var s = 0;
var d = s || "test";

var s = "";
var d = s || "test";

All will result in d being "test"

|| is a logical operator. When s is not null then the condition of (s) is true so d is assigned the value of s, otherwise it is assigned 'test'

|| is the OR operator in javascript
so a||b means a OR b in simple terms
explanation of question you have asked is that id you simply do somethings like these in js you will ultimately get in the else block

if(null)
if(undefined)

so s||"test" will mean which ever is not null or undefined which in this case is test

yes correct, || symbols just does the job of OR. when the first condition is true its gonna return that one.. else it will move to the next... simple as it is...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM