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 :)
You 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.
Related
Can I write the if else shorthand without the else?
var x=1;
x==2 ? dosomething() : doNothingButContinueCode();
I've noticed putting null for the else works (but I have no idea why or if that's a good idea).
Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.
What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:
var y = (x == 2 ? "yes" : "no");
So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:
if (x==2) doSomething();
This is also an option:
x==2 && dosomething();
dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.
It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:
if(x==2) dosomething();
You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)
Another option:
x === 2 ? doSomething() : void 0;
If you're not doing the else, why not do:
if (x==2) doSomething();
Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.
As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:
if (x==2) doSomething;
else doSomethingElse
or, in your case,
if (x==2) doSomething;
A small addition to this old thread..
If you're evaluating an expression inside a for/while loop with a ternary operator and want to continue or break as a result - you're going to have a problem because both continue & break aren't expressions; they're statements without any value.
This will produce Uncaught SyntaxError: Unexpected token continue
for (const item of myArray) {
item.value ? break : continue;
}
If you really want a one-liner that returns a statement, you can use this instead:
for (const item of myArray) {
if (item.value) break; else continue;
}
P.S - This code might raise some eyebrows. Just saying.. :)
Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).
Probably shortest (based on OR operator and its precedence)
x-2||dosomething()
let x=1, y=2;
let dosomething = console.log;
x-2||dosomething('x do something');
y-2||dosomething('y do something');
I am currently having a hard time figuring out how to use multiple conditions for my if-else statements. I can do 1 condition at a time, but multiples are a problem for me. I'm not quite sure where to start with the multiple one as I'm using the HTML form stuff, and I'm not sure where to start with it as well. Any sample code is fine as I would like to learn rather than have people figure everything out for me.
Ok, let's start from the beginning.
You agree that this code right here:
if (true)
console.log('foo');
obviously prints out 'foo' on your console, cause the condition is satisfied (i.e. is true).
Let's try something different now:
if (true && false)
console.log('bar');
The && in Javascript and most programming languages is the and operator, which evaluates to true only if both the conditions at its left and at its right are true. This means that the code above does not print out 'bar'.
if (true || false)
console.log('bla');
The || operator, on the other hand, is the or operator, which is true when one of the two conditions (or both) is true. In this case, 'bla' is printed out on your console.
In the end, let's have a look at the ! operator (not): if the condition that follows the operator is true, then it evaluates to false, and viceversa. So writing if (!false) equals if (true).
Now you can apply these simple rules to easily use multiple logical conditions in one if or else branch. Remember the precedence of the logical operators, i.e. which one you have to evaluate first if you have more than one, taking a look here: Which Logic Operator Takes Precedence
I ran into this piece of code:
<a ng-click= "item.statusId !== itemStatus.in || transfer()">
I guess we can generalize as:
<element ng-click = "someVar !== someValue || doStuff()">
I then found this article on short circuits and another more focused one once I knew what they are called. However, I still don't get it.
Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement? (This is the main question I am asking, everything else is extra).
I guess that part I don't get is whether the compiler interprets this code differently or it still evaluates to false and just runs the function. Not even sure how to phrase Q.
Does it basically work on the principle of an OR statement ending evaluation if the first statement evaluates to true? So if the first statement is true, end evaluation, if it's false, run the function in the second half of the OR statement?
It's effectively shorthand for an if statement, and you intuited correctly why it works. For more details on short-circuit evaluation in JavaScript, see this Stack Overflow question.
That code is equivalent to:
//Note the intentional and explicit use of `== false` to mean falsy (NOT `=== false` to indicate strict equality test for false)
if( (item.statusId !== itemStatus.in) == false ) {
transfer();
}
It is an interesting means of executing a function only when a condition is falsy.
There are many different examples of this around on StackOverflow, and is not specific to AngularJS.
I've starting to dig my teeth into backbone and when working with a router function creating and destroying views I came across this little snippet, which didn't quite make sense to me as I've always assumed these sorts of operators only work in conditional statements,
this.view && this.view.remove();
It was inside of a method attached to the router which seems to work like a charm, but I'm always weary of voodoo code that doesn't sit well with me.
Heres the full method
loadView : function(view) {
this.view && this.view.remove();
this.view = view;
}
Would love to understand this a bit better, hope its not too silly to ask.
Cheers.
In JavaScript:
this.view && this.view.remove();
is equivalent to
this.view ? this.view.remove() : this.view;
The righthand side is only executed if the lefthand side is truthy. If the value of the expression is ignored and the lefthand side has no side-effects (as in this case), then it's also equivalent to this:
if (this.view) {
this.view.remove();
}
So, in this specific case if there is an existing view, then it is removed. Note that the value of this expression is not necessarily a boolean (unlike in many other languages); it's whatever is returned by remove. However, this value is ignored, so it's not actually pertinent.
The operator && in javascript evaluates the first expression, if it is falsy it is returned, if it is truthy the second expression is evaluated and returned.
For || it is the other way round: the first expression is evaluated, if it is truthy it is returned, else the second expression is evaluated and returned.
I opened a js file that I wrote a while back and although it's working, I thought I spotted an error. (JS is not my primary language)
I had this:
if( myvar = fieldval.match(mypattern))
{
//Do Stuff
}
So I think I get it. Is this a correct statement?:
A javascript assignment operation evaluates to the value being assigned.
I tested on w3schools
<script type="text/javascript">
var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
var test
document.write(test=str.match(patt1));
</script>
and it writes "ain,AIN,ain,ain" where I might have expected it to write "true" or not to write at all because boolean true is not a string. Is my line of thought and then ultimate conclusion correct. (I ask about my line of thought on this because I do not have a lot of formal CS training.)
It is a correct statement. The new value of myvar is tested:
if ( myvar = fieldval.match(mypattern) )
When the String.match method cannot find a match, it returns null. !!null === false, so the if-block is not evaluated. When any non-empty match is found, the condition is true, and the block is evaluated.
In this case, it is very likely that the if-statement is correct, and that the following is intended:
if ( (myvar = fieldval.match(mypattern)) !== null )
Rob W is correct, however it's extremely poor practice to put an assignment in an if statement like that. In the future, anyone coming along (including yourself) will scratch their head at that statement to determine if that's what you really meant.
I highly recommend Douglas Crockford's talk: http://www.youtube.com/watch?v=taaEzHI9xyY It'll make anyone (Js dev or not) a better developer for watching it because you'll consider the implications of your coding style and what future maintainers might assume.
match returns an array of matching values, not boolean. Use test instead.
The function string.match() returns an array of matches, or null if no matches are found. The code works because null evaluates to false in an if statement, while an array evaluates to true.
So indeed, the result of str.match is stored in myvar and then myvar is evaluated as boolean. It works as expected.