JavaScript is the most popular programming language in 2020. It’s widely used in both frontend and backend web development, it’s in high demand, and it powers most of the frameworks that enable cross-platform app development. Whether you need a beautiful UI or a tool to process a mouse click, JavaScript presents the best solution regardless of the industry. You can read more about the current cream of the crop among programming languages here.
While JS is a powerful tool by itself, it truly shines when you grasp how to use various specific features inherent to this language. Below is a quick overview of seven tips and good practices that will make your code cleaner, faster, and more resistant to faulty behavior.
#1: Get Query String Parameters With the URLSearchParams API
Query string parameters are incredibly useful both on the server and the client side. When you work with JavaScript, you will regularly encounter the need not only to grab them but modify them dynamically.
The classic JavaScript way of getting the full query string uses window.location.search property:
console.log(window.location.search);
This method gets ugly really quickly since you have to parse the received string every time. Instead of doing the additional work, use URLSearchParams API to quickly grab and modify the query string:
// Assuming the query string to be “?post=1234&action=edit”
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get(‘action’)); // “edit”
console.log(urlParams.getAll(‘action’)) // [“edit”]
console.log(urlParams.toString()); // “?post=1234&action=edit”
console.log(url.Params.append(‘active’, ‘1’)); // “?post=1234&action=edit&active=1”
The API also comes with familiar Object methods, including keys(), entries(), and values():
var keys = urlParams.keys();
for (key of keys) {
console.log(key);
}
// post, action
#2: Filter Out Falsy Values
Filtering out null, false, undefined, 0, and other similar values out of an array can get messy if you use conditional statements. It also takes a toll on execution speed, and your code grows bulkier without adding any value.
When working with arrays, use the filter method to clean up your data instead. It accomplishes the task in just one line of code, and you don’t need to worry about these residue values in your array. You can use the method with Boolean to further improve the readability:
myArray.filter(Boolean);
#3: Retrieve Unique Values From an Array
Pulling unique values from an array is a widely required operation, though native JavaScript methods had overlooked it until the emergence of the spread operator. Now, to get an array of unique values from another array, you only need to use this tool with Set:
var j = […new Set([1, 2, 3, 3])]
// [1, 2, 3]
#4: Merge Objects’ Properties
The spread operator can be incredibly useful for several other operations with arrays and iterables. In particular, it comes in handy when you need to merge the properties of multiple objects into a new object.
const person = { name: ‘Peter’, age: ‘43’ };
const books = { genre: ‘horror’, author: ‘Stephen King’ };
// You decide what number of objects you want to merge
const mergeProps = {…person, …books};
As a result of the merge, JS has created a new object that contains all properties and values from the specified objects:
/*
Object {
“genre”: “horror”,
“author”: “Stephen King”,
“age”: “43”,
“name”: “Peter”,
}
*/
Keep in mind that when two identical keys are present, the priority is given to the last object’s value:
const animal1 = { species: ‘cat’, speaks: ‘meow’ };
const animal2 = { species: ‘dog’, food: ‘meat’ };
const newAnimal = {…animal1, …animal2}
/*
Object {
“species”: “dog”,
“speaks”: “meow”,
“food”: “meat”.
}
*/
#5: Require to Pass Values for Given Arguments
It can be useful to be able to set default values for function parameters. JavaScript goes even further, however, and additionally permits you to throw an error when a specific parameter is not passed to the function.
Watch how easy it is to make the name parameter mandatory:
const isRequired = () => { throw new Error(‘param is required’); };
const hello = (name = isRequired()) => { console.log(‘hello${name}`) };
Calling hello without providing a name will throw an error:
hello(); // not valid
hello(undefined); // not valid
While feeding it other values will work fine:
hello(null);
hello(Tiffany);
#6: Use Destructuring
Destructuring is a handy technique that allows you to unpack properties from objects or values from arrays into multiple variables. In JS, you can utilize the spread operator for destructuring and extracting data while keeping your code clean:
let { x, y, …rest } = { x: 1, y: 2, b: 3, c: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(rest); // { b: 3, c: 4 }
#7: Create Truly Empty Objects
In JavaScript, you can create empty objects with {}, but they still contain the usual object methods like hasOwnProperty. To create pure dictionary objects, use Object.create with null as the only argument:
let dict = Object.create(null);
The created object will have __proto__ set to undefined, and it will not contain any keys, methods, or properties until you add them manually.
Leave your vote
This post was created with our nice and easy submission form. Create your post!
Like what you read? Give author a thumbs up?
Bookmark this article to read later, drop a remark in comment section and share with your friends..