简体   繁体   中英

Using || to perform null / undefined check in javascript?

I've read code that has snippets similar to this but I obviously forgot the semantics:

        let serve = target || "Hello World";

In other words if target is null , the serve equals Hello World . My goal, since target is null, is to get serve to be Hello Word ...

If I run the function as stated node prints this:

ReferenceError: target is not defined

You need to define the variable target first. Here are some examples:

 let target; let serve = target || "Hello World"; console.log(serve); // prints "Hello World"; target = null; serve = target || "Hello World"; console.log(serve); // still prints "Hello World"; target = "Cat"; serve = target || "Hello World"; console.log(serve); // prints "Cat" 

Using a || b a || b will return b if a is falsy. The falsy values from You Don't Know JS: Types and Grammar - Chapter 4: Coercion are:

  • undefined
  • null
  • false
  • +0 , -0 , and NaN
  • ""

If you'd like to return the default only when target is null , use:

let serve = target === null ? "Hello World" : target;

target , in your example is not null . It isn't anything: You haven't declared it at all.

 let target = null; let serve = target || "Hello World"; console.log(serve); 

Possibly you are thinking of the pattern:

 var serve = serve || "Hello World"; console.log(serve); 

Which:

  • Uses var to ensure that serve is a declared variable
  • Assigns "Hello World" to serve is some previous code hasn't already assigned it a true value.

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