DEV Community

Jochem Stoel
Jochem Stoel

Posted on

[JS] Do you use 'with' in JavaScript?

let a = document.createElement('a')
with(a) {
  setAttribute ('href', 'http://google.com/')
}

console.log(a.getAttribute('href')) // http://google.com/

let object = {
  id: 14904, 
  value: 'Main Street Avenue'
}

with(object) {
  console.log(id, value) // 14904, Main Street Avenue
}

let fs = require ('fs')
with(fs) {
  readFile('log.txt')
}
Enter fullscreen mode Exit fullscreen mode

I rarely if ever come across someone using with. Some sources consider it deprecated and advise against it but in my experience every JavaScript interpreter understands it and behaves like expected.

Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. See the "Ambiguity Contra" paragraph in the "Description" section below for details.
The with statement extends the scope chain for a statement.

Source: MDN

What about your experience, are you with me?


Top comments (4)

Collapse
 
nektro profile image
Meghan (she/her)

No. And I'm genuinely curious to find out the original reason for it being added. with is one of the biggest blunders about JS as a language and should be removed.

Collapse
 
tadman profile image
Scott Tadman

It seemed like such a good idea at the time.

Collapse
 
jochemstoel profile image
Jochem Stoel

Many of the world's most destructive developments started like a good idea.

The road to hell is paved with good intentions


Collapse
 
xowap profile image
Rémy 🤖

Honestly, I read about this feature once every few years and just forget what it is and how it works in between. So the answer is a clear no.