- 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
- JavaScript One-Liners to Use in Every Project
- 1. How to Capitalize Text
- 2. How to Calculate Percent
- 3. How to Get a Random Element
- 4. How to Remove Duplicate Elements
- 5. How to Sort Elements By Certain Property
- 6. How to Check if Arrays/Objects are Equal
- 7. How to Count Number of Occurrences
- 8. How to Wait for a Certain Amount of Time
- 9. How to Use the Pluck Property from Array of Objects
- 10. How to Insert an Element at a Certain Position
- Become a Professional React Developer
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!
JavaScript One-Liners to Use in Every Project
JavaScript is a powerful language that can do a lot with very little code.
In some cases, the amount of code you need to write doesn't exceed more than a single line, which is why they are known as one-liners.
Let's go through 10 essential one liners worth using in virtually every JavaScript project you create.
1. How to Capitalize Text
Capitalizing strings is not a built-in feature of JavaScript.
To fix this, we can make a capitalize function which accepts some text and makes the first letter uppercase, then appends the rest of the string.
This one-liner is useful for just about every kind of text you want to capitalize. I use it most frequently with displaying users' names.
const name = "robert"; capitalize(name) // "Robert";
2. How to Calculate Percent
const calculatePercent = (value, total) => Math.round((value / total) * 100)
Calculating a percent is pretty easy and just involves some simple math. It is an essential task if you want to display user progress, for example in incrementing a progress bar.
calculatePercent accepts a certain amount, divides it by the total amount, then multiplies it by 100. Finally, we use Math.round() to round the result up to the nearest whole number.
const questionsCorrect = 6; const questionTotal = 11; calculatePercent(questionsCorrect, questionsTotal); // 55
3. How to Get a Random Element
const getRandomItem = (items) => items[Math.floor(Math.random() * items.length)];
Getting a random element and array is really nice when you want to make things unique for your user.
For example, you might want to show your users a congratulations message based on some action. But you probably don't want to show them the same one every time, because that would get repetitive and boring.
getRandomItem uses the Math.random() function, which returns a decimal between 0 and 1. This is multiplied by the length of the array to select a random index, which can be used to select a random element.
const items = ["Nicely done!", "Good job!", "Good work!", "Correct!"]; getRandomItem(items); // "Good job!"
4. How to Remove Duplicate Elements
const removeDuplicates = (arr) => [. new Set(arr)];
Removing duplicate values in an array is an essential task in JavaScript.
For example, you might be adding one user to another user's friends list, but you don't want that user to be added or displayed twice.
This removeDuplicates function leverages the Set constructor in JavaScript, which removes any duplicate (primitive) values by default. After that, we use the spread operator . to spread its values into a new array.
const friendList = ["Jeff", "Jane", "Jane", "Rob"]; removeDuplicates(friendList); // ['Jeff', 'Jane', 'Rob']
5. How to Sort Elements By Certain Property
const sortBy = (arr, key) => arr.sort((a, b) => aJavascript function on one line > bJavascript function on one line ? 1 : aJavascript function on one line < bJavascript function on one line ? -1 : 0);
A common task when displaying data in JavaScript is to sort it based on some property.
This sortBy function uses the native sort method, compares the elements in the array based off of the provided key, and sorts the array in ascending order.
Where would this be helpful? If you're fetching data that is supposed to be in a certain position based off of a position key, sortBy will make sure that those elements are placed in the proper order.
const lessons = [< position: 1, name: "Intro" >, < position: 0, name: "Basics" >]; sortBy(lessons, 'position'); // , //
6. How to Check if Arrays/Objects are Equal
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
It's easy to check for equality with JavaScript primitives, like numbers and strings.
Checking for equality between arrays and objects is a bit harder, however. Fortunately, there's a neat trick you can use with JSON.stringify to convert arrays or objects into a JSON string. If all the elements match, isEqual will return a value of true.
This is very handy when you expect multiple inputs from a user, for example if they're answering a question and you want to compare it to the correct solution.
isEqual([1, '2'], [1, 2]); // false isEqual([1, 2], [1, 2]); // true
7. How to Count Number of Occurrences
const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a), 0);
Another helpful array-based one liner is to count the number of occurrences of an element in an array. It uses the .reduce() function. If the value is found in the array, it increments a counter by one.
One useful example might be a poll to determine what most people voted for.
const pollResponses = ["Yes", "Yes", "No"]; const response = "Yes"; countOccurrences(pollResponses, response); // 2
8. How to Wait for a Certain Amount of Time
const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
In your application, you might want to wait for a certain period of time. For example, if you want to delay an animation or are waiting for an important operation for finish.
You can provide the wait function a certain amount of time to wait in milliseconds. Because it uses a promise, you can use the then callback or the await keyword to make sure it has finished.
wait(2000).then(() => goToSignupPage());
9. How to Use the Pluck Property from Array of Objects
const pluck = (objs, key) => objs.map((obj) => objJavascript function on one line);
If you need to extract data from an array of objects and are not interested in getting all the data that is returned, use the pluck function.
It takes an array of objects and a property that each of the objects contains. The function maps over this array and returns an array with only the values of the property that we specified.
For example, if we have an array of user data, but we want to convert it just to an array of their names, pluck can do this.
const users = [< name: "Abe", age: 45 >, < name: "Jennifer", age: 27 >]; pluck(users, 'name'); // ['Abe', 'Jennifer']
10. How to Insert an Element at a Certain Position
const insert = (arr, index, newItem) => [. arr.slice(0, index), newItem, . arr.slice(index)];
If we want to put an element in a precise location in an array, we can use this special insert function.
To use it, we just need to pass to insert the array we want to transform, the index where we want the element insert, and the element to insert.
This is a great function to use instead of .splice() because it does not mutate the original array. It creates a new array with the help of the slice method, by slicing the array into two parts around the specified index and then creates a new one.
const items = [1, 2, 4, 5]; // insert the number 3 at index 2: insert(items, 2, 3); // [1, 2, 3, 4, 5]
Become a Professional React Developer
React is hard. You shouldn't have to figure it out yourself.
I've put everything I know about React into a single course, to help you reach your goals in record time:
It’s the one course I wish I had when I started learning React.
Click below to try the React Bootcamp for yourself: