Meteor Leaderboard Example JS Pattern Explanation - javascript

In the Meteor Leaderboard example, there is the following line of Javascript code:
Session.equals("selectedPlayer", this._id) ? "selected" : '';
I know this is shorthand JavaScript, I believe for some sort of 'if' statement, but I can't remember exactly how it works. I was wondering if someone could provide an explanation of what exactly is going on here. Many thanks!

var x = conditionExpression ? trueExpression : falseExpression
// The above is equivalent to the one below.
if(conditionExpression){
var x = trueExpression
}else{
var x = falseExpression
}

Related

button.js in ternary operator code

I was just looking up the code in button.js and I saw this ternary operator that's hard to decode. Basically I am talking about the below line of code:
$el[val](data[state] == null ? this.options[state] : data[state])
I understand the below part:
data[state] == null ? this.options[state] : data[state]
But what is this:
$el[val]
I am having a problem understanding this javascript syntax, can somebody decode the complexity and explain this to me please. I ran through the code a few times, but still couldn't quite understand.
You can check out the plugin on GitHub too, here's the link : link (line 40)
On line 31, you can see this line
var val = $el.is('input') ? 'val' : 'html'
val and html functions of jQuery object. So, $el[val] returns a function reference of either val or html, which is called by passing the result of
data[state] == null ? this.options[state] : data[state]
To be more clear,
var func = $el[val]; // function reference is gotten
func(data[state] == null ? this.options[state] : data[state]); // invocation
The above is just to show how it works. In real time it would break, as context of $el is missing.

What is the ??! operator in Javascript?

when I'm looking for some sites Javascript code, I see this
function hrefLeftMenu() {
var x = true;
for (i in info) {
$(".leftmenu ul").append("<li" + (x ? " class='active'" : "") + " onclick='openAnInfo(\"" + i + "\", this);'> - " + info[i].title + "</li>");
x = x??!x;
}
openAnInfo("0", ".lelelesakineyy");
}
What it does in javascript? Why the coder's used this operator?
Thanks.
What it does in javascript?
It throws a syntax error.
> x = x??!x;
SyntaxError: Unexpected token ?
Why the coder's used this operator?
Taking a reasonable guess (beyond "they made a mistake") would need more context. Saying for sure would require mind reading :)
In JavaScript this is not valid code. However, the sequence ??! exists (existed?) in C as a trigraph, representing |. Maybe that's not JavaScript code, or it was poorly-ported from ancient C code. But even then, x = x | x can hardly be called a useful statement.
EDIT: With a bit context in the question now, that speculation is likely wrong. A friend suggested that maybe the sequence x?? was a typo and subsequent attempt to correct it where backspace was turned into a character by some intermediate mangling (not uncommon when typing in terminals or via SSH) and that the line in question was supposed to be x = !x.
I think it is a mistake. They're generating a menu and x is used to set an item as active, and it looks like they want to default to selecting the first item. They want x to be true the first time around, and then false for the rest. It was probably supposed to be something like
x = x?!x:x; // If first time through, then set x = false for the rest
aka
x = false; // Set x = false for the rest
but confusion/muddy thinking led to over-complification.
Was this a mistake?
Did you mean this?
x= x?x:!x;

Is it safe to run code inside the conditional operator?

I often see and use codes like:
var myvar = (1 < 2) ? 3 : 4 ; //if 1 < 2 then myvar = 3, else = 4
But I just recently saw a code that was executing code, just like some kind of replacement for the if(){}else{}:
Example:
(1 < 2) ? alert("example1") : alert("example2");
The first thoughts that came to me were, "wow, this is like 6-7 characters shorter", "endless of possibilities" or "this made my day".
My question:
Is this thing error-free and safe to use? (like, with a lot of code inside, and nested stuff)
For now, I will just keep using it in the normal way, I have the fear that if I start using it to execute pieces of code might not work.
Is this thing error-free and safe to use? (like, with a lot of code
inside, and nested stuff)
Yes. However, the more code that's within it, the less readable it becomes.
I prefer to use it (the conditional operator) for short, concise statements. Anything more complex deserves an if/else for the sake of readability and maintainability.
There are some exceptions. You can't do this with:
break
continue
Any block like if, for, while, do, or try
for example. What's more, it can mess with your order of operations:
x < 3 ? l = true : r = true; // Syntax error, = has lower precedence than ?:
But that's not the reason not to do it, it's because it's ugly. Which one is clearer to you, this:
if(i > 5) {
alert('One');
} else {
alert('Two');
}
or
i > 5 ? alert('One') : alert('Two');
? It's not quite right, is it? And saving characters is never a reason to do anything, really; otherwise there would be no comments or whitespace. A good minifier like Google Closure Compiler will automatically convert these for you when possible, and there are plenty of other places to save. In the end, it's just whatever you find most convenient and readable.
Also, if you do end up needing break, continue, etc. then it's going to be rather inconsistent and unattractive code.
You're referring to the ternary operator. It's usually used for setting variables with simple strings like this:
var phone = old ? "blackberry" : "iPhone"
That much simpler than using an if:
var phone = "iphone"
if (old) {
phone = "blackberry"
}
It's good in this context, in the example you described and as soon as it starts getting confusing or I'd definitely not recommend it!
Your example might be made better like this:
var msg = 1 < 2 ? "alert1" : "alert2";
alert(msg);
You could also write:
alert( 1<2? "example1" : "example2" );
The ternary opertator is designed for simple cases, sometimes developers get carried away and use it to replace multiple if..else statements, e.g.
var someVal = foo < bar? 'yes' : bar > fum? : fum : fi != fee? fi : fee;
which is not a good idea IMHO.

Ternary Operator in JavaScript With Multiple Expressions?

the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();
Obviously, this isn't valid. Notice the ";" between the appendTo() and the_styles=null. How do I write it on 1 line and still have multiple expressions like that?
Use the comma operator this way:
the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles = $('.stylesheet').detach();
Here's what the Mozilla Developer Center writes about the comma operator:
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
Read more here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator
Who needs the ternary operator?
​the_styles = !the_styles && $('.stylesheet').detach()​​​​ ||
the_styles.appendTo('head') && null;​
Had to switch the expressions around as otherwise the null value of the first expression will always force the second expression .detach() to be evaluated.
The only thing about clever code is that once you come back to it after a coffee break, it won't make any sense even to you. So this is much better:
if(the_styles) {
the_styles.appendTo('head')
the_styles = null;
}
else {
the_styles = the_styles.detach('.stylesheet');
}
To me, even the above simplistic version doesn't make any sense. The what part is obvious, but why is it doing that?
the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc>
Just wrap the code block in (function() { and })().
Now for the hard part: why would you want to do this? Perhaps there's a better solution!
i agree with glowcoder but if you still want it:
the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach();
the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach();
you dont need to null it if your overwriting it !
the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head');

Refactoring JScript code

How can I make this code into a one line instruction?
var qe : QuestionnaireElement = state.Parameters["demobreak"];
var qid : String = qe.QuestionId;
qid != "q45"
public class QuestionnaireElement : ParameterValue, IParameterValue, ICloneabl
My real question is:
How can I cast in JScript objects?
((QuestionnaireElement)state.Parameters["demobreak"]).QuestionId != "q45"
I can't test this, but wouldn't
(state.Parameters["demobreak"]:QuestionnaireElement).QuestionId != "q45"
do it?
Sorry for all of you if I make waste your time. I was kind of desesperate to find out the solution, and like always, once that seen the solution, everything looks easier.
The final answer is (or at least a solution is):
(QuestionnaireElement)(state.Parameters["demobreak"]).ValueId != report.DataSource.GetProject("ds0").CreateQuestionnaireElement("q45").ValueId

Categories

Resources