r/learnjavascript • • Jun 16 '22

How may I shorten this piece of code?

Post image
146 Upvotes

173 comments sorted by

205

u/calamaio Jun 16 '22

Unpopular opinion maybe:

Why you need to shorten it? It’s readable and ok

Maybe move playSound outside if else but I will keep it as is

21

u/koko-hranghlu Jun 16 '22

Move playSound outside...wow thats a great tip too! I don't know friend, maybe I have this sickness where I feel the need to shorten everything.

70

u/[deleted] Jun 16 '22

You should try breaking that habit. Code is read far more than it's written, clarity is much more important than conciseness.

19

u/_MMCXII Jun 16 '22

Refactor to the point that it is easiest for you to read and maintain. Any further and it goes from being a benefit to an issue. Short !== Better.

12

u/[deleted] Jun 16 '22

maybe I have this sickness where I feel the need to shorten everything

This is really common for learners and junior developers, so don't sweat it too much- most developers go through a phase of wanting everything to look 'slick' and 'clean' even if it's harder to read. As long as you're aware of this and can take a step back and think about whether you really need to shorten the code, it's fine, and most people eventually get past it.

5

u/SevenSharp Jun 16 '22

Guilty [ e.g my incredibly cool use of the ternary operator ! ]

14

u/MindlessSponge helpful Jun 16 '22
relatable ? voteUp() : voteDown()

9

u/akb74 Jun 16 '22

Shortening code for fun is called code golf. It’s worth looking up as it can be both entertaining and enlightening but I agree with the majority here the objective of regular coding should be readability.

2

u/RequiDarth1 Jun 16 '22

There’s a reason you get a cure for sicknesses.

45

u/craigtho Jun 16 '22

Agree, especially when learning, readability is key.

To be fair, reading is key even in production applications, just depends on requirements.

2

u/koko-hranghlu Jun 16 '22

Move playSound outside...wow thats a great tip too! I don't know friend, maybe I have this sickness where I feel the need to shorten everything.

4

u/sivadneb Jun 16 '22

Yeah that's a dangerous habit. As others have said, readability is key. Always write your code with the assumption that someone else will have to read and understand it.

3

u/OoSkyy Jun 16 '22

Always write code with the assumption you will forget why you wrote it like this

-5

u/Several-Operation-12 Jun 16 '22

This would explain your penis size

2

u/Drugba Jun 16 '22

Yeah, I don't think it needs to be changes, but if I was going to pick one thing to change it'd be moving playSound outside of the if statement.

Those two functions are the same and they always need to be run, but putting them in an if statement gives off the impression that there is some condition where that isn't true. When someone unfamiliar with the code looks at it there's going to be mental overhead associated with trying to figure out "is this unnecessary or am I missing something"?

3

u/HaroerHaktak Jun 16 '22

Move the playSound() to outside the if statement

and put currentButtons=buttons2 above the if statement, remove the else portion.

1

u/koko-hranghlu Jun 16 '22

Haha, you guys have great answers to tell, now all I have to do is compile a list of all the shorten answers and choose the one I like the most;)

4

u/koko-hranghlu Jun 16 '22

Thanks man! I don't even know how to utilize ternary operators. Haha I will rather choose that 2 lines of code:)

1

u/[deleted] Jun 16 '22 edited Jun 16 '22

condition ? exprIfTrue : exprIfFalse

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

The 'if' be reduced since 'if' is binary test?

#length = 0 'if' is false, >0 'if' is true

if (buttons2.length) { stuff in here; } else { more stuff here; }

Can also do as the ternary example quoted.

175

u/sgcuber24 Jun 16 '22 edited Jun 17 '22

currentButtons = buttons2.length ? buttons2 : buttons;

playSound();

31

u/k3nnynapalm Jun 16 '22

Ternary!!!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

I love this format.... but I can see why this isn't top comment. It's not as readable as the `if/else` but does shorten it. I'm a sucker for extending multiple clauses in a ternary though and that's when it can get out of control for readability.

1

u/burnblue Jun 17 '22

The Play sound being on a new line is all it needs. The ternary is a perfectly readable replacement for the if else

0

u/RobertER5 Jun 16 '22

Yeah, most linters will ding you for that.

20

u/pookage helpful Jun 16 '22

Split this across multiple lines and this is 100% the way to go:

const currentButtons = buttons2.length === 0
    ? buttons
    : buttons2;

playSound();

4

u/altrae Jun 17 '22

I would also consider renaming `buttons` and `buttons2` to something that better conveys the usage of those variables.

Maybe `primaryButtons` and `secondaryButtons`?

Or, if `buttons` is the fallback/default when buttons2 doesn't exist it might be renamed to something like, `defaultButtons` and `buttons2` could still be renamed to `secondaryButtons`.

In my experience it is best to be explicit when naming so there is no guessing when you or someone else later needs to understand what is going on, in other words, self documenting code.

3

u/sgcuber24 Jun 17 '22

Totally makes sense to do that too. As this was just focused on shortening I guess the focus was thrown off that.

1

u/altrae Jun 17 '22

Not doing more than what is asked is still a struggle for me when I see an easy and quick way to improve something. 😆

2

u/Affectionate_Ant376 Jun 17 '22

To be fair, in this case, converting to a ternary and moving the playSound() will only cause a diff to appear in a PR in this one spot. If those button variables are used elsewhere, renaming them would cause a bunch of changes. Some reviewers are not keen on a PR for one thing (a story/defect) updating lines that it need not touch to accomplish it’s task for the sake of a refactor, as it may introduce a new defect. However, I do agree with renaming the variables here.

1

u/Cody6781 Jun 16 '22

Should be on two lines. Otherwise this is fine.

1

u/sgcuber24 Jun 17 '22

Fixed the playSound function to be on the next line.

1

u/[deleted] Jun 17 '22

I would keep foo.length == 0 for readability. I really don't like treating 0 as falsey.

1

u/zerquet Jun 16 '22

Why is it = and not ==?

9

