Jacob Kelley
Jacob Kelley

Reputation: 405

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
 */

Upvotes: 2

Views: 66

Answers (2)

hobberwickey
hobberwickey

Reputation: 6444

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 sayfoo() and you'll get 'hello', or foo('goodbye') and get 'goodbye'.

Upvotes: 0

wsanville
wsanville

Reputation: 37516

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";

Upvotes: 3

Related Questions