Avoid having to type your object notation multiple times using with statement.
Consider the below code -
const earth = { name: "earth", satellite: "moon", position: 3 };
console.log("name:", earth["name"]);
console.log("satellite:", earth["satellite"]);
console.log("position:", earth["position"]);
/* output
name: earth
satellite: moon
position: 3
*/
Typing “earth” everywhere can be quite laborious. This is more prominent when you are retrieving a big JSON from somewhere and trying to insert specific values in different parts of the page.
Ergo, this shortcut -
const earth = { name: "earth", satellite: "moon", position: 3 };
with (earth) {
console.log("name:", name);
console.log("satellite:", satellite);
console.log("position:", position);
}
/* output
name: earth
satellite: moon
position: 3
*/
with can also be nested.
const earth = {
name: "earth",
satellite: "moon",
position: 3,
asia: { type: "continent", population: "3B" }
};
with (earth) {
console.log("name: ", name);
with (asia) {
console.log("type: ", type);
console.log("population: ", population);
}
}
/*
ame: earth
type: continent
population: 3B
*/
The Bad
If you think all this sounds cool, hear the other side of the story.
Although with reduces the size of code and repetitive typing (if that’s a thing) - there are disadvantages to it -
withincreases confusion. Your typical blocks can cover a lot of pages. Someone debugging at the 7th page is not going to be happy if she has to find out just which object does a prop belong to in a nestedwithheaven- Javascript will do a full search for all props whenever it encounters a prop within
with. This may cause performance issues when there is a possibility of using props that do not exist in object, or for an object that has a large number of props
Recommendation
Do not use with.
If you include a "use strict;" at the beginning of your module or function (and you should), with causes the program to fail.