I'm new to Javascript, CSS, HTML, and jQuery, and came across this line of code that uses the condition ? if true : if false
statement, and I'm trying to understand it. What would it's equivalent if() {} else {}
statement look like? This is the line of code:
$('.app-container').css('background', this.background ? `url(${this.background.get('Href')})` : `url(${DefaultImage.Background}`);
Thanks for any explanation :)
I'm new to Javascript, CSS, HTML, and jQuery, and came across this line of code that uses the condition ? if true : if false
statement, and I'm trying to understand it. What would it's equivalent if() {} else {}
statement look like? This is the line of code:
$('.app-container').css('background', this.background ? `url(${this.background.get('Href')})` : `url(${DefaultImage.Background}`);
Thanks for any explanation :)
Share Improve this question asked Jan 19, 2016 at 15:05 keennskeenns 9034 gold badges15 silver badges26 bronze badges 2- Not sure what's with all the extra single code-quotes in your example though :) – iCollect.it Ltd Commented Jan 19, 2016 at 15:08
- I can only guess that the backticks indicate ES6 template strings, or else they're part of some other unknown JS framework. – Blazemonger Commented Jan 19, 2016 at 15:27
2 Answers
Reset to default 3You need to expand the second parameter that was passed to url()
to an if
, else
as that is evaluated first:
if (this.background)
bgurl = `url(${this.background.get('Href')})`
else
bgurl = `url(${DefaultImage.Background})`
$('.app-container').css('background', bgurl);
If you're looking for exactly what this would look like with a traditional if-else
:
if (this.background)
$('.app-container').css('background', `url(${this.background.get('Href')})`);
else
$('.app-container').css('background',`url(${DefaultImage.Background}`);
In javascript the ternary operator follows this basic premise:
(condition) ? (what will happen if condition evaluates to true) : (what will happen if condition evaluates to false)
Sometimes they can be difficult to decipher but in the right situation (like this one) they can save you from writing 'extra' code.