paint-brush
Why You Shouldn't Use "With Statement" Syntax in JavaScriptby@wagslane
345 reads
345 reads

Why You Shouldn't Use "With Statement" Syntax in JavaScript

by Lane WagnerJanuary 16th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Use of the with statement is discouraged, but it is important to understand how it works. Using with can make long pieces of code easier to read due to the removal of long accessor paths. The danger or potential bugs due to ambiguity isn’t worth it. There is 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 minified code can do.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Why You Shouldn't Use "With Statement" Syntax in JavaScript
Lane Wagner HackerNoon profile picture

Let’s look at the JavaScript with statement. We will go over the simple uses, as well as a deep dive into some more advanced concepts.

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

With Function Syntax

From Mozilla’s definition:

with (expression){
  statement
}

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'

As you can see, the car object becomes the default object in the scope. The object’s properties become available without using the ‘.’ 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'

Why Shouldn’t I Use ‘With’?

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.

While using with can make long pieces of code easier to read due to the removal of long accessor paths,

with(car.make.model){
  let size = width * height * length;
}

vs

let size = car.make.model.width * car.make.model.height * car.make.model.length;

the danger or potential bugs due to ambiguity isn’t worth it.

There is 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 minified code can do.

By @wagslane (twitter)

Previously published at https://qvault.io/2020/01/15/javascript-with-statement-explained-a-deep-dive/

Thanks For Reading