What do ? and : mean in javascript [duplicate] - javascript

This question already has answers here:
How do you use the ? : (conditional) operator in JavaScript?
(20 answers)
What does ? : mean in Javascript? [duplicate]
(9 answers)
Closed 10 years ago.
I am trying to understand the Javascript/jQuery in this http://www.queness.com/post/12078/create-jquery-pinterest-pin-it-plugin plugin. The lines 20 and 22 are confusing me, the code is:
pi_media = e.data('media') ? e.data('media') : e[0].src,
pi_desc = e.attr('title') ? e.attr('title') : e.attr('alt'),
Can anyone help me out with what these lines mean in Javascript

It's the JavaScript ternary operator.
x = condition ? a : b
is equivalent to
if(condition)
x = a;
else
x = b;
Note that an assignment is not necessary. As an expression, it simply evaluates and produces a or b depending on the truth value of condition.

It's called the Ternary Operator. It means:
Evaluate the expression to the left of the ?
If the expression evaluated to true, run the first piece of code (between the ? and the :)
If the expression evaluated to false, run the second piece of code (after the :)
This is a construct common to many C-style languages.

Those are part of the ternary operator.
Basically, if the condition before the ? is evaluated to true, the expression immediately following the ? is the one which is evaluated, and otherwise the expression following the : is evaluated.

For example take the code:
var result=condition?arg1:arg2;
First the condition is evaluated.
If the evaluation results to true, then arg1 is returned and assigned to result
If the evaluation results to false, then arg2 is returned and assigned to result

Related

How do multiple OR's || work in JavaScript? [duplicate]

This question already has answers here:
javascript multiple OR conditions in IF statement
(6 answers)
Closed 3 years ago.
if(eggsAmount < eggsMin || milkAmount < milkMin || flourAmount || FlourMin)
Does it mean whichever of these are true?
Yes, in an if statement with only OR || operators, it will simply go through each condition and as soon as it finds one that is true, the if statement resolves as true, the rest are not checked, and the code in the if block.
An if statement containing multiple OR conditions (||) has in Javascript the same behaviour descripted by Boolean Algebra: the whole evaluation is True if any of the conditions is true.
At this w3schools link you can find JS logic operators description.
Anyway the evaluation of the expression itself is not necessarily a boolean value. The expression
Res = expr1 || expr2 || ... || exprN
is evaluated as the first condition that can be evaluated as true (for example if expr1 is 4+7, Res=11.
If none of the condition can be evaluated as true the assigned value is the value contained in the last condition: Res = exprN.
(thanks to Jared Farrish, Barmar and Teemu)

Please interpret this java script line of code [duplicate]

This question already has answers here:
What is "?:" notation in JavaScript?
(5 answers)
Closed 6 years ago.
Can someone interpret this javascript line for me?
mouseWheelEventName = $.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel',
Need to know what "?" does, and what 'DOMMouseScroll' : 'mousewheel', is saying particularly the "," at the end of the line... why isn't it a ";"
Thank you.
This is a ternary operator, used as a shorthand conditional statement:
it's the same as saying:
if ($.browser.mozilla) {
mouseWheelEventName = 'DOMMouseScroll';
} else {
mouseWheelEventName = 'mousewheel';
}
The first piece before the = is declaring a variable (mouseWheelEventName) dependent on the following condition.
The next piece between = the ? is the condition (is $.browser.mozilla true?).
Immediately after the ? is the then portion (if the condition is true, set the variable mouseWheelEventName to the string DOMMouseScroll).
After the : is the else (if the condition is NOT true, set the variable mouseWheelEventName to the string mousewheel).
Further reading:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
As for why there is a comma at the end of it, we'd need to see a more complete code sample including what follows that to say for certain. If I had to guess, I would say the author of the code was chaining variable statements. This answer may shed some light for you: Javascript best practices, why to use comma to chain function/variable declarations? (see chosen answer)

Unable to correctly write ternary operator in JavaScript [duplicate]

This question already has answers here:
Concatenate string with ternary operator in javascript [duplicate]
(2 answers)
confusion with hasOwnProperty
(1 answer)
Closed 6 years ago.
I have an undefined variable and I check it in a string concat:
var undefinedVariable = undefined;
console.log("foo" + undefinedVariable === undefined ? "bar" : undefinedVariable.toString() );
Considering that undefinedVariable is undefined, undefinedVariable.toString() is an unreachable code. However, I get this error:
Uncaught TypeError: Cannot read property 'toString' of undefined(…)
The strange thing is if I remove "foo" at the start of console.log, then the code works fine.
console.log(undefinedVariable === undefined ? "bar" : undefinedVariable.toString() );
I have tested in chrome and firefox and I get the same result so probably it is not a bug. Is there any explanation why JS engines try to run the unreachable part?
It is because of the Operator Precedence. The + (concatenation operator) has a greater precedence than the ?: (ternary operator). So, you need to enclose the ternary condition inside () because, it takes it along with the + (concatenation operator) and no more the left side is undefined. Use:
console.log("foo" + (undefinedVariable === undefined ? "bar" : undefinedVariable.toString()) );
You need to tell the JavaScript engine to evaluate the undefinedVariable separately and don't join both the "foo" and undefinedVariable and evaluate.
var undefinedVariable = undefined;
console.log("foo" + (undefinedVariable === undefined ? "bar" : undefinedVariable.toString()) );
The above gives me: foobar.

How can jquery || "OR" be used outside of an if statement? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".

What does mean && between variables in line without if? [duplicate]

This question already has answers here:
Using &&'s short-circuiting as an if statement?
(6 answers)
Javascript AND operator within assignment
(7 answers)
Closed 8 years ago.
I have following line of code in javascript:
q && (c = q === "0" ? "" : q.trim());
WHat does it mean? I understand that c is equals either empty string or q.trim() result, but what does mean q && ()?
JavaScript optimizes boolean expressions. When q is false, the right hand side of the expression doesn't matter for the result, so it's not executed at all. So this is a short form of:
if( q ) {
c = q === "0" ? "" : q.trim()
}
It is a guard against undefined/null/false variables.
If q is not defined, false or set to null, the code short circuits and you don't get errors complaining about null.trim()
Another way to write that would be:
if(q) {
c = q === "0" ? "" : q.trim();
}
You can use this kind of clause to check wether q is defined.

Categories