java script features you should use!
Let’s start to get to know some cool features you may
not using in JS.😁
1/optional chaining:
According to the MDN docs, optional chaining is "shorter
and simpler expressions when accessing chained properties when the possibility
exists that a reference may be missing".
In simple terms, it allows us to access to chained proprieties such as object proprieties. It’s like the ‘.’ Chaining operator but when the value is null or undefined it returns undefined.
Less "can’t read
propriety of undefined"bugs😉. Take an example:
let person ={
name:"john",
age:25
}
console.log(person.adress.street)
console.log(person?.adress?.street)
Here the address is not a valid person propriety.
The first line will throw "can’t read propriety of undefined’"error.
But the second one will deal with it as undefined.
Pretty cool no?😎
2/With block:
It’s a little similar to destruction. Here’s the
syntax:
let person ={
name:"john",
age:25
}
with(person) {
console.log(name,age)
}
Of course you can do much more than console.log.
It’s a powerful trick for a clean code.
3/Comma operator:
You may have used it when working with for loops
for(var a=0, b=5;a<10,b<10,a++,b++)
The concept is that all the expressions will be evaluated
and the affection will get the last expression’s value.
let result = expression1,expression2,expressionN;
This is very useful when writing multiple statements
in one line. For example.
function f(){
return counter++,console.log(counter),counter;
}
Try to guess the output.😉
4/ Import/export:
Those tow statements are a great solution for managing
modules and dependencies . In simple terms when a data or logic inside a file require
other one inside other file.
//A.js
export const fA=()=>{
console.log("this is a data in A file")
}
And this in B.js file:
//B.js
import {fA} from './A'; //in case A and B are in the same folder
fA();
Of course there are other cool features but I tried to
bring the newer and most useful as possible.😉
Bonus:
If you want know more about destructuring or thiskeyword please see those articles.😍
No comments