Most people don’t know these incredible features of JavaScript.
Photo by Kristina Flour on Unsplash
Do you think you know all the hidden, precious JavaScript features and tricks?
Well, I used to think the same until recently when I started to look out specifically for helpful features and tricks that are barely talked about.
Indeed JavaScript is evolving every year with the introduction of doing complex or tedious tasks in just a few lines of code, but some aspects of the language have been baked into it for years however, they are not much talked about.
Nonetheless, these features help you overcome some of the most common issues we encounter while using this language.
Below are 7 less popular features of JavaScript:
1. Dynamic Imports
Most of us are used to the standard way of importing modules. Technically, it is the static method of importing modules.
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
However, not many know that there exists a dynamic way of importing your modules, that is, you can import modules conditionally and as per your demands.
To dynamically import, use the keyword import
as a function and pass in the module name. It will return a promise, resolving into a module object.
import('some-module')
.then(obj => ...)
.catch(err => console.log(err))
Although static imports are still preferable for loading initial and vital modules, dynamic imports offer a few benefits:
Static imports can increase the loading time of your code and can also lead to unused modules.
Static imports specifier strings can’t be generated dynamically.
Static imports can lead to unnecessary memory usage.
2. Templates Literals
Unless you know and use React, there is a high chance that you might not be aware of or use template literals.
Introduced in ES6, template literals essentially make your string literals behave like it’s on steroids.
Below is an example of the template literal.
let a = `Hello World! This is a template literal`;
Notice that we have used backticks instead of single or double quotes to wrap our text.
Template literal provides the following advantages:
Ability to substitute variables directly into the string, that is, string interpolation.
Strings can have multiple lines.
Safe to include it in HTML.
The normal string can span multiline as well and the syntax for that is given below:
console.log('string text line 1\n' +
'string text line 2');
However, with template literal, it becomes easier to understand and also looks cleaner.
console.log(`string text line 1
string text line 2`);
Both the code logs multiline string but without a doubt, the template literal one looks simpler.
When used correctly, it can lead to cleaner, shorter and simpler strings.
3. Nullish Coalescing Operator
A logical operator, the nullish coalescing operator(??) can save you from unforeseen errors and logs.
Using this operator, you can quickly check if the variable is null and if so, set the default value.
const foo = null ?? 'John Smith';
console.log(foo);
//output: 'John Smith'
const bar = undefined?? 75;
console.log(bar);
In other words, this operator returns the right-hand side operand when the left-hand side operand is undefined
( or null
).
You can immediately see the immense benefit this operator provides.
Not only will it to a more error-free code, but can also help in avoiding unexpected behaviours that may lead to crashes.
It is worth noting that the OR operator(||) can be used to achieve the same.
let firstName = null;
let lastName = null;
let nickName = "Guest"; // shows the first truthy value: alert(firstName || lastName || nickName || "Anonymous"); //Guest
There is a subtle difference between the OR(||) and the nullish coalescing operator(??) and that is, the || operator returns the first truthy value while the ?? operator returns the first defined value.
4. Optional Chaining
The optional chaining operator(?.) provides a safe and quick way to access nested object properties.
With it, you can easily read the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.
const user= {
name: 'John',
security:{
password:'somepass',
}
};
const mpassword = user.security?.password;
console.log(mpassword); //"somepass"
const mpassword = user.address?.street;
console.log(mpassword); //undefined
You can also use this operator to check if a property exists in the first place before performing any operations but the better way of doing so is discussed below.
5. in
Operator
The in
operator is used to verifying a specified property exists in an object or in its prototype chain.
const car = { make: 'Honda', model: 'Accord', year: 1998 };
console.log('make' in car);
// expected output: true
delete car.make;
if ('make' in car === false) {
car.make = 'Suzuki';
}
console.log(car.make);
// expected output: "Suzuki"
As you can notice, the in
operator returns true
or false
depending on the specified property existence.
This property can be incredibly useful when doing DOM manipulation.
var q= "onrender" in document.createElement("div");
if(q){
...
}
else{
...
}
You can read more on this operator here.
6. JSON Object
I know that the JSON object and in particular JSON.stringify()
is something that even beginners know and use, especially while debugging.
But there is more to this than meets the eye.
For starters, the stringify
function can have more than one argument.
The second argument can be an array that contains the keys of the values we intend to log to the console, allowing us to only print the value we are interested in.
You can even pass a function as a second argument, which will check each key & value pair.
JSON.stringify(someObject, (key, value) => {
if (value === 0) {
return undefined;
}
return value;
});
You can find more such less-talked-about aspects of this amazing function here.
7. Array Methods
This one doesn’t exactly sound new or as exciting as the ones discussed above, but the recent development surrounding arrays has led to some incredible array methods.
For instance, if you have the salaries of your employees stored in an array and you want to deduct a certain percentage from all of them, it can be easily done using the map
method.
var numbers = [400, 800, 300, 1000];
var x = numbers.map(*v*=> v*0.75) //reducing 25% of the salary
console.log(x)
console.log(numbers)
Similarly, you have every
method that checks the entire array to see if it meets particular criteria.
var data = [
{name:'Science', results:'passed'},
{name:'Maths',results:'failed'},
{name:'Computer',results:'passed'},
];
var finalResult=data.every(*v* => v.results=='passed')
I have discussed these functions as well as other functions in a recent article. 8 Modern Array Methods that Every Developer Should Know Incredibly useful methods to make your life easierjavascript.plainenglish.io
Final thoughts
JavaScript, like most things in life, is not something you can master completely.
JavaScript has a lot of hidden features and I have curated some of the most helpful ones in this article.
You can become proficient and competent in JavaScript but no matter what you do, there is a high chance that some features or tricks will still be out of your purview.
Coding is a life-long journey of stumbling upon and learning new things, therefore you must enjoy this journey.
However, the journey doesn’t have to be monotonous and boring.
I have discussed some of the fun games which can sharpen your coding skills in my recent blog. 7 Fun Games You Should Play To Up Your Coding Skills Not-so-typical methods to master various web technologies.javascript.plainenglish.io
I hope you enjoyed reading this article!