简体   繁体   中英

Whats the point of defining a JS variable like so: var appName = appName || {};

Can anyone tell me the reasoning behind using a ternary operator to check if the object exists already before defining it?

var message = message || "hello",
    messageOverwritten = "Variable wasn't overwritten",
    messageOverwritten = messageOverwritten || "Variable wasn overwritten";

console.log( message );
console.log( messageOverwritten );​

/* 
 * Output
 *
 * -> hello
 * -> Variable wasn't overwritten
 */

All that's happening here is an "or" statement. If message is null or undefined for example, it will evaluate to false when tested, and the or statement will evaluate to right hand side. Then, the right hand side will be the value set to message .

The reasoning behind doing things like this is because some consider it to be less verbose than the alternates:

if (!message)
    message = "hello";

wsanville is right about what that syntax does and why people use it, but I think you might be asking more what it's useful for. I've seen it mostly used for setting default values for optional variables. Take for instance the function

function foo(value){
   value = value || 'hello';
   console.log(value);
}

then you can say foo() and you'll get 'hello', or foo('goodbye') and get 'goodbye'.

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