Doing multiple lines of code on one line

I’m trying to do multiple lines of code on one line. I am using conditional ternary (statement ? true : false;) and i wanted to know how i could do things that i would normally do on multiple lines, (change variable values simple) on one.

My geometry program is going to have have a lot of if statements, and i can cut that down 75% if i just can do multiple simple things per line.

Its not complicated code, i’m really only going to be changing the value of 3 variables at most.

I was thinking:

true === true ? this = that, that = 0 : console.log("false")

What is the problem with multiple lines? What problem are you trying to solve? I don’t think you’re going to get a performance boost and all you are going to do is make life a living hell for anyone that has to read that code. That would include you after you’ve been away from it for a few months.

Yes, you can do something like:

let age = 10;
let isServe;

age<21?(console.log("No beer for you!"),isServe=false):(console.log("Grab a cold one!"),isServe=true);

console.log("Serve = " + isServe);

But only if you hate any other coder that has to read it. Personally I’d much rather see:

if (age<21) {
  console.log("No beer for you!");
  isServe = false;
} else {
  console.log("Grab a cold one!");

There is a cult of “code concision” where people assume that more compact code is better. It is much harder to read and often adds not boost in performance.


For starters if you want multiple lines, then use if/else, not the ternary operator. You should try to keep these statements very trivial and simple, unless you like making things complex for no reason.

Cutting down 75% of lines is not something you as a developer should be concerned with a minifier will automatically cut down your code to that AND MORE.

If your program’s structure is going to have a lot of repetitive code just to check these things, then maybe you should refactor how your approaching your code so things aren’t so repetitive. I’d consider things to be readable to be the most important since lets be serious, your going to run into a bug and debugging hard to read code sucks.

Finally, if really want to use ternary operators, then fine, they do have their use case. If what your doing is fairly complex you can always consider providing functions for each part of the operator.

  ? displayTriangle(object)
  : displaySquare(object)
// I'm just guessing what sort of stuff your doing in your program
// also I try to indent my operators, so it reads top to bottom, and left to right, which IMO is a more clear than trying to find everything on one line.
1 Like

No it will be just as easy. Here is what it would look like:

var radius = 0;
var height = 0;
var volume = 0;
var answer = 0; 
if (shape==="cylinder") {
 answer = 0; 
    input[1] === "volume" ? radius = input[2], height = input[3], answer = eval((Math.PI*radius**2)*height) : input[1] === "height" ? etc : etc

I’m just repeating the same thing over and over again if i’m trying to find height, radius, or volume. Simple.

I also do this for cone, hemisphere and sphere.

You can see how many if statements that is going to be.

You did two things ‘per line’ in each of your true and false. I will be doing only 3 things, will that idea still work?

I’m going to be making this program at --> so anyone can just loo up and see what each equation means.

1 Like

This makes it very very difficult to read, debug and modify, it doesn’t simplify anything. Take the equations out into separate functions then call the functions of you want to make the code simpler. Single expression per line. Normally you want line lengths <= 80 characters. And if this is just running calculations, why do you need to assign variables?

Can you show more of his this is supposed to work, because the complexity of what you’ve come up with suggests that you can alter the logic quite a bit to get a much simpler solution: nested ternaries are generally a bad idea (as are very large amounts of conditional statements), it makes it very difficult to understand your own code

1 Like

“Cult of code concision” lmao. To play devil’s advocate, though, unless minifiers restructure if/else if/else statements into nested ternaries, and can turn nested assignments into less DRY code, don’t all these little optimizations add up to shorter bundle length in kb, and thus parsimoniously use the most costly resource top the user—network bandwidth? Obviously, without amazing comments, such code is going to be a nightmare to read, costing developer time, which leads to a feedback loop for figuring out the utility of concise code for a business. But, in the toy problem I’m proposing, isn’t concise code a way to gain market share, especially with the mobile market?

1 Like

I’m referring to some extent to groups like codewars where people seem to revel in compact impossible to read code that has as few characters as possible.

To play devil’s advocate, though, unless minifiers restructure if/else if/else statements into nested ternaries, and can turn nested assignments into less DRY code, don’t all these little optimizations add up to shorter bundle length in kb, and thus parsimoniously use the most costly resource top the user—network bandwidth?

I don’t know about transpiling. But let’s look at the numbers I count 102 characters in the ternary version and 109 in the if/else version. Again, number of lines is not the same as code length. That is a difference of 7 characters. So to cost a kb, you would need over 100 of these. And at that point all the rest of your code would be much larger so as to dwarf that 1kb extra. Really, if/else statements are just a fraction of the code.

And again, don’t join the cult of concision. When I started learning code, back in the Harding administration, that was important. Every program was a balance of speed and memory. You fought hard to optimize those things. Now there are other considerations: readability, maintainability, security, etc. Speed and memory have become so cheap that the others have become dominant.

How much time do you think you’re going to save? Especially if they are a regular user of your site, it’s cached anyway.

And who would want to read that code? With or without comments. And something that I have learned about coding - what seems obvious while you write it will be a puzzle when you look at it in a few months. We assume because it’s obvious now that it always will be. Anyone who has gone back to code after a year and had to figure out what the hell they were thinking knows what I am talking about. Always assume that a complete stranger is going to have to read your code.


The difference in size going to be pretty much irrelevant unless you have a very large program with a vast number of conditionals. And it means you end up with a codebase that only a single developer can write and maintain, the trade-off is awful: a tiny decrease in file size, zero benefit to performance and a useless codebase.

@DanCouper or you could have AI write it. What could go wrong?

When had the idea of doing multiple things on one line, i was thinking just simple stuff like assigning variables. It could just save space and have readability.

I also like compacting things because it looks professional and its better to look at. Compact code is better for writing comments, as you can basically explain more in a smaller space.

When stuff is compact, its less confusing. When code gets big, it gets confusing to see. Would you rather write 10 if statements or 10 simple 1 line conditionals.

This one of the longest conditional statements i have written (before this);

function translatePigLatin(str) {
    str = str.toLowerCase().split('');
    /^[aeiou]$/.test(str[0]) === true ? str.push('way') : /^[zbtg]$/.test(str[0]) === true ? str.push(str[0] + str[1] + 'ay' (str[0] = null), (str[1] = null)) : str.push(str[0] + 'ay', (str[0] = null));
    // Its only checking the first letter of the word
    return str.join('');

The reason you can find it a little hard to understand, is because you don’t know pig latin (most people).

Its easier to decipher a program if you know its intent. This is because you know what to look for, rather than just what it is doing. You can better connect thing and compact what its doing in your head.

I also cant stand people who code like:

if (this)
return this

Like really>???

1 Like

I was able to compact my idea down to:

function geo(shape, find, input1, input2) {
if (shape==="cylinder") {
    return find === "volume" ? find+" = "+(Math.PI*(Math.pow(input1,2)))*input2 : find === "radius" ? find+" = "+Math.sqrt(input1/(Math.PI*input2)) : find === "height" ? find+" = "+input1/(Math.PI*(Math.pow(input2, 2))) : null;
geo("cylinder", "height", 30000, 4)
// [shape, "volume", radius, height]
// [shape, "radius", volume, height]
// [shape, "height", volume, radius]

I just do this for each shape -->

So putting multiple things on one line isn’t really needed as much now (on mine), as i figured out a more compact way. But it is a still a great topic as discussion, as you might need/ want to do multi-able things on one line in the future. What will be a future update to JS? more compact ways to put things on one line?

Here is a function I wrote that might benefit you as I see you have come to a similar solution. As everyone else said you most certainly should be calling a function for all the repeated conditionals. In my function I just use the shape command to call a method containing the specific formula for calculating the area of a given shape. Area is the same but the way you find it among different shapes varies.

function area( type = "", dimensions ){
	const w = arguments[1];
	const h = arguments[2];
	const w2 = arguments[3];
	const areas = {
		circle( r ){ return Math.PI * r * r; },
		ellipse( w, h ){ return Math.PI * w * h; },
		parallelogram( w, h ){ return w * h; },
		rectangle( w, h ){ return w * h; },
		square( i ){ return i * i; },
		trapezoid( w1, h, w2, ){ return w1 * w2 * h; },
		triangle( w, h ){ return w * h / 2; },
		sector( r, a ){ return r * r * a / 2; }

	return areas[type.toLowerCase()]( w, h, w2 );

area("circle", 10);
area("square", 4);
area("rectangle", 4, 12);
area("rectangle", 4, 4);
area("triangle", 2, 4, 6);

That is very cool, i like it.

What do you mean by type=""

Whats the arguments for? How did you get w,h, and w2?

Can you put some comments in to explain it very basically.

Your code is like a compact switch statement, i like :smiley:

type = "" is the first parameter accepted by the function, setting it to an empty string is the default value of that parameter is it is not given to the function. Since that would only happen if no other arguments are given, then a user must not have passed any parameters to the function.

Setting your parameters to defaults is a good way to indicate the desired data type of that parameter.

arguments is the global object in all functions that stores the parameters passed in. The order the parameters are given in is the property index of that value. I am using dimensions parameter name as a placeholder to self-document that those are the expected data given after indicating the type. But I don’t use that identifier, instead I grab the values I need.

area("triangle", 2, 4, 6);
w = 2
h = 4
w2 = 6

In retrospect it’s missing some type validation, but other than that it’s loosely structured.

1 Like

Your code is still ‘big’, you’ve just extended it horizontally instead of vertically, making it impossible to read easily in a text editor. Regarding comments, code should be self-descriptive: comments are for the ‘why’ not the ‘how’. But if you handed that code to someone else you would need comments that described the ‘how’, because it’s too difficult to understand otherwise. It doesn’t look more professional, it just looks (and is) fantastically complicated; in a professional setting, you would be asked to rewrite that in a sane manner.

Would you rather write 10 if statements or 10 simple 1 line conditionals.

The latter, but what you have is not a set of simple conditionals, you currently have a set of very complex conditionals.

You can and should reduce the amount of code through sane methods, @emgo-dev describes one way (basically the Command pattern). And that’s the sensible way to do things: intent is extremely clear, there are no conditionals, that function has no side effects, no variables are reassigned, and there are 16 lines of code, none of which is more than 80 characters wide.

What you’re talking about, there are languages that are designed to allow that. Small, single use languages like Regex. Full languages like APL, J and K. But they are pathologically complex; by their nature, they’re very difficult to understand and need an extremely high level of knowledge/skill to be able to use.


When had the idea of doing multiple things on one line, i was thinking just simple stuff like assigning variables. It could just save space and have readability.

Again, you have several people telling you it is less visible. And the “space” you are saving is mainly on your editor screen - not in the finished product.

I also like compacting things because it looks professional and its better to look at.

Well, you have couple of professionals here saying the opposite. It may look cooler in an egghead-kind of way. It’s kind of cool know that it can be done. But why would you want to? I disagree with every reason you give. I would hate to have to work on that code.

“Your scientists were so preoccupied with whether they could, they didn’t stop to think if they should.” - Dr. Ian Malcolm, Jurassic Park

Compact code is better for writing comments, as you can basically explain more in a smaller space.

Your comment just tells what it does. That doesn’t tell how it does it. I know the refrigerator makes things cold. That doesn’t tell me how to fix it if something goes wrong. Your comment is just a label - a well named function could do as much. It doesn’t explain anything. To explain it properly would take 15 lines of comments. Or you could just write it out in a way that is much more obvious.

When stuff is compact, its less confusing.

Again, strongly disagree.

When code gets big, it gets confusing to see.

Then you need to break things up into functions and learn to compartmentalize.

Would you rather write 10 if statements or 10 simple 1 line conditionals.

That depends. That would be like saying, “Which is better: a screwdriver or a hammer?” That really depends.

If the ternary operations are clear, then that is what you need. Personally I don’t like your statement:

/^[aeiou]$/.test(str[0]) === true ? str.push('way') : /^[zbtg]$/.test(str[0]) === true ? str.push(str[0] + str[1] + 'ay' (str[0] = null), (str[1] = null)) : str.push(str[0] + 'ay', (str[0] = null));

I don’t think the innards of a ternary operation should have side-effects. I think they should only be used in assignment statements, returning simple expressions. If it takes me longer than two seconds to figure out what is going on, it shouldn’t be a ternary operator. If you get a job and you write code like that, every other developer is going to pitch in to hire a hitman. At the very least you need to get AAA because every day you are going to come out to find your tires slashed. You will be the most hated person there. I can’t even imagine having to debug or modify pages of code like that. And to be honest, the first time you have to go back after a year and modify pages of that code, you are going to want to take out a hit on yourself.

If the if statements you needed were so odious to your sight, you could have wrapped them up in a nice little function.

As one of my old programming teachers used to say, “Just because it’s true doesn’t mean that it is useful.” Yes, it is possible to code that way. I guess, to you it looks cool.

I don’t really advocate single line code unless there’s a very good reason for it. They could be hard to read and understand… down the road.

But sometimes I break this rule. See my thread on this exact issue

Yeah, but those are all readable. I still would have split the last if between two lines, but I can read and instantly understand what you wrote and what it does.

We’re not saying that things can’t be concise. Just that concision is not a goal unto itself, at the expense of readability.

1 Like

Yeah I agree. Readability and easy to understand is a big priority for me, and should also be for other coders.

After all, it will be humans that will be reading and trying to understand this text. Not machines. Machines couldn’t care less. I’d rather make it more efficient for humans to understand. I’m writing code for other humans to understand.

That is pretty unreadable, tbh. Even when you know pig latin. Why the second test? Why the === true when test returns a boolean? Why not just use string methods instead of turning everything into an array? This also doesn’t seem to work for words like ‘school’ or ‘freeCodeCamp’.

BTW I’m not against nested ternaries at all, but prefer them in the structure suggested by Eric Elliott:

1 Like

Now i agree that massive statements is not good, and will not use them in the future

As @forkerino said, there is two ways to do this.

Here is that massive conditional statement formatted with comments:

if (shape === 'cylinder') {
		return find === 'volume'
			? find + ' = ' + Math.PI * Math.pow(input1, 2) * input2
			// cylinder volume equation (true)
			: find === 'radius'
			// else it checks for radius (false)
				? find + ' = ' + Math.sqrt(input1 / (Math.PI * input2))
				// radus eqution (true)
				: find === 'height' 
				// else it checks for height (false)
					? find + ' = ' + input1 / (Math.PI * Math.pow(input2, 2))
					// height equation (true)
					: null;
					// else there a typo (false)


As you can see, anyone knows with basic knowledge of this statements that the : is for false, and after the ? is true. Its like reading a compact if statement. As long as you are not doing too much, if you format it like this its easy to read.

This also allows for comments, which is better.

What are your thoughts on this format? Assuming you only do one or two things per line (in true & false).

Yeah, i agree. For the price of not being readable you just expand in another direction/