This page looks best with JavaScript enabled

With statement in Javascript

 ·   ·  ☕ 2 min read

Avoid having to type your object notation multiple times using with statement.

Consider the below code -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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 -

  • with increases 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 nested with heaven
  • 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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things