- JavaScript If-Else on One Line
- The Ternary Operator – One Line If-Else Statements in JavaScript
- Nested One-Line If…Else…Else If Statements in JavaScript
- Multi-Line Ternary Operator in JavaScript
- Be Careful with the Ternary Operator
- Conclusion
- Multi-Line JavaScript Strings
- Recent Features
- Welcome to My New Office
- Create Namespaced Classes with MooTools
- Incredible Demos
- Build a Toggling Announcement Slider Using MooTools 1.2
- Form Element AJAX Spinner Attachment Using jQuery
- Discussion
JavaScript If-Else on One Line
In JavaScript, you can have if-else statements on one line. To write an if-else statement on one line, follow the ternary conditional operator syntax:
condition ? true_expression : false_expression
const age = 20; const age_group = age < 18 ? "Child" : "Adult";
This is a useful way to compress short and simple if-else statements. It makes the code shorter but preserves the readability.
However, do not overuse the ternary operator. Converting long if-else statements into one-liners makes your code verbose.
The Ternary Operator – One Line If-Else Statements in JavaScript
Writing a one-line if-else statement in JavaScript is possible by using the ternary operator.
Here is the syntax of the one-liner ternary operator:
condition ? true_expression : false_expression
For instance, let’s say you have an if-else statement that checks if a person is an adult based on their age:
Running this code prints “Adult” into the console.
This code works fine. But you can make it shorter by using the ternary operator.
This way you were able to save 4 lines of code. And the code is still readable and clear.
Nested One-Line If…Else…Else If Statements in JavaScript
Trying to express everything in one line is no good. The ternary operator should only be used when the code can be made shorter but the readability remains.
However, JavaScript allows you to construct nested ternary operators to replace if…else…else if statements.
condition1 ? true_expression1 : condition2 ? true_expression2 : else_expression2
if(condition1) < true_expression1; >else if(condition2) < true_expression2; >else
For instance, you can convert an if…else…else if statement like this:
const age = 17; if(age < 17)< console.log("You cannot drive."); >else if( age == 17 ) < console.log("Go to driving school."); >else
To an expression like this using the nested ternary operator:
However, you already see why this is a bad idea. The nested ternary operator only makes the code hard to read in this example. Using the ternary operator this way is ineffective.
In this situation, you have two options:
- Use a regular if…else…else if statement instead of a nested ternary operator. That is still perfectly valid JavaScript code!
- Break the nested ternary operator into multiple lines.
Let’s next understand how the latter option works.
Multi-Line Ternary Operator in JavaScript
Your motive to use the ternary operator is probably to express if-else statements as one-liners. But it is good to know you can break a ternary operator into multiple lines too.
As you already saw, the one-liner ternary operator syntax in JavaScript is:
condition ? true_expression : false_expression
But you can break this expression into multiple lines this way:
condition ? true_expression : false_expression
Breaking the expression to multiple lines works with nested ternary operators too.
Generally, this type of nested ternary expression:
condition1 ? true_expression1 : condition2 ? true_expression2 : else_expression2
Becomes a multi-line ternary expression:
condition1 ? true_expression1 : condition2 ? true_expression2 : else_expression2
Let’s see a concrete example of this by going back to the example of checking the age of a person:
const age = 17; console.log(age < 17 ? "You cannot drive." : ( age == 17 ? "Go to driving school." : "You can drive."));
This ternary expression is rather verbose. Assuming you do not want to put it back to a regular if…else…else if statement, you can break it down to multiple lines:
const age = 17; console.log( age < 17 ? "You cannot drive." : age == 17 ? "Go to driving school." : "You can drive." );
However, it is up to a debate whether this makes the code any better than the original if…else…else if statement. Anyway, now you know it is possible.
Be Careful with the Ternary Operator
Your goal is to always write readable and concise code.
Even though the ternary operator is a built-in mechanism, you can treat it as a “trick in a book”.
If you want, you may use the ternary operator to replace basic if…else statements with one-liners. However, avoid increasing the code complexity by replacing longer if…else…else if statements with one-liners. It is more than fine to use regular if…else statements in your code!
If you still want to use a lengthy ternary operator, please make sure to at least break it down into multiple lines.
Conclusion
In JavaScript, you can turn your if-else statements into one-liners using the ternary operator. The ternary operator follows this syntax:
condition ? true_expression : false_expression
const age = 20; const age_group = age < 18 ? "Child" : "Adult";
JavaScript also supports nested ternary operators for if…else…else if statements. This way you can have as long chains of ternary operators as you like.
condition1 ? true_expression1 : condition2 ? true_expression2 : else_expression2
Usually, a nested ternary operator causes a long one-liner expression. To avoid this, you can break the ternary operator down to multiple lines:
condition1 ? true_expression1 : condition2 ? true_expression2 : else_expression2
Keep in mind that using a one-liner if-else statement makes sense if it improves the code quality! Applying it on a complex if…else statement does not make sense as it decreases the code quality.
Here is a “good” example of a rather bad usage of the ternary operator:
const age = 17; console.log(age < 17 ? "You cannot drive." : ( age == 17 ? "Go to driving school." : "You can drive."));
Thanks for reading. Happy coding!
Multi-Line JavaScript Strings
The JavaScript language performs automatic semicolon insertion at the end lines, so creating multiline strings usually ends up looking something like this:
var multiStr = "This is the first line" + "This is the second line" + "This is more. ";
String upon string of concatenated JavaScript mess. ugly, slow, and . ugly. Many novice JavaScript developers don't know that there's a better way to create multiline strings:
var multiStr = "This is the first line \ This is the second line \ This is more. ";
Adding a backslash at the end of each line tells the JavaScript engine that the string will continue to the next line, thus avoiding the automatic semicolon insertion annoyance. Note that the second string includes line breaks within the string itself. Just another nice tip to add to your JavaScript arsenal!
Recent Features
Welcome to My New Office
Create Namespaced Classes with MooTools
Incredible Demos
Build a Toggling Announcement Slider Using MooTools 1.2
Form Element AJAX Spinner Attachment Using jQuery
Discussion
It should be noted the backslash multiline string notation is not part of any ECMAScript standards and can break various minifiers. Otherwise, it’s definitely good to know!
I think this is quite controversial. Other than issue with minifiers, ‘backslashes’ can cause error if there is any white space after it. I often write multiline string as arrays and join, this way IMO is quite readable.
var multiStr = [
"This is the first line",
"This is the second line",
"This is more. "
].join("\n");
You can also see the intent here wether it’s about construct a real multiline string (with join(“\n”)) or just try to avoid writing a long string (with join(“”)).
/**
* @tungd : +1
*
* Moreover, you can't indent your code or it will add the whitespaces to the string.
*
* e.g:
**/ "my string \
is long" === "my string is long"; // and not "my string is long"
I forgot about this implementation till this morning while I was working on some jQuery forms. Funny I came across this now.
While I understand the concern for minifiers, we don’t write JS for minifiers, we write JS for JS interpreters. JS minifiers need to improve. If the minifier you use doesn’t support this basic pattern, however, feel free to work around it.
When I first found out that you could escape newlines, I thought it was a pretty neat way to split a single line of text over several lines. It’s advantages are that it’s faster than concatenation and more readable than having the text spanning one long line that you have to scroll through. However, it’s slower, less readable and less maintainable than having the text on one line and just turning on word wrap in your IDE. It’s also error prone, for reasons explained above. The most common reason for including large, unbroken chunks of text in a JavaScript file is for the purposes of HTML injection, in which case I would personally include the text in a separate tag, which I then retrieve with innerText and store in a variable. That way, I can format it as HTML, but it won’t get shown on the page, nor get interpreted as JavaScript. Yes, it’s slower, but it’s much more readable and maintainable.
You can just use the first one, minifiers (at least uglify-js) will change the var a = "foo" + "bar"; into var a = "foobar"; anyway.
In Google javascript guide, they advise “”+ instead of \ because . «The whitespace at the beginning of each line can’t be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.» http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Multiline_string_literals#Multiline_string_literals What do you think? Could you please enlighten me? Thank you.
@David: i don’t think there’s much case for “improving” minifiers to support the escaped line feed. The structure itself is non-standard, some browsers don’t support it, so minifiers that adhere to the standards are right to reject that method. Besides, your own point defeats itself: it we write JS for JS interpreters, the implication is to write JS for the broadest compatibility possible. Escaped line feeds reduce that compatibility. And minifiers are increasingly essential tools to reduce bandwidth and execution time, so we SHOULD write JS with minifiers as part of the plan. Personally, i find it no easier to read an escaped line feed than “a “+ “b “+ … There’s always something interrupting the end of the line. Sure, concatenating strings suffers a performance hit, but at the point it becomes significant, one should ask why such long strings are being statically coded into Javascript.
Am I missing something? It looks like string literal line continuations _are_ in the spec: http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4 Maybe it’s relatively new but that’s from 2011…?
Ah, I read that more closely and now see that the backslash is only valid if it’s part of something else–not by itself like this post describes. My bad.
Michael Haren: The backslash *isn’t* “by itself”; it’s the character right before a newline. However, the spec does specify (ha!) that the newline is *not* a valid character for escape purposes. The only valid escape characters after a backslash are listed explicitly: ‘ ” \ b f n r t v
console.log(`i am a multiline string and it works but not on all browsers - yet `);
Your two examples produce different results. I think many people will be surprised by the amount of whitespace in your multiline example.
But that’s not a multiline string! That is a multiline string literal representing a single-line string. If you want to produce a multiline string (a variable in memory that, upon inspection during execution, contains more than one line of text), you don’t need the trailing backslash but the classic backslash + new line modifier. The trailing backslash allows us to introduce line breaks in a string literal, mostly for clarity in the source code, without inserting them in the actual string represented by the literal. https://jsfiddle.net/q68cktfq/
var mlString = `I am multiline \ hear me roar`;