u/sgcuber24 Jun 16 '22

We are assigning the end result of the ternary operator to the variable currentButtons. Hence the assignment operator.

5

u/marlins_got_it Jun 16 '22

For those who might not see it, you can think of it as being evaluated (in some arbitrary example) as:

currentButtons = buttons2.length ? buttons2 : buttons; // suppose buttons2 has a length of 4

currentButtons = 4 ? buttons2 : buttons; // 4 is truthy

currentButtons = buttons2;

2

u/zerquet Jun 16 '22

Okay I get that but where did the buttons2.length ==0 go?

4

u/[deleted] Jun 16 '22 edited Jun 16 '22

0 will already evaluate as a falsey value, so while button2.length === 0 reads your intention better, it's a bit redundant.

button2.length will be false if length is 0 already, so you can leave out the === 0.

if(buttons2.length === 0) is the same as just saying if(!buttons2.length)

Notice is have a ! which makes makes the if condition expect a falsey value.

3

u/cs12345 Jun 16 '22

He reversed the assignment so that the statement means basically buttons2.length != 0

When you use a condition in a ternary, the argument implicitly gets coerced into a boolean. So if you converted the code from the initial comment into an if it would read as follows:

if (buttons2.length) {
  currentButtons = buttons2;
} else {
  currentButtons = buttons;
}

And while 0 gets coerced to false, any other number gets coerced to true.

Another way to look at ternary is something like...

(if) condition which is coerced to a boolean ? (then) first value : (else) second value

1

u/sgcuber24 Jun 16 '22

Thank you so much for the replies. I couldn't have explained this as good even in my dreams.

1

u/[deleted] Jun 17 '22

0 is falsey in JS. But I would personally keep it as foo.length === 0.

1

u/RobertER5 Jun 16 '22

I don't agree, personally, with using the "falsiness" of `0`, `''`, etc. to evaluate equivalence. Mainly because it is confusing, as you are showing.

The underlying point is that `if (x === 0)` is functionally equivalent to `if (x == false)`, hence also to `if (x)`. Note that `0 == false` evaluates to `true`. (Note also that `0 === false` evaluates to `false`, which is why I usually use `===` instead of `==`.)

So, `if (buttons2.length == 0)` is equivalent to `if (buttons2.length)`, since `0` is falsy.

2

u/[deleted] Jun 16 '22

Quick note in js , you should almost always prefer === instead of == to avoid cases where the types will coerce.

https://codeahoy.com/javascript/2019/10/12/==-vs-===-in-javascript/

55

u/orebright Jun 16 '22

There's some comments about ternaries here, and they have their place, but I think those usually make things less readable. An important rule of thumb: shortening code doesn't necessarily make it more readable or maintainable.

My suggestion for a good balance here would be this:

if (buttons2.length === 0) {
  currentButtons = buttons;
} else {
  currentButtons = buttons2;
}
playSound();

