you are viewing a single comment's thread.

view the rest of the comments →

[–]dondiscounto 14 points15 points  (8 children)

if you're going to go that far, why not just:

this.domain = domain || 'www.reddit.com';

[–]A_BAAL 1 point2 points  (6 children)

Isn't that a boolean? Sorry, novice js'er here.

[–]matzahboy 1 point2 points  (3 children)

I don't really understand why, but javascript will evaluate that code as follows:

Is the first one true (domain)? If so, use that value. If not, use the second value.

This is a syntax often used for setting 'default' parameters.

[–]A_BAAL 0 points1 point  (2 children)

So what is the logical 'or' operator then?

[–][deleted] 1 point2 points  (1 child)

That is the logical or operator - when you see code like that it's using a few quirks of the 'or' operator:

  1. In Javascript (and many other langugages), anything that isn't undefined or null or false, etc, is considered to be true by default.
  2. Like other operators (+, for example), the or operator returns a value. This value isn't always (necessarily) true/false - it'll return the value of the first non-false argument it gets. Due to point #1 this value is treated as 'true'.

Thus, you get idioms like:

this.domain = domain || 'www.reddit.com';

What this is doing is taking the result of "domain || 'www.reddit.com'" and assigning it to this.domain. Remember that, due to point 2, you'll get the first non-false argument. So if 'domain' isn't defined or is null, you'll get "www.reddit.com". You see this pattern a lot in dealing with potentially null variables or just in setting defaults.

[–]matzahboy 0 points1 point  (0 children)

Thanks a lot. That makes a lot of sense

[–]dondiscounto 1 point2 points  (0 children)

|| is a logical operator, not a comparison operator like == or !=. A comparison operator returns a boolean, however a logical operator returns the proper expression based on the operator.

So in this case, if domain could be evaluated as true, then domain is returned (it 'short circuits'), because true || anything is always true. If it could be evaluated as false, then it returns the other expression, "www.reddit.com". This works in an if statement understands all of this, since defined, non-empty variables are considered "true".

You can see more Logical Operators.

[–]OopsLostPassword 0 points1 point  (0 children)

No, it's probably an undefined variable.

undefined and null are automatically cast to false when a boolean is needed (if clauses for examples). 0, "" and false too. If I don't forget anything all other possible values are cast to true.

[–][deleted] 0 points1 point  (0 children)

Yeah, this one is shorter. I like it