JavaScript
9 JavaScript Tricks That Make Your Code Fantastic
The elegance of JavaScript goes beyond what you can imagine

JavaScript, with the original purpose of inventing it, was a simple language to add some functionalities to a website. Surprisingly, nowadays, it is everywhere and far more complex.
As web applications are becoming more and more complicated, JavaScript is evolving so fast as well. It’s not as easy as the old days to write neat, readable, and maintainable JavaScript programs anymore.
This article will summarize 9 practical JavaScript tips and tricks to help you write better front-end code and feel the beauty of this elegant programming language.
Talk is cheap, let’s check out the code.
1. Break Nested Loops in a JavaScript Way
Many programming languages have the break keyword for breaking out of a loop.
However, this keyword is merely for going out of the current loop. If you have to break from a nested loop, it could be hard to keep your code neat.
For example, how can you implement the following code?
for (let i in arr1) {
for (let j in arr2) {
for (let k in arr3) {
if (k === j - 4) {
// need to break out of the second loop
}
if (k === i - 3) {
// need to break out of the outermost loop
}
}
}
}In other languages, you probably need to declare boolean variables as “flags” for the outer loops, and check the breaking “flags” whenever entering the corresponding loops. This method works, but makes your code a little messy if there are many boolean flags.
JavaScript provides a syntax-level solution for this scenario — label.
You can use a label to identify a loop, and later refer to the label to break the corresponding loop.
Therefore, the JavaScript way to implement the above code is as follows:
loop1:
for (let i in arr1) {
loop2:
for (let j in arr2) {
for (let k in arr3) {
if (k === j - 4) {
break loop2
}
if (k === i - 3) {
break loop1
}
}
}
}The loop1 and loop2 are labels for these two outer loops, so it’s effortless to break the matching loop using its label. No need to declare other variables as “flags”.
2. Leverage Spread Operators for Destructuring Assignments
Spread Operators are the key to tidy JavaScript programs.
let leaders = {
me: "Yang",
T: "Elon",
A: "Tim",
MS: "Bill"
}
let {me, ...others} = leaders
console.log(me)
// "Yang"
console.log(others)
// {T: "Elon", A: "Tim", MS: "Bill"}As the above example shows, we used a spread operator, which is as simple as three dots, to assign the value of leaders["me"] into a variable named me, and the other key-value pairs into an array others.
In React, this trick is commonly used for receiving multiple values from the props when building a UI component.
3. Several Ways To Shallow Copy Objects or Arrays
As we know, non-primitive data types such as objects and arrays are passed by reference in JavaScript.
Therefore, as the following example, changing the “new” array will change the original array as well:
let a = [1, 2, 3]
let b = a
b.push(8)
console.log(a, b)
// [ 1, 2, 3, 8 ] [ 1, 2, 3, 8 ]To really copy the array a to a new array b, there are at least 4 ways in JavaScript.
Use the slice() method
The slice() method is to extract a part of an array. Given that it returns the extracted part in a new array, we can just extract the whole array and get the returned one as the copy:
let a = [1, 2, 3]
let b = a.slice()
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]Use spread operator
The spread operators are not only good at destructuring assignments, but also able to unpack items from arrays or objects:
let a = [1, 2, 3]
let b = [...a]
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]Using the built-in Array.from() method
In fact, there is a dedicated designed method to do the copy — Array.from():
let a = [1, 2, 3]
let b = Array.from(a)
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]Using concat() method
The concat() method is used to merge two or more arrays. Since this method returns a new array without changing the existing arrays, we can harness it for copying as well:
let a = [1, 2, 3]
let b = [].concat(a)
b.push(8)
console.log(a, b)
// [ 1, 2, 3 ] [ 1, 2, 3, 8 ]For objects, the three dots will work perfectly as well:
let leader = {
name:'Yang',
age:'30'
}
let fake_leader = {...leader}
fake_leader['skill']='coding'
console.log(leader,fake_leader)
// { name: 'Yang', age: '30' } { name: 'Yang', age: '30', skill: 'coding' }Another way is to use the built-in Object.assign() method:
let leader = {
name:'Yang',
age:'30'
}
let fake_leader = Object.assign({},leader)
fake_leader['skill']='coding'
console.log(leader,fake_leader)
// { name: 'Yang', age: '30' } { name: 'Yang', age: '30', skill: 'coding' }This type of copy is actually called shallow copy, which means it’s only one level deep. It only copies the references of the elements, not the elements themselves. Therefore, if the elements are objects or arrays, the copied array will still reference the same objects or arrays.
For instance, if the array a contains an inner array (two-level deep), the shallow copy cannot really copy them, and editing the array b’s inner array will also change a’s:
let a = [1, [2, 2, 2], 3]
let b = [].concat(a)
b[1].push(8)
console.log(a, b)
// [ 1, [ 2, 2, 2, 8 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]4. Use JSON Tricks for Deep Copy
To implement deep copy, a popular trick is to use JSON.stringify() and JSON.parse() together.
The idea is to serialize the object (or array) into a JSON-formatted string and then parse it back into a new object. This process effectively and elegantly creates a deep copy of the original array or object:
let a = [1, [2, 2, 2], 3]
let b = JSON.parse(JSON.stringify(a))
b[1].push(8)
console.log(a, b)
// [ 1, [ 2, 2, 2 ], 3 ] [ 1, [ 2, 2, 2, 8 ], 3 ]The JSON-based trick is useful in most simple cases. However, we need to know that to make this method effective, the object must be JSON serializable.
Let’s see a counterexample:
const obj = {
func: function() {
console.log("hello world!");
}
}
const cp_obj=JSON.parse(JSON.stringify(obj))
console.log(cp_obj['func'])
// undefinedThe value of the obj['func'] is a function. It cannot be copied through the JSON trick anymore.
In this case, we can harness a famous third-party JS library named lodash:
const _ = require('lodash');
const obj = {
func: function() {
console.log("hello world!");
}
}
const cp_obj=_.cloneDeep(obj)
cp_obj['func']()
// hello world!As demonstrated above, the cloneDeep method from lodash perfectly cloned the function inside the obj and it can be executed successfully on the new cp_obj.
5. Implement For Loops Skillfully
If you are still using the C/C++ style for loops in JavaScript, you definitely need to upgrade your skill.
Of course, the following code is correct, but it’s not “JavaScript” enough.
const arr = ['Y', 'a', 'n', 'g']
for (let i = 0; i < arr.length; i++) {
console.log(arr[i])
}
// Y
// a
// n
// gThe idiomatic ways to write the above code in JavaScript are as follows:
Use the forEach() method
The forEach method is ideal for iterating the elements of an array:
const author = [ 'Y', 'a', 'n', 'g' ];
author.forEach((c)=>{console.log(c)})
// Y
// a
// n
// gUse the map() function
If you read open-source JavaScript programs, you probably will meet the map() function. It’s one of the most popular methods in JavaScript:
const author = [ 'Y', 'a', 'n', 'g' ];
author.map((c)=>{console.log(c)})
// Y
// a
// n
// gThe behavior of the map() function is mostly similar with forEach(), but there is a significant difference:
The map() method returns a new array with the same length as the original array, where each element is the result of the function call on the corresponding element. The original array remains unchanged. The forEach() method doesn’t return anything.
The following code illustrates how to get a new array using the map() function:
const author = ['Y', 'a', 'n', 'g'];
const cute_author = author.map((c) => c + ':)')
console.log(cute_author)
// [ 'Y:)', 'a:)', 'n:)', 'g:)' ]
console.log(author)
// [ 'Y', 'a', 'n', 'g' ]However, we cannot get the new array with the forEach() function:
const author = ['Y', 'a', 'n', 'g'];
const cute_author = author.forEach((c) => c + ':)')
console.log(cute_author)
// undefined
console.log(author)
// [ 'Y', 'a', 'n', 'g' ]Use the for…of… structure
ES6 is a milestone for JavaScript. Many good features were introduced by this version. The “for…of…” method is one of them.
const author = [ 'Y', 'a', 'n', 'g' ];
for (let char of author){
console.log(char);
}
// Y
// a
// n
// gUse the for…in… structure
The “for…in…” syntax is also able to implement the same thing as we did. But we should be careful about the difference between “for…in…” and “for…of…”. The following code snippet explains it:
const author = [ 'Y', 'a', 'n', 'g' ];
for (let idx in author){
console.log(author[idx]);
}
// Y
// a
// n
// g6. The Fastest Way To Remove Duplicate Values of an Array
ES6 introduced a new data structure for JavaScrip — set. A set is a collection of items that are unique.
Thanks to the feature of sets, it makes removing duplicate values of an array much simpler.
const a = [1, 2, 1, 6, 6, 6, 9]
const unique_a = [...new Set(a)]
console.log(unique_a)
// [ 1, 2, 6, 9 ]As the above program shows, we can leverage the usage of the spread operator and Set() method to get unique elements of an array conveniently.
7. Reverse a String in One Line of Code
To reverse a string in JavaScript, we don’t need to write a for loop.
There are 3 steps to do this operation:
- Split the string into an array
- Reverse the array
- Convert the array into a string
These 3 steps need to harness 3 different built-in methods as follows:
const author = "Yang Zhou";
const reversedAuthor = author.split("").reverse().join("");
console.log(reversedAuthor);
// uohZ gnaYIt’s a decent one-liner, but to be honest, the JS way to reverse a string is not as elegant as Python. Due to its beautiful slicing syntax, Python can do the same thing much neater:
author = 'Yang Zhou'
reversed_author = author[::-1]
print(reversed_author)
# uohZ gnaYBy the way, an easy way to check if a JavaScript string is a palindrome is by comparing the string to its reversed version:
const author = 'YangnaY'
const isPalindrome = author.split("").reverse().join("") === author
console.log(isPalindrome)
// true8. Count Elements in an Array Quickly
How to count every element in a JavaScript array?
Using a for loop to go through the items one by one and count them in the process?
It’s a solution, but not an elegant solution at all. I would say lodash is a super useful JS library:
const _ = require('lodash');
const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
console.log(_.countBy(author))
// { Y: 1, a: 3, n: 2, g: 4 }If you prefer to not use a third-party library, it’s not hard to implement a similar function by yourself:
const countBy = (arr) => {
let count = {};
arr.forEach((e) => {
count[e] = (count[e] || 0) + 1;
});
return count;
}
const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
const charCount = countBy(author);
console.log(charCount);
// { Y: 1, a: 3, n: 2, g: 4 }If you merely need to count one specific item, the filter() method is a good choice:
const author = ['Y', 'a', 'a', 'a', 'n', 'n', 'g', 'g', 'g', 'g']
// Filter all elements equal to 'a' and return the length (count)
const countOfa = author.filter(x => x === 'a').length
console.log(countOfa)
// 39. Simplify Your Code with Comma Operator
Commas are more powerful in JavaScript because of the syntax of comma operators.
The comma (,) operator evaluates each expression (from left to right) and returns the value of the last one. It will be super helpful to simplify your code if you can leverage its power skillfully.
For instance, the following program demonstrates the utilization of the comma operator to accomplish two distinct purposes with a single line of code:
let sum = 0;
const squares = [1, 2, 3, 4, 5].map((x) => (sum += x, x * x));
console.log(squares);
// [1, 4, 9, 16, 25]
console.log(sum);
// 15Given that the comma operator always returns the result of the last expression, we can leverage this feature to avoid writing many return keywords.
For example, the get_author() function of the following code returns the arr after changing it:
const get_author = arr => {
arr.push('g')
return arr
}
console.log(get_author(['Y','a','n']))
// [ 'Y', 'a', 'n', 'g' ]This is the best scenario to let the comma operator show off:
const get_author = arr => (arr.push('g'), arr)
console.log(get_author(['Y', 'a', 'n']))
// [ 'Y', 'a', 'n', 'g' ]Thanks for reading ❤️. Which one is your favourite trick?
If you are new here, feel free to take a glimpse into my 10-year love-hate relationship with programming:
In Plain English
Thank you for being a part of our community! Before you go:
- Be sure to clap and follow the writer! 👏
- You can find even more content at PlainEnglish.io 🚀
- Sign up for our free weekly newsletter. 🗞️
- Follow us on Twitter, LinkedIn, YouTube, and Discord.
