Is it a good practice to use the ternary operator for this:
answersCounter = answer.length != 0 ? ++answersCounter : answersCounter;
This is a question that I always asked myself as it happens quite often. Or, is it better to use a normal if statement? For me, this looks much cleaner in one line.
This is just opinion, but I think that writing the increment like you have it is somewhat poor style.
Assigning a variable to a pre-incremented version of itself is a little bit confusing. To me, the best code is the clearest (excepting nods to optimization where necessary), and sometimes brevity leads to clarity and sometimes it does not (see anything written in Perl... I kid, sorta).
Have you ever had the programming trick question of:
int i = 5;
i += i++ + i;
Or something similar? And you think to yourself who would ever need to know how that works out since when would you ever assign a variable to the pre/post increment version of itself? I mean, you would never ever see that in real code, right?
Well, you just provided an example. And while it is parseable, it is not idiomatic and not clearer than a straight forward if.
E.g.
if (answer.length != 0) answersCounter++;
Of course, some people don't like if statements with out braces, and don't like braces without newlines, which is probably how you ended up with the ternary. Something with the coding style needs to be re-evaluated though if it is resulting in (subjectively) worse code to avoid a few carriage returns.
Again, this is opinion only, and certainly not a rule.
For Javascript
As it's unclear whether OP is asking about Java, JavaScript or genuinely both.
Also know this is an old question but I've been playing with this and ended up here so thought it worth sharing.
The following does nothing, as incrementers within ternary operators don't work as expected.
let i = 0;
const test = true;
i = test ? i++ : i--;
console.log(i) // 0
Switching ++ to +1 and -- to -1 does work.
However it conceptually is a little strange. We are creating an increment of the variable, then assigning that incremented variable back to the original. Rather than incrementing the variable directly.
let i = 0;
const test = true;
i = test ? i+1 : i-1;
console.log(i) // 1
You can also use the logical operators && and ||.
However I personally find this harder to read and know for sure what will be output without testing it.
let i = 0;
const test = true;
i = test && i+1 || i-1;
console.log(i) // 1
But at the end of the day as commented above, an if else statement seems to be the clearest representation.
This increments the variable directly, and if brevity is the aim then it can still all go on one line.
let i = 0;
const test = true;
if (test) { i++ } else { i-- }
console.log(i) // 1
Related
I've recently become informed of the ternary operator and it seems like an effective way of cleaning up my code. However, I seem to be confused with the possibilities of it.
I understand that you cannot use it for if-only conditions, but I'm a little confused about the logic of what I've done.
I wrote this:
if(current_slide < 1){
current_slide = 1;
ToggleEnabled(next_button);
}else if(current_slide > total_slides){
current_slide = 1;
ToggleEnabled(prev_button);
}
It works, whatever. I wanted to clean it up a little, so I made this:
current_side < 1 ? (ToggleEnabled(next_button), current_slide = 1) : current_slide > total_slides ? (ToggleEnabled(prev_button), current_slide = 1) : [No clue what to put here];
Is there a better way of doing this in a more tidy way, or should I just keep using the if-elseif- ?
In my opinion the ternary operator should not be chained. As #VLAZ expressed their concerns in their comment, the ternary can become excessively difficult to read if you chain it in multiples. In this situation I would stick with the traditional if-else.
Take a look at the following:
if (condition1) {
// do stuff #1
} else if (condition2) {
// do stuff #2
} else if (condition3) {
// do stuff #3
} else {
// do stuff #4
}
And compare the readability to the same in ternary (I tried to indent it clearly, but chained ternary formatting is a matter of opinion):
condition1
? // do stuff #1
: condition2
? // do stuff #2
: condition3
? // do stuff #3
: // do stuff #4
To my eye the first option is a lot more readable. There is not much to be gained even if you would understand chained ternary very well, as it is (slightly) less efficient than traditional if-else.
Also of note should be the fact that ternary always needs the both the ? and the :, which means there is always a "final else" that you must deal with.
IMO, the ternary operator is meant to choose between answers or values, based on a condition, e.g.:
const x = condition1 ? 1 : 2;
return condition2 ? func1(x) : func2(x);
If you don't use the resulting value from a ternary expression (as you do) then the usage becomes highly suspect to me, and I would most likely ask it to be changed in code review. Even more so if you move the assignment part to BEHIND the ? and : selectors as you did.
Not everything that is possible, is also good style, good practice or recommended.
I'm wondering which of these is better and why. I often encounter situations in my daily work where I'm like "This algorithm works so long as the input isn't empty" or something like that. I usually just return early because, for some reason, the idea of wrapping almost the entirety of a function in an if conditions seem wrong to me. However, I know that some religions don't believe in early return statements.
Example:
(1)
function combine ( strings , separator )
{
if ( strings.length > 0 )
{
retstring = strings[0];
for ( var i = 1; i < strings.length; ++ i )
retstring += (separator + strings[i]);
}
return retstring;
}
(2)
function combine ( strings , separator )
{
if (strings.length === 0) return undefined;
retstrings = strings[0];
for ( var i = 1; i < strings.length; ++ i )
retstring += (separator + strings[i]);
return retstring;
}
So which is better to go with in such situations?
I'd say that neither is "better"; it's subjective.
And, unlike many subjective programming choices, this one isn't just a matter of personal preference. Rather, I think a good programmer will use both patterns, choosing which one based on what they want to express.
Pattern #1 says "if X do Y". Pattern #2 says "If !X, don't do anything else." Admittedly, those two are equivalent to any browser running your code.
But, to a human reading your code (eg. such as a co-worker who has to modify it) each pattern suggests different things about what is going on. Thus, my recommendation would be to try and determine which of the two patterns best describes what you are trying to communicate, and use that.
For instance, many functions have "if this isn't relevant logic", and that is best expressed with pattern #2:
function doStuffIfLoggedIn(user) {
if (!user.isLoggedIn()) return;
doStuff();
}
But it's also fairly common to do something if a particular option is provided, and that fits better with the first pattern:
function format(word, capitalize) {
if (capitalize) {
word = string.toUpperCase();
}
returns word;
}
If either is equally valid (and I find this happens fairly often) then it does come down to a matter of preference. Personally, in those "either is valid" cases I opt for #2; all else being equal it results in less indentation, which I (subjectively) find easier to read.
But really, the important thing (IMHO) is to think about how your code will look to the person who comes after (and that might even be you, a year later when you've forgotten why you wrote it that way). The browser doesn't care either way, and your co-workers will be able to understand either one, but using the one that best represents the situation can offer a critical clue about the code's function to whoever reads it later.
EDIT
To your point about:
some religions don't believe in early return statements
I think the idea there is that multiple return statements can make the code more complicated. When your function has lots of ways of exiting it can become hard to understand its logic, because to interpret a latter part, you have to reason through whether any of the earlier parts prevented you from getting there.
However, the Stack Overflow consensus is that, while it's a good idea to avoid excessive return statements, using a few properly can make your code more readable, and thus are a good idea.
See:
Should a function have only one return statement?
There is a built-in array method that does what your functions do: join()
function combine(strings, separator) {
return strings.join(separator);
}
console.log(combine(['this','is','a','test'], '...')); //this...is...a...test
But if join() didn't exist, I'd recommend a variation on your first code. You don't have to explicitly return undefined. If you don't include a return statement, the function will automatically return undefined:
function combine(strings, separator) {
if (strings.length) {
var retstring = strings[0];
for (var i = 1; i < strings.length; ++i)
retstring += (separator + strings[i]);
return retstring;
}
}
console.log(combine(['this','is','a','test'], '...')); //this...is...a...test
console.log(combine([], '...')); //undefined
In Javascript what is the best way to handle scenarios when you have a set of arrays to perform tasks on sets of data and sometimes you do not want to include all of the arrays but instead a combination.
My arrays are labeled in this small snippet L,C,H,V,B,A,S and to put things into perspective the code is around 2500 lines like this. (I have removed code notes from this post)
if(C[0].length>0){
L=L[1].concat(+(MIN.apply(this,L[0])).toFixed(7));
C=C[1].concat(C[0][0]);
H=H[1].concat(+(MAX.apply(this,H[0])).toFixed(7));
V=V[1].concat((V[0].reduce(function(a,b){return a+b}))/(V[0].length));
B=B[1].concat((MAX.apply(this,B[0])-MIN.apply(this,B[0]))/2);
A=A[1].concat((MAX.apply(this,A[0])-MIN.apply(this,A[0]))/2);
D=D[1].concat((D[0].reduce(function(a,b){return a+b}))/(D[0].length));
S=S[1].concat((S[0].reduce(function(a,b){return a+b}))/(S[0].length));
}
It would seem counter-productive in this case to litter the code with tones of bool conditions asking on each loop or code section if an array was included in the task and even more silly to ask inside each loop iteration with say an inline condition as these would also slow down the processing and also make the code look like a maze or rabbit hole.
Is there a logical method / library to ignore instruction or skip if an option was set to false
All I have come up with so far is kind of pointless inline thing
var op=[0,1,1,0,0,0,0,0]; //options
var L=[],C=[],H=[],V=[],B=[],A=[],D=[],S=[];
op[0]&&[L[0]=1];
op[1]&&[C[0]=1,console.log('test, do more than one thing')];
op[2]&&[H[0]=1];
op[3]&&[V[0]=1];
op[4]&&[B[0]=1];
op[5]&&[A[0]=1];
op[6]&&[A[0]=1];
It works in that it sets only C[0] and H[0] to 1 as the options require, but it fails as it needs to ask seven questions per iteration of a loop as it may be done inside a loop. Rather than make seven versions of the the loop or code section, and rather than asking questions inside each loop is there another style / method?
I have also noticed that if I create an array then at some point make it equal to NaN rather than undefined or null the console does not complain
var L=[],C=[],H=[],V=[],B=[],A=[],D=[],S=[];
L=NaN;
L[0]=1;
//1
console.log(L); //NaN
L=undefined;
L[0]=1
//TypeError: Cannot set property '0' of undefined
L=null
L[0]=1
//TypeError: Cannot set property '0' of null
Am I getting warmer? I would assume that if I performed some math on L[0] when isNaN(L)===true that the math is being done but not stored so the line isn't being ignored really..
If I understand what you want I would do something like this.
var op = [...],
opchoice = {
//these can return nothing, no operation, or a new value.
'true': function(val){ /*operation do if true*/ },
'false': function(val){ /*operation do if false*/ },
//add more operations here.
//keys must be strings, or transformed into strings with operation method.
operation: function(val){
//make the boolean a string key.
return this[''+(val == 'something')](val);
}
};
var endop = [];//need this to prevent infinite recursion(loop).
var val;
while(val = op.shift()){
//a queue operation.
endop.push(opchoice.operation(val));
}
I'm sure this is not exactly what you want, but it's close to fulfilling the want of not having a ton of conditions every where.
Your other option is on every line do this.
A = isNaN(A) ? A.concat(...) : A;
Personally I prefer the other method.
It looks like you repeat many of the operations. These operations should be functions so at least you do not redefine the same function over and over again (it is also an optimization to do so).
function get_min(x)
{
return +(MIN.apply(this, a[0])).toFixed(7);
}
function get_max(x)
{
return +(MAX.apply(this, a[0])).toFixed(7);
}
function get_average(x)
{
return (x[0].reduce(function(a, b) {return a + b})) / (x[0].length);
}
function get_mean(x)
{
return (MAX.apply(this, x[0]) - MIN.apply(this, x[0])) / 2;
}
if(C[0].length > 0)
{
L = L[1].concat(get_min(L));
C = C[1].concat(C[0][0]);
H = H[1].concat(get_max(H));
V = V[1].concat(get_average(V));
B = B[1].concat(get_mean(B));
A = A[1].concat(get_mean(A);
D = D[1].concat(get_average(D));
S = S[1].concat(get_average(S));
}
You could also define an object with prototype functions, but it is not clear whether it would be useful (outside of putting those functions in a namespace).
In regard to the idea/concept of having a test, what you've found is probably the best way in JavaScript.
op[0] && S = S[1].concat(get_average(S));
And if you want to apply multiple operators when op[0] is true, use parenthesis and commas:
op[3] && (V = V[1].concat(get_average(V)),
B = B[1].concat(get_mean(B)),
A = A[1].concat(get_mean(A));
op[0] && (D = D[1].concat(get_average(D)),
S = S[1].concat(get_average(S)));
However, this is not any clearer, to a programmer, than an if() block as shown in your question. (Actually, many programmers may have to read it 2 or 3 times before getting it.)
Yet, there is another solution which is to use another function layer. In that last example, you would do something like this:
function VBA()
{
V = V[1].concat(get_average(V));
B = B[1].concat(get_mean(B));
A = A[1].concat(get_mean(A));
}
function DS()
{
D = D[1].concat(get_average(D));
S = S[1].concat(get_average(S));
}
op = [DS,null,null,VBA,null,null,...];
for(key in op)
{
// optional: if(op[key].hasOwnProperty(key)) ... -- verify that we defined that key
if(op[key])
{
op[key](); // call function
}
}
So in other words you have an array of functions and can use a for() loop to go through the various items and if defined, call the function.
All of that will very much depend on the number of combinations you have. You mentioned 2,500 lines of code, but the number of permutations may be such that writing it one way or the other will possibly not reduce the total number of lines, but it will make it easier to maintain because many lines are moved to much smaller code snippet making the overall program easier to understand.
P.S. To make it easier to read and debug later, I strongly suggest you put more spaces everywhere, as shown above. If you want to save space, use a compressor (minimizer), Google or Yahoo! both have one that do a really good job. No need to write your code pre-compressed.
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.
In this question,I'm asking how the following snippets work, as it involves weird use of variable:
while (+(+i--)!=0)
{
i-=i++;
}
console.log(i);
Interesting problem... you've tagged it Java, JavaScript and C -- note that while these languages have the same syntax, this question involves very subtle semantics that may (I'm not sure) differ across languages.
Let's break it down:
+(+i--)
The -- postfix decrement operator is most tightly bound. So this is equivalent to +(+(i--)). That is therefore equivalent to the value of +(+i) (that is, i), but it also decrements i after taking the value. It compares the value with 0 to see if the loop should continue. Thus, while (+(+i--)!=0) is equivalent to the following:
while (i-- != 0)
Note that it also performs i-- at the end of the loop.
Inside the loop, I believe you have some undefined behaviour, at least in C, because you are referencing i on the right, and also updating i on the left -- I believe that C doesn't define which order to do that in. So your results will probably vary from compiler to compiler. Java, at least, is consistent, so I'll give the Java answer. i-=i++ is equivalent i = i - i++, which is equivalent to to reading all the values out of the expression, computing the result of the expression, applying the post-increment, and then assigning the result back. That is:
int t = i - i; // Calculate the result of the expression "i - i++"
i++; // Post-increment i
i = t; // Store the result back
Clearly, this is the same as writing i = 0. So the body of the loop sets i to 0.
Thus, the loop executes just one time, setting i to 0. Then, it decrements i one more time on the next while loop, but fails the check because i (before decrementing) == 0.
Hence, the final answer is -1, no matter what the initial value for i is.
To put this all together and write an equivalent program:
while (i-- != 0)
{
int t = i - i;
i++;
i = t;
}
console.log(i);
When I tried it in Java and JavaScript, that's what I got. For GCC (C compiler), it gives -1 only when i starts out as 0. If i starts out as anything else, it goes into an infinite loop.
That's because in GCC (not necessarily all C compilers), i-=i++ has a different meaning: it does the store back to i first, then does the post-increment. Therefore, it is equivalent to this:
int t = i - i; // Calculate the result of the expression "i - i++"
i = t; // Store the result back
i++; // Post-increment i
That's equivalent to writing i = 1. Therefore, on the first iteration, it sets i to 1, and then on the loop, it checks whether i == 0, and it isn't, so it goes around again, always setting i to 1. This will never terminate, but for the special case where i starts out as 0; then it will always terminate the loop and decrement i (so you get -1).
Another C compiler may choose to act like Java instead. This shows that you should never write code which both assigns and postincrements the same variable: you never know what will happen!
Edit: I tried to be too clever using that for loop; that wasn't equivalent. Turned back into a while loop.
That's soooo wierd! (I love it)
first, you can forget about the +(+...) part, it's just like saying 1 + (+1) = 2.
i-- means i = i - 1. In your while condition, you test if i-- is different from 0. Note: the test is made on i != 0 and then i's value is changed. If you wanted to change its value before the test, you should have used --i instead.
As for the i -= i++, it's a very dumb way to say i = 0. You must read it from right to left: i = i + 1 and then i = i - i1 (whatever value of i you have, you'll end up with 0.
Simplier quivalent snippet:
while (i-- != 0) {
i = 0;
}
console.log(i);
1 a -= b means a = a - b.
i -= i++ would mean a similar thing to i = i-i; i++ (if you make the -= explicit).
In a similar fashion, you can pull the side effect of i-- out of the loop condition by
transforming while (foo(i--)) { ... } to while (foo(i)) { i--; ...} i--; (you need to put it both in the loop body and after the loop because, at the end, the condition will be false and the loop body will not be executed but execution continues after the while loop).
The while condition evaluation happens based on operator precedence. I have used explicit braces to help understand the evaluation:
(+(+(i--)) != 0) which is equivalent to using (i-- != 0) as the '+' are just unary operators.
The expression i -=i++; is equivalent to i = i - i++; where the LHS expression gets evaluated from left to right.
i = 4;
while (+(+i--)!=0) //here i would be decremented once to 3.
{
i-=i++; // here i = 3 - 3 = 0; even though i has been incremented by 1 its value is set to 0 with this assignment
}
This is very simple. And I think the only reason to code like this is a concept called "code obfucasion" or "code confusing". This way makes the code harder to read and debug, so that can prevent from reverse engineer your code :-)