Introduction
JavaScript offers powerful techniques that can be used to to do very complex tasks in one line, these can be called one-liners. These are short lines of code that can perform complex tasks, making your code compact.
Especially while working with react I am using these one liners a lot.
So, Let's Start! 🚀🚀🚀
Ternary Operators Instead of If/Else
Instead of using If/else
you can use ternary operators
.
Condition is described before question mark ?
and then we put true value and then :
colon and then false value.
Example:
let variable = condition ? 'hello' : 'bye';
// if condition is true then hello is assigned to variable
// otherwise bye is assigned
const age = 23;
let isAdult = age >= 18 ? "You're an adult" : "You're not an adult";
console.log(isAdult);
You can even use it for if / else if / else
conditions making more chained and complex decisions in easier and shorter code.
// example
const age = 23;
let isAdult = age >= 13 // if
? "You are a teenager!" // assign this
: age >= 18 // else if
? "You are over 18!" // assign this
: age >= 60 // else if
? "You are old!" // assign this
: "You are a kid!" // else
console.log(isAdult);
This is very much used in professional code when we want to execute something on the basis of some given conditions.
Printing values of an array
Instead of using a for loop we can use forEach()
method with implicit return values.
const nums = [1, 2, 3, 4, 5, 6];
nums.forEach(num => console.log(num));
Where num
is each element of the array being printed on console.
Filtering out values from an array
In a single line of code you can use filter()
method to filter out values of an array.
Filter method creates a new array of filtered out values.
const nums = [1, 2, 3, 4, 5, 6];
const filteredNums = nums.filter(num => num % 2 == 0);
console.log(filteredNums);
// output: 2, 4, 6
Finding if a value exist or not in an array
const nums = [1,2,3,4,5]
const element = 19;
const isElementFound = nums.includes(element) ? "Yes" : "No"
console.log(isElementFound)
// output: No
// includes() returns boolean value: true/false
This above code assigns No in the variable since there is no 19 value in the nums array.
Transforming an array using map
Map method can be used to transform existing values of an array and then return those values in form of new array.
const nums = [1,2,3,4];
const squaredNums = nums.map(num => num * num);
console.log(squaredNums);
// output: 1, 4, 9, 16
"map() and filter() methods are the most used methods in react"
Getting the length of an array or string
const string = "Shubh"
const stringLen = string.length;
console.log(stringLen);
//output: 5
Getting values out of an object
We use destructuring syntax to get out those values from the object.
const object = {
w: 0,
x: 1,
y: 2,
nestedObject: {
z: 3
}
};
const { w, x, y, nestedObject: { z } } = object;
console.log(w);
console.log(x);
console.log(y);
console.log(z);
// output: 0 1 2 3
Getting values out of arrays
We use destructuring syntax to get out those values from arrays.
const nestedArray = [1, 2, [3, 4], 5];
const [first, , [nested1, nested2], last] = nestedArray;
console.log(first); // Output: 1
console.log(nested1); // Output: 3
console.log(nested2); // Output: 4
console.log(last); // output: 5
Here you can see that we didnt print 2 because we skipped it, yes we actually skipped it, look here ➡️ [first, ,
This extra comma means skip the value
.
Swapping values using destructuring
let a = 10;
let b = 20;
[a, b] = [b, a];
console.log(a); // output: 20
console.log(b); // output: 10
Explanation: "put value of b in a and value of a in b" ➡️ [a, b] = [b, a];
Spread Operator to merge, split and manipulate arrays and strings
const array1 = [1,2,3,4,5];
const array2 = [6,7,8];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // output: 1,2,3,4,5,6,7,8
// spliting values of a string using spread operator
const stringArray = [..."Shubh"];
console.log(stringArray); // output: [ 'S', 'h', 'u', 'b', 'h' ]
// rest operator
const [firstValue, secondValue, ...restValues] = [1,2,3,4,5];
console.log(restValues); // output: [ 3, 4, 5 ]
Finding min and max values of an array using Spread operator
const numbers = [2, 5, 1, 8];
const minNumber = Math.min(...numbers); // minNumber will be 1
const maxNumber = Math.max(...numbers); // maxNumber will be 8
Default function parameters
function greet(name = "World") {
console.log(`Hello ${name}!`);
}
greet(); // Output "Hello, World!"
greet("Shubh"); // Output "Hello, Shubh!"
Conclusion
If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more upcoming content on JavaScript, React, and other Web Development topics.
For paid collaboration, you can mail me at: gmail
Connect with me on Twitter, LinkedIn and GitHub
Thank you for Reading :)
Top comments (25)
Please never use chaining in ternary operators because it's hard to follow and can lead to errors.
They are not more difficult to read than the 8f-else-if chains
Right off the bat the nested ternaries should be considered a crime
No, they shouldn't
Totally agree but its still a valid one liner in js :)
Can you elaborate please, i'm new to programming, and would love to know why.
Thank you.
the danger is precedence order of the operations in the ternary operator expression.
expressions should be put in parantheses.
Thank you!
might have to update your article. swapping values with const won't work... this could be misleading for someone starting fresh.
also I don't agree with the use of chaining ternary operator like others. but it could be just my perspective.
anyways, good luck!
That ternary chaining is absolutely horrible for readability.
Done Thanks a lot!
Swapping values using destructuring with const
🫣🥶
Did you even test that?
yes it works but the only thing that needs to change is
let
instead ofconst
That's my point... Not tested. Maybe even AI generated....
No it doesn't
It would return a SyntaxError because
a
is already declared.That was a mistake since i mostly use const while creating variables so yeah it was a habit of using const there, fixing it now, Thanks!
I don't that use const as much as I should :).
and prefer dynamic typing, for creativity.
If the dude doesn't know the difference between let and const, it's better to forgo the whole article, sadly.
It was a mistake! Fixing it now :)
If you're a fresh coder right out of college or maybe a deep back-end dev who is just starting to mess with front end, and you ever give me a nested ternary like that in a pull request, I will come to your place, wherever you live, off-shore, domestic, doesn't matter, and I will punch you directly in the mouth.
in the face*
thank you Shubh, my friend.
your list is reconforting, and definitely good to know :).
about the chained ternary operations, precedence should be taken care of.
You have to be trolling with the chained ternaries…. right? No one writes code like this in the real world.
I have seen that happen in react code while rendering multiple possible jsx code