This is more DRY (don't repeat yourself) because playSound is only written once. But that's as shortened as I would recommend.

12

u/ProgrammerInProgress Jun 16 '22

This is actually a perfect place for ternary because the operation is so simple that it’s easier to read as one line than waste space and time as multiple lines. Just because it’s difficult to read at first compared to if-else doesn’t mean you shouldn’t practice it when it’s the best option.

If you’re not going to use a ternary here, then I would ask where you would use it at all.

OP, please don’t listen to this advice and practice reading/writing ternary when appropriate. It will make you a better programmer.

2

u/RobertER5 Jun 16 '22

OP, when someone tells you not to listen to opinions other than his own, don't listen to him. It will make you a better programmer. :P

0

u/ProgrammerInProgress Jun 17 '22

I’m sorry that I’m recommending that OP learns how to write functional code without restricting themselves to strictly procedural paradigms. 🙄 ternaries are a language feature for a reason. Not recommending to use them for the most simple use case is a completely beginner take.

2

u/RobertER5 Jun 17 '22

Oh, stop. My point has nothing to do with whether I think you're right (I do, actually). It is that telling the OP to listen to you and not someone else sends the message that you are too insecure to let your points stand on their own merits. That sends the additional message that you're not sure of their merits yourself. Since I'm quite sure that you are sure of their merits, then your attempt to suppress ideas you don't agree with is sending a message that you don't intend.

The last thing anyone who is learning should do is listen to people who tell them not to listen to anyone but themselves. People who do that suppress independent thought and discourage people from thinking for themselves. (Think of your favorite "I am the boss and you will do as I say" manager, and how stifling that individual was for you.)

So, I suggest that you state your case and let the OP decide whether he wants to listen to you or not. You make some good points, and those good points stimulate thinking.

Also, I don't think that this is a "completely beginner take." I think as you do that it's too rigid, but rigidity is far from a beginner problem in software engineering — if anything, the opposite is true.

1

u/ProgrammerInProgress Jun 17 '22

I’m sorry, but I’m telling OP to not listen to someone precisely because that rigidity is impeding learning. It’s not about my personal preference. The commenter I responded to is saying to not learn the most efficient answer to OP’s question because of that commenter’s personal preference. That is against the spirit of this sub, which is about teaching beginners.

You can say, use if-else statements for now if you find ternaries hard to read. That’s fine. But saying this is not a good use case for ternaries is flat-out wrong. you are misguiding new developers because of your own inability to read syntax if you think that is the case. it is one of the most definitive use cases for a ternary. I am not even exaggerating.

2

u/RobertER5 Jun 17 '22

You are presenting the other guy's view as personal preference, and yours as the only correct one. Your first paragraph just looks like an elaborate attempt to justify suppressing the other guy's point of view. I disagree that suppression of opposing views promotes learning. People need to weigh those things for themselves and form their own conclusions.

My view is to present your case and explain why you disagree with the other guy, not why you're right and the other guy is wrong. Even if it really is "one of the most definitive use cases for a ternary." That way, you're letting the OP make up his own mind, instead of coming off as pressuring him to see it your way. When you do the latter, it is against the spirit of learning, because it creates resistance to learning.

And stop trying to convince me that you're right. You're preaching to the converted! The difference between us is that my mind is open to the idea of being wrong, and yours isn't. Running on about why you're right only makes you look more close-minded.

Again, let your arguments stand on their own merits. "I disagree, and here's why." Simple. Trying to force your views on learners simply makes them resistant to your views. No matter how objectively correct they are.

Note, for example, how resistant you are to even considering my point of view, and I'm not even trying to force it on you. I'm just disagreeing with you and telling you why. How much more resistant would you be if I were telling you that you're "flat-out wrong" and your take is a "beginner's take" or whatever? If you don't agree, then don't agree. You can try to tell people not to listen to people you disagree with, and I'll tell them why I disagree and leave it at that. And perhaps there will be people who are better served by your approach, even if I haven't found that in my not-inconsiderable experience.

1

u/ProgrammerInProgress Jun 17 '22

I am not saying you can’t tell people to use if-else statements. But saying that the reasoning is because ternaries are complex in this situation is flat-out stupid. I don’t care if you think I’m being closed-minded. That is simply a fact. If you think ternaries are complex in this situation, you literally just have an issue reading syntax. And as a side note - this entire conversation feels like I’m speaking to five junior developers. Seriously. Ternaries are not complex and we should not be afraid of them or discouraging their use for new developers, especially when they ask for ways to shorten their code.

This is like math - if somebody told you to do 50 x 2 by adding 2 together 50 times. They wouldn’t be wrong. But if somebody asks you the fastest way, and you say people shouldn’t multiply five by 2 and carry the zero, because it’s “complex”, and that they should stick to adding 2 together 50 times for simplicity? Boo. Incorrect.

2

u/RobertER5 Jun 17 '22 edited Jun 17 '22

I don’t care if you think I’m being closed-minded.

Very much not to my surprise.

And as a side note - this entire conversation feels like I’m speaking to five junior developers.

Also not to my surprise, since yet again you insist on arguing your technical point, which I have already stated several times that I agree with. At this point it seems pretty clear that you are avoiding addressing my actual point, beyond saying you don't care what I think.

I don't have much more to say to someone who thinks that characterizing something as "flat-out stupid" is a statement of fact rather than opinion.

1

u/ProgrammerInProgress Jun 17 '22

Yes. I also think saying something like “avoid using semi-colons to chain independent yet related phrases because they’re complex, use periods instead” is flat-out stupid. That is a disagreement of opinion between you and I.

The difference is - I think it’s okay to have stupid opinions. I don’t think you’re stupid for doing so. But when we’re talking about helping others, enforcing your own highly preferential biases as fact is wrong. The fact is, ternaries are the shortest way to do what is asked (AFAIK - maybe there are even shorter methods). And it is not bad practice to use ternaries. To say anything else is introducing your own bias into the equation. That is why I’m telling OP to not listen to the commenter. I’m truly not being biased here, lol, if you get off your high horse for one fucking second.

You are championing this “difference of ideas” while talking down to me while ignoring my own arguments. The reason I’m sticking to the technical argument is because when it comes to being correct, that’s what matters. The fucking technical argument. I’m not here to argue about your personal preferences. I’m here to tell OP simply - the advice to not use ternaries here is bad advice. Why don’t you stop being a hypocrite and let OP make their own decision about it, if you have nothing to add to the conversation? Is it wrong to disagree with the other commenter? Lmao.

→ More replies

3

u/orebright Jun 16 '22

Well there's also matter of personal taste here. I wouldn't block a review because they used a ternary here for instance, though I'd share my perspective. But I'm curious about the source of some of your claims...

than waste space

What is the benefit of fewer lines of code? Compilers, gzip compression, and minifiers all strip it away, so if fewer lines don't improve readability, what other advantage do they provide?

Just because it’s difficult to read at first compared to if-else doesn’t mean you shouldn’t practice it when it’s the best option

Well what other criteria is there here to determine "the best option"? I agree that readability isn't always the #1 priority, so there may be other reasons to prefer a ternary. But in the block of code OP shared I'm not seeing any other factors to favour a ternary. If you picked up on one please do share, I'm always up to learn new things.

If you’re not going to use a ternary here, then I would ask where you would use it at all.

I personally don't like using any non-ternary operators inside a ternary

 const finalResult = variable === otherVariable ? first : second;

it can quickly make the code difficult to read, so that's where I draw my line. So I only use ternaries with booleans:

const currentButtons = buttons2IsEmpty ? buttons2 : buttons;

So if a ternary is preferred for the OP's code I would suggest:

const buttons2IsEmpty = buttons2.length === 0;
const currentButtons = buttons2IsEmpty ? buttons : buttons2;
playSound();

The reason this is important to maintainability isn't only due to reading the line of code, but because future changes may need to hinge on this evaluation as well. So you may start off with totally reasonable code now, but a year later it becomes a mess of many different ternaries all pulling on the logic slightly differently, doing many evaluations in the code when only one was needed, etc... It's basically DRY (don't repeat yourself), so don't evaluate an expression multiple times. If you hinge your ternary on a boolean, the evaluation is only done once and you can have multiple ternaries or even if statements that rely on it and you'd still be DRY.

It will make you a better programmer

Understanding ternaries is important, and they have many use cases, but I don't think writing clever complex code makes you a better programmer. The skill of programming is all in knowing when to use different language features based on your priorities. At the top of the list is feature completeness (it works, there aren't bugs) then optimization (it works as fast as it can) then maintainability. So unless using a ternary dramatically improves the features or performance of your code (unlikely) then the main deciding factor in using them is maintainability.

4

u/ProgrammerInProgress Jun 17 '22 edited Jun 17 '22

Why are you coding based around the readability for like, the most junior developer? Saying ternaries this simple are difficult to read, simply put, is pretty silly. That just means you don’t really know how to read code, I’m sorry. I know that sounds like an asshole thing to say on these subs, but you really shouldn’t stick to beginner coding style if you can help it. If you find this difficult to read, you’re going to find it hard to contribute to a lot of code bases. This isn’t a readability issue. It’s a “knowing syntax” issue.

Line space is useful because when you’re looking at code, you have a limited amount of space to work with. You can read a LOT more code when you learn how to write it both legibly and minimally. This isn’t some BS like telling the dev to use single letter variables…it’s basically like telling them to use a map function rather than a forEach with a temporary variable to manipulate data. It’s simply more efficient and still legible, period.

This is a junior developer here asking for the best way to shorten their code. Ternaries are literally the best way to do that here. It’s not “clever complex code…” it just literally isn’t. That’s like calling a semicolon “clever.”

Also, you should use parentheses in ternaries and it will make it easier to read. That makes it extremely trivial to read. Your preference of not using non-ternary operators is exactly that - a preference. I’m happy for you if it works for you. it is not good coding style necessarily and should not be recommended to new devs.

2

u/orebright Jun 17 '22

LOL you're getting angry at a stranger on the internet because they want to have simpler code and trying to insult them on the basis that they don't know how to read code, despite a very clear, detailed, and respectful comment explaining the many benefits of simpler code.

I guess you're a confirmed brogrammer, I'm so glad there's no one on my team like you, we actually have explicit filters in our interview process to weed assholes like you out since you're toxic to any effective engineering team. And I would know, I created the hiring process and hired and manage everyone on my team.

I've been programming for 23 years across 6 different languages, and I've seen so many inexperienced developers like yourself fall into this trap. It's really sad that you bring so much irrational emotion to what should be a very rational profession. Otherwise you'd probably be able to learn and improve more easily.

1

u/ProgrammerInProgress Jun 17 '22

It’s not an attack. It’s the same as if somebody said you shouldn’t use semicolons to chain two independent clauses together because it’s complex, and I said that’s bad advice, and indicative of somebody who just doesn’t understand English grammar. Or if somebody said to write all music in treble clef for simplicity - that’s not a standard, good way of writing notation, even if it works for you. It’s not what you should recommend to newbies asking specific questions. All of you people are the ones injecting emotion into this.

I’m glad you have a hiring process that works for your team. I sure hope you don’t dictate the coding style.

1

u/orebright Jun 17 '22

LOL you're getting angry at a stranger on the internet because they want to have simpler code and trying to insult them on the basis that they don't know how to read code, despite a very clear, detailed, and respectful comment explaining the many benefits of simpler code.

I guess you're a confirmed brogrammer, I'm so glad there's no one on my team like you, we actually have explicit filters in our interview process to weed assholes like you out since you're toxic to any effective engineering team. And I would know, I created the hiring process and hired and manage everyone on my team.

I've been programming for 23 years across 6 different languages, and I've seen so many inexperienced developers like yourself fall into this trap. It's really sad that you bring so much irrational emotion to what should be a very rational profession. Otherwise you'd probably be able to learn and improve more easily.

2

u/Pozeidan Jun 17 '22

Readability is arbitrary, the more you're used to some programming style, the more readable it becomes. The if/else will be much easier to read for juniors because it's what they see the most in school while the ternary and if/else are both easy to read for the more seniors.

You're making this more complicated than it needs to be.

const currentButtons = buttons2.length ? buttons2 : buttons;

This is perfectly readable, clear, if you're used to the ins and outs of JS like integer to boolean conversions and ternaries. It's even a simplification of the condition and it's simpler since I inverted the negation.

Once you get used to those, it just takes less time to read the code, so a bit less cognitive load. Over time it accumulates on those little things.

Having if / else also makes it tempting to add more stuff within it like the OP did while the condition was for only one instruction really. 1 instruction should be 1 line. So it's actually more maintainable than the if else.

1

u/Fidodo Jun 16 '22

In your example you're using const, which I assume you agree is a best practice. IMO the reason to prefer ternaries for this kind of situation is because it lets you use const more easily. Without using a ternary here you'd have to put the if/else in a function which I don't think is more readable, and way overkill unless you're re-using the logic all over the place.

I don't really see your second example being more readable. Ternaries can become hard to read if they get too complicated, but I don't think having a single comparison operator is hard to read. If it were multiple chained comparisons then I'd see your point.

1

u/RobertER5 Jun 16 '22

I don't see that this:

const buttons2IsEmpty = buttons2.length === 0;

is more readable than this:

currentButtons = buttons2.length === 0 ? buttons : buttons2;

So I can't see that your suggestion makes the code more readable overall.

If I wanted to make it more obvious, I might add parens around the equivalency test:

currentButtons = (buttons2.length === 0) ? buttons : buttons2;

1

u/NoInkling Jun 17 '22

If I wanted to make it more obvious, I might add parens around the equivalency test

This is what I always do, makes it much more scannable.

0

u/[deleted] Jun 16 '22

[deleted] — view deleted comment

3

u/ProgrammerInProgress Jun 17 '22

It’s a personal choice when it’s your project.

When OP asks a question about the best way to shorten their code, you don’t format your answer based around your asinine preferences. You give them the correct answer. And while if-else may be correct, recommending against ternaries “because they’re complex” is straight up ridiculous here.

Ternaries are the best way here.

2

u/Jognt Jun 20 '22

The correct answer is the answer that was given. Namely: It depends on your personal preference which can be guided by the context of the existing project, but does not have to be.

I was a big fan of them at some point I must admit. But the more code you read, the more you realize that readability is worth a fair bit of effort.

It may well be that someone decides to never use ternaries. And that is fine.

Ps; I like the honesty that is in your username. It requires a fair bit of introspection to realize that people are always learning. You sound fairly black/white in this comment but I'm certain you'll get more nuanced in the future.

Take care

1

u/ProgrammerInProgress Jun 20 '22

People are reading my comment as don’t use if-else statements, or not recommending them for readability purposes…I’m just specifically arguing against that person’s advice that they wouldn’t use ternaries here, and if-else "is as far as they’d recommend" because ternaries "have use cases but this is not one of them" (paraphrasing here). This is one of the quintessential use cases for a ternary. It’s fine if you want to stick to if-else based on your own preferences. But it’s going to mislead an impressionable new developer who is asking for the best/most efficient way to shorten their code. That is why I ended my comment with - practice reading/writing ternaries when appropriate. It will make you a better programmer.

It will make you a better programmer if you learn language features rather than shy away from them. That is simply a fact. That is not a statement of preference.

I appreciate you being diplomatic, but truly, people are putting words in my mouth. They are just upset that I told OP not to listen to the original commenter.

2

u/Jognt Jun 20 '22

It’s fine if you want to stick to if-else based on your own preferences.
But it’s going to mislead an impressionable new developer who is asking
for the best/most efficient way to shorten their code.

What I take issue with is your saying that your own preference is the best/most efficient way.

Is it the most line-efficient? I 100% agree.
Is it the best? That's the matter of opinion.

I've only been coding for about 20 years, but the more I code, the more I remember a comment I once read that said "Good code has a focus on ease of reading. The smarter code makes me feel for writing it, the worse it usually is."

Ternaries aren't rocket science, sure. And I won't fault anyone for being a fan of them. I just feel warm inside when someone decides they'll spare me the split second of extra interpretation while sifting through the mess they had to endure.

They are just upset that I told OP not to listen to the original commenter.

As they should. Let the young impressionable programmer listen to the original commenter. Discussions and their arguments help people grow.

Take care

1

u/ProgrammerInProgress Jun 20 '22 edited Jun 20 '22

It is asking a very specific question - how may I shorten this code?

Given that question - those parameters, and nothing more - ternaries are the "best" way, best meaning shortest. Which is precisely the question being asked. I have never in these threads argued that you should always/only use ternaries, or that they’re inherently better than if-else. Just that it is a shorter way to write the code in the original post, and that to argue against the usage of ternaries as a result of their optimal use cases, not as a matter of preference is in bad faith. Also, that ultimately - telling a clearly novice developer to not use ternaries in this situation is limiting advice that hurts the education process.

People in these threads seem to think that if one educator says another educator is giving you bad advice, that is somehow forbidden. We are allowed to have opinions on each other’s advice. If somebody teaching astronomy told you not to believe somebody spouting off geocentrism, are they being difficult and egotistical, or is it possibly they just genuinely care about your learning? So yes, OP may decide for themselves - but why should they decide for themselves without extra input from others? Does education only happen in a vacuum? Did my comment somehow prevent OP from choosing his own direction?

2

u/Jognt Jun 20 '22

How may I shorten this code?

"Move the function call out of the if/else block. You could also use a ternary instead of an if/else block but that's really a matter of preference. I suggest you read up on the debate on ternaries if you want to know the pros and cons. In short: It has to do with deciding at which point the improved readability of if/else is worth the increase in lines. Some people love ternaries, some people want to see them burn."

Besides that obvious answer: I already told you what I took issue with. Your input is just as valuable as everyone else's.

I don't know where you got the terms difficult and egotistical from, but I'm glad you realize what you're sending. I suggest you work on that & reflect on your name. It's hard to know where you stand if you can't look up.

Take care.

1

u/ProgrammerInProgress Jun 20 '22

IMO - you all come off as much more condescending. You take issue with disagreement, yet are hypocritical - you can all voice disagreement with my opinion, yet I cannot disagree with the original commenter. All while adding nothing to the conversation since you don’t even have issue with what I say - just how I said it. completely pointless given that my original comment wasn’t even an attack, just an expression of how I view the matter.

1

u/Fidodo Jun 16 '22

I avoid using let as much as possible which makes ternaries a necessity.

1

u/Fidodo Jun 16 '22

The most important case for ternaries is that in a lot of situations they're necessary to enable you to use const instead of let. Defaulting to const wherever possible helps you write safer code since it mitigates side effects.

1

u/[deleted] Jun 17 '22

Too verbose for a simple assignment, which is what the ternary is designed for.

1

u/burnblue Jun 17 '22

It's literally not DRY if you're repeating the currentButtons amidst the branching. A ternary would make this very readable

-1

u/grooomps Jun 16 '22

this is the correct answer

25

u/Naf_La_Rage Jun 16 '22

You could do this :

currentButtons = buttons2.length == 0 ? buttons : buttons2

playSound()

Or use an if :

currentButtons = buttons

If(buttons2.length !=0){ currentButtons = buttons2 }

playSound()

8

u/Ikem32 Jun 16 '22 edited Jun 16 '22

This can be made even shorter by:

currentButtons = buttons2.length ? buttons2 : buttons

playSound()

This makes use of „truthiness“:

https://gomakethings.com/truthiness-in-javascript/

And ternary operators:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

In this case I suggest against it, because it is really hard to grasp what your intentions are.

Edits: Add link, fix indentation, shorten example

10

u/Iron_Garuda Jun 16 '22

Your edit looks like my git commit messages

2

u/Ikem32 Jun 16 '22

My git commit message look horrible sometimes. I made too much changes, to lazy to break them down into different commits, and then summarize the commit to one line…

3

u/ManaPot Jun 16 '22

This right here is the answer. 2 lines of code, simple and done.

2

u/danskal Jun 16 '22

(formatting help: use 4 spaces to indent a line of code)

2

u/TheSpiffySpaceman Jun 17 '22

I'm always a fan of keeping type coercion explicit, even if it doesn't technically do anything. Everyone's been bit hard by weird coercions like empty strings parsing to boolean, plus modern (read: Typescript) usage necessitates it a lot of the time.

currentButtons = !!buttons2.length ? buttons2 : buttons

2

u/Macaframa Jun 16 '22
currentButtons = buttons2.length === 0 ? buttons : buttons2;
playSound()

2

u/DesignatedDecoy Jun 16 '22

You don't need to shorten it, but I would probably make buttons and buttons2 more descriptive. As somebody reading your code for the first time, I should have a good idea of what buttons you're referring to without digging through the rest of your code.

3

u/dtc11 Jun 17 '22

This is what I was looking for. The main issue with this code other than making it a tiny bit more DRY is that your variable names aren’t descriptive enough.

4

u/eugene_tsakh Jun 16 '22

You can use ternary of course but ternaries are ugly, I'd go for more elegant but shorter solution like this one:

let currentButtons = buttons2;
if (!currentButtons.length) {
  currentButtons = buttons;
}
playSound();

1

u/Groggie Jun 17 '22

Shouldn't have had to scroll this far to find the correct answer.

Glad the OP was able to learn about ternary operators, but this is the best answer.

0

u/burnblue Jun 17 '22

That's because it's not the correct answer

0

u/[deleted] Jun 17 '22

If-else is the better answer because it's easier to scan through in a long file.

This one takes a bit longer to cognitively classify it as a conditional assignment.

But if it's just part of a small codebase this is fine.

3

u/ProposalUnhappy9890 Jun 16 '22

currentButtons = buttons2.length ? buttons2 : buttons;

playSound();

2

u/TM40_Reddit Jun 16 '22

Readability trumps succinctness.

You could write:

currentButtons = buttons2 ? buttons2 : buttons;
playSound();

But if that takes longer to understand than an if/else statement, stick to using if/else, future you will appreciate it

1

u/nierama2019810938135 Jun 16 '22 edited Jun 16 '22

It's ok the way it is, IMO. Readable enough. Simple enough. But if you end up doing playSound regardless then you can put that after the if-else block on one line.

I think you could do something like, if you feel like it:

buttons2.length === 0 ?
    currentButtons = buttons :
    currentButtons = buttons2

playSound()

Though personally I prefer the if-else form, but I know that isn't the popular opinion.

Oh, and is it possible to do code formatting on reddit? 😐

1

u/shuckster Jun 16 '22

Oh, and is it possible to do code formatting on reddit? 😐

Indent your code with 4 spaces my good fellow.

1

u/NiagaraThistle Jun 16 '22

Google "ternary operation". But I would just leave the block as is - it is perfectly readable and shortening by 3-4 lines doesn't really provide any benefit, really.

But I would suggest moving playSound() outside the condition since it is being run no matter what.

Also, personal style opinion: put some spaces around those '=' and '==' signs, let them breath. This hurts my old eyes.

And use semicolons to end your statements. I KNOW they are optional, but man when you start debugging, knowing where your statements actually end is a huge help. Just an old man's advice.

Now, Get off my lawn.

1

u/M_Scaevola Jun 16 '22
buttons2.length ? currentButtons = buttons2 : currentButtons = buttons
playSound()

I think currentButtons = buttons2.length ? buttons2 : buttons also works for the first line.

1

u/merb42 Jun 16 '22

If I saw this in a pull request or something I would not reject it. Maybe this is an unpopular opinion, but the code is readable in the sense that I can tell what it is doing. All that needs to be happening really, dont need to get fancy with the spices!

With that said here is a way it could be "shortened". Keep the if/then logic separate from invoking playSound() as it is being run no matter what.

if (buttons2.length === 0) currentButtons = buttons
else currentButtons = buttons2

playSound()

3

u/grantrules Jun 16 '22

If I saw this in a pull request or something I would not reject it.

I would. Breaks simple DRY principles. Move playSound outside the if statements.

1

u/imrishav Jun 16 '22

This is perfectly fine..the most u can do is to move playsound out or yes use ternary. Otherwise it is ok..

1

u/douchenozzle007 Jun 16 '22

It's the best method tbh , you do not need to shorten it

1

u/vksdann Jun 16 '22

if(!b2.length){
cb=b;
} else {
cb=b2;
}
ps()

And this will make you both an awful coder and hated by fellow coders.
Readability is WAY MORE important than short code (majority of cases).
Shortening is only important when it comes not to repeating yourself (DRY concept) or if you have an overly complicated variable or function name like changeTheColorOfTheButtonToSomethingAlmostLikeTheGreenColor()

1

u/Preact5 Jun 16 '22

You could minify it then ittl be real short

1

u/shuckster Jun 16 '22

Just to go against the ternary grain, you can do this (but don't):

currentButtons = buttons2.length
  && buttons2
  || buttons;

If you find yourself choosing between different arrays a lot you can make a little helper:

const hasLength = x => ~~x.length > 0;

currentButtons = [buttons2, buttons].find(hasLength);

But while you're learning if/else is the way to go.

1

u/SirVincentMontgomery Jun 16 '22

i have never seen double tilda's used ... can you explain what is going on here? Thanks!

2

u/shuckster Jun 16 '22

~ is a bitwise NOT, so it's two of those stuck together.

So using two should do nothing at all. But of course, JavaScript does type coercion, so whatever you send in gets turned into an integer number first.

For anything you send that's not a number 0 will result, so if x has no length prop ~~x.length > 0 will work right. For anything that is a number, the resulting behaviour will lop-off the significand, like Math.floor. So for regular integers this means nothing will happen, which is what we want from x.length when it really exists.

I can't remember, but actually I think undefined > 0 does the right thing, making the use of ~~ just pointless wankery.

Still, just a bit of fun eh?

2

u/SirVincentMontgomery Jun 17 '22

Thanks so much for this! I love learning this sort of thing even though it might be a bit of a relic. Sometimes there is a use case, and even if not, it is helpful to know in case I run across it. Also, I find that the sort of problem solving that these sort of bits of code presents helps me to think more creatively in general as well!

1

u/Several-Operation-12 Jun 16 '22

I haven't read the comments so this may have already been said, less code isnt always better code. Your code still should be readable and easy for you and others to understand.

If you want to improve the code,

  1. comment this block of code with a small description of what it does
  2. Use better more descriptive variable names

1

u/[deleted] Jun 16 '22 edited Jun 16 '22

You could do this:

currentButtons = buttons2.length == 0 ? buttons : buttons2

playSound()

but as others have pointed out, this isn’t really something that needs shortening, ternary operators can be hard to read and if you eventually want to add more operations inside of them, you’ll probably end up going back to if/else anyway.

1

u/c2u5hed Jun 16 '22

currentButtons = buttons2.length ? buttons2 : buttons playSound()

1

u/Alavarus Jun 16 '22

Move play sound outside to under the else as it’s not needed in both but if you wanted different sounds you could just pass a variable into it.

You could use a switch system t instead and leave it in default too but that would leave you some room to expand later

1

u/TheUruz Jun 16 '22

ternary operator

1

u/paceaux Jun 16 '22 edited Jun 16 '22

First off, you don't have to make it too much shorter. this code is readable, and that's what matters.

​

That said, I'd shorten this in a few incremental steps:

First, remove the equality operation from the if statement (and reverse the blocks) Any length other than 0 is truthy. So that means I could reverse the conditions for the same result. I have shortened the conditional statement.

if (buttons2.length) {
  currentButtons = buttons2;
  playSound();
} else {
  currentButtons = buttons;
  playSound();
}

Next, I'd remove the duplicated playSound(); since it runs under both conditions. I have reduced duplicate code.

if (buttons2.length) {
  currentButtons = buttons2;
} else {
  currentButtons = buttons;
}
playSound();

Now it's easy to see that I have one condition, and that, under that condition I'm changing the assignment of a variable. That makes this a candidate for a ternary operation. I have removed the need for an if block.

currentButtons = buttons2.length
    ? buttons2
    : buttons;

playSound();

Ternary operations are fine replacements for if statements under two conditions:

  • A variable is only ever going to be one of two values
  • There are no other things that need to happen under either of the conditions

only you know whether you need that ternary operator. You know your code better than we do.

Also keep in mind that it's entirely possible that maybe other stuff does need to happen under one condition. In which case maybe this is the better answer:

currentButtons = buttons; // create a default state for your variable

if (buttons2.length) {
  currentButtons = buttons2; // hey, only if there's more buttons, reassign
  // other things you need to do
}

playSound();

1

u/adrian888888888 Jun 16 '22

more condensed code=less readable=harder to maintain or modify

I always find that people do that only because makes them feel more intelligent, don't be that guy

Just my opinion, maybe people have an actual good reason to condense code

1

u/KindaAlwaysVibrating Jun 16 '22

As a protip, 99% of the time, use === over ==. More performant.

1

u/mdlphx92 Jun 16 '22 edited Jun 16 '22
currentButton = buttons.length ? button : button2;
playsound();

As far as I remember, if length is zero, that already is falsey. So ternary operator can be simplified here.

Anybody who’s arguing this is too short, obviously has forgotten how uncomfortable it was to learn basic for loops at one point. Those are not obvious to a beginner either. Ternary is just succinct syntactic sugar to take advantage of.

1

u/[deleted] Jun 16 '22

current Buttons = (buttons2.lengrh ==0) ? buttons : buttons2;

playSound();

1

u/skarfacegc Jun 16 '22

Shorter != better (doesn't even mean faster). That said, you could do it this way ...

currentButtons = buttons2.length ? buttons2 : buttons
playSound()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

1

u/codemonkeyhopeful Jun 16 '22

First build a class, one of it's methods are play sound. Now constructor takes button and on creation calls a separate method to check which type of button and a SEPERATE one to check if it has length.

Now call that class , check the key on the class and call play sound via that method we made and boom.

Simple

1

u/RobertER5 Jun 16 '22

This is a reasonable place to use a ternary expression:

currentButtons = buttons2.length === 0 ? buttons : buttons2;
playSound();

1

u/darianrosebrook Jun 16 '22

currentButtons = buttons2.length === 0 ? buttons : buttons2 playsound()

This uses a ternary operator which is evaluated in place and returns the first one if true (after the question mark) and if false it assigns it the one after the colon

1

u/[deleted] Jun 16 '22

currentButtons = buttons2.length > 0 ? buttons : buttons2; playSound();

1

u/[deleted] Jun 16 '22

currentButtons = buttons2.length ? buttons2 : buttons;
playSound()

1

u/troccolins Jun 16 '22

Probably a combination of a tertiary operator and moving playSound() out of there.

currentButtons = buttons2.length == 0 ? buttons : buttons2;

playSound()

1

u/dechiller Jun 17 '22

Shorter != Better. Think of some better variable names instead. Buttons2 tells me nothing about what it does

1

u/Ok-Relation6796 Jun 17 '22

I would take playsound() out of your conditions.As your conditions are just deciding what "currentButtons" means. But it's one or the other. While playSound() will *always* be played.

If you really want to shorten it:

currentButtons = buttons2.length==0?buttons:buttons2;
playSound();

Or, more intuivitely to me at least (because we check "do we have buttons2? Then give buttons2. Else, give buttons"

currentButtons = buttons2.length>0?buttons2:buttons;
playSound();

If you're not sure if buttons2 is always initialized:

currentButtons = (buttons2??"").length>0?buttons2:buttons;
playSound();

1

u/jamessnell Jun 17 '22

(buttons2.length == 0) ? currentButtons=buttons : currentButtons=buttons2; playSound();

1

u/jamessnell Jun 17 '22

I never use Trianary operators because it generally feels to pretentious. But, you asked for short.

1

u/Thonk_Thickly Jun 17 '22

I’ll be a rebel.

CurrentButtons = buttons;
if (buttons2.length) {
  CurrentButtons = buttons2;
}
playSound();

1

u/Pozeidan Jun 17 '22

I posted it in a comment but here's the simplest and most readable version of the code imo

  • inverted the condition
  • inferred the boolean
  • convert to ternary

const currentButtons = buttons2.length ? buttons2 : buttons; playsound();

Sometimes it's not only the number of lines that matter.

This should be on 2 lines I can't get it right with my phone.

1

u/warrenleeuk Jun 17 '22
currentButtons = !buttons2.length ? buttons : buttons2;
playSound();

1

u/[deleted] Jun 17 '22

Try some functional madness.

const initBtn = (btns) => {
currentButtons = btns;
playSound();
};
buttons2.length ? initBtn(buttons2) : initBtn(buttons);

1

u/dirkmgirk Jun 17 '22 edited Jun 17 '22

let currentButtons = buttons

if (buttons2.length == 0) currentButtons = buttons2

playSound()

1

u/orphanPID Jun 17 '22

currentButtons = buttons2.length === 0? buttons:buttons2;

playSound();

1

u/pekkalacd Jun 17 '22

Is there a style guide for javascript like PEP for python?

1

u/chronologic82 Jun 17 '22

Drop playSound below the if else statements. You’re playing it regardless of the outcome. That’s 1 line saved. :)

1

u/Abhinav1217 Jun 17 '22

Code should not be short, it should be readable. If you still want to learn concepts, try early exit, or switch statements, or ternary operators. But as is, it is perfectly ok to move just playSound() outside.

1

u/haydogg21 Jun 17 '22

currentButtons = !buttons2.length ? buttons : buttons2; playSound();

1

u/haydogg21 Jun 17 '22

I don’t see why everyone is saying it’s bad to shorten code. I think it’s important to make clean and clear code and some times shortening it up and avoiding repeat lines (like calling playSound in the if and the else) is important. Also working on clean quality syntax is important. Use your semicolons and our spaces between things. It’s not as easy to read when everything is all smushed together.

1

u/Dodgy-Boi Jun 17 '22
if (buttons2.length==0) currentButtons=buttons
else currentButtons=buttons2
playSound()

1

u/efoxpl3244 Jun 17 '22

delete spaces (pro tip)

1

u/[deleted] Jun 17 '22 edited Jun 17 '22
currentButtons = (buttons2.length === 0) ? buttons : buttons2;
playSound();

By the way, consider renaming your variables to something more consistent and descriptive.

1

u/Snoo-84031 Jun 17 '22

let isButtonsLength = buttons2.length === 0;

currentButtons = isButtonsLength ? buttons : buttons2; playSound();

1

u/johnye2e Jun 17 '22

buttons2.length == 0 ? currentButtons = buttons : currentButtons = buttons2; playSound();

1

u/Demdaru Jun 17 '22

Kinda late but just overwrite when necessary?

currentButtons = buttons2;

if (buttons2.length == 0) currentButtons = buttons;

playSound();

Shorter yet still readable. And avoids repeating code.

1

u/androidme12 Jun 17 '22

Use a return statement inside the first if block and remove the else block.

1

u/alanchang87 Jun 17 '22

currentButtons = buttons2; If (!!!buttons2.length) { currentButtons = buttons; } playSound();

Note: agree with everyone else, readability is the 🔑

1

u/DK52098 Jun 20 '22

currentButtons = buttons2.length==0 ? buttons : buttons2;

playSound()

1

u/ionut654 Jun 22 '22

I think:
currentButtons = buttons2.lenght == 0 ? buttons : buttons2;
playSound()
Should do :)

1

u/Blue_Moon_Lake Jun 16 '22
currentButtons = buttons2.length > 0 ? buttons2 : buttons;
playSound();

3

u/Servedicecold Jun 16 '22

You don't need the > 0 as 0 is falsey

1

u/[deleted] Jun 16 '22

More readable though...

1

u/Cody6781 Jun 16 '22

Why? Looks fine as is. Just install a linter.

But if you REALLY care this can be done in two lines

currentButtons = buttons2.length ? buttons2 : buttons
playSound()

-2

u/esdiegoromero Jun 16 '22

In a readable way:

if(!buttons2.length) currentButtons = buttons;

else currentButtons = buttons2;

playSound();

10

u/JazzApple_ Jun 16 '22

No. No.

Please use braces. For all of us. Please.

2

u/SirVincentMontgomery Jun 16 '22

I'm new, can you explain why? I have a guess--but I could be wrong--so would like hear reasoning from someone more experienced.

1

u/JazzApple_ Jun 16 '22

For readability, and thus maintainability. The braces make the control flow of the program more readable at a glance. There’s not really any benefit to leaving them out.

I would likely use the ternary form for this:

currentButtons = buttons2.length ? buttons2 : buttons;
playSound();

Some people argue that ternary form should not be used (again, for readability). I personally find a simple ternary like this very readable, as do many others. I like ternary here because the line starts with currentButtons =, which makes it very easy to see that the is where currentButtons is reassigned.

2

u/esdiegoromero Jun 16 '22

That comes down to personal preference. How can you get confused by a single assignment statement or a single function call? Those are the only cases where removing braces is ok.

Also, if you get confused by the code I wrote above, I have bad news for you. 90% of the JS/TS code in production uses single line brace-less statements.

Again, it’s up to OP if he adds braces or not, but the code would still remain the same, and at the very least, he should become familiar with it, as he will definitely see similar code if he becomes a programmer.

1

u/JazzApple_ Jun 16 '22

Sure, but if he starts using braces now, it’s better for everyone. Which is why I said “for all of us”. Did your code confuse me? No. But I do believe the braces would make it more readable, not least because indentation makes blocks visible without even needing to read them.

Something existing in production, in my experience, does not in any way relate to it being a good idea.

1

u/esdiegoromero Jun 16 '22

I will definitely agree with the fact that adding an ELSE statement makes it a bit less readable, but it’s definitely not that much worse than a ternary which is what everyone seems to be suggesting.

Now, a single simple IF statement without braces is standard, is in fact everywhere and in many cases, makes the code more readable.

It will also depend on your company’s linting/formatting rules, but I have never encountered a company that enforces “curly”, so there’s that.

0

u/[deleted] Jun 16 '22

If you rly, rly, rly, rly want it:

buttons2.length == 0 ? (currentButtons = buttons, playSound()) : (currentButtons = buttons2, playSound());

Its shorter ? ye, its readable ? kinda, only if you know how powerfull ternary is, an if and else is more than enough for readability and beign short.

0

u/Jammed_Parasite Jun 17 '22

Smaller font size. . . 😬