Learn the coding skills for your next job

JavaScript With Statement Explained – A Deep Dive

JavaScript’s built-in with statement specifies the default object for the given property and gives us a shorthand for writing long object references. More precisely, it adds the given object to the head of the scope chain.

Note: Use of the with statement is discouraged. It can lead to strange bugs. That said, it's important to understand how it works because it may exist in legacy code.

With Function Syntax

Usage

with (expression){ statement }
Code language: JavaScript (javascript)

expression: An expression that evaluates to an object that will become the default object inside its scope.

statement: Code that will run with the evaluated expression as the default object

Example

let car = {color: 'red'} with(car){ console.log(color) } // prints 'red'
Code language: JavaScript (javascript)

As you can see, the car object becomes the default object in the scope. The object’s properties become available without using the dot (.) operator.

If the variable already exists in the parent scope, it will be overwritten:

let color = 'blue' let car = {color: 'red'} with(car){ console.log(color) } // prints 'red'
Code language: JavaScript (javascript)

Why Shouldn’t I Use ‘With’?

stop sign in bushes

Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

Mozilla

While using with can make long pieces of code easier to read due to the removal of long accessor paths, the danger of potential bugs due to ambiguity isn’t worth the convenience.

with(car.make.model){ let size = width * height * length; } // vs let size = car.make.model.width * car.make.model.height * car.make.model.length;
Code language: JavaScript (javascript)

There’s an argument to be made that code will be smaller and easier to send to the browser by using ‘with’ statements. While true, the gains are negligible, especially when compared to what code minifiers do.

Related Reading

Trying to find your next programming job?

If you are a self-taught developer having trouble finding your first programming job, we've got your back! We have the learning resources and tight-knit dev community that you need to land the coding job you've been looking for. To get started, create a free account and join our Discord community.

Have questions or feedback?

If we've made a mistake in the article, please let us know so we can get it corrected!