Javascript with Statement

Introduction

The with statement sets the scope of the code within a particular object.

The syntax is as follows:

with (expression) statement; 

The with statement was created as a convenience:

let qs       = location.search.substring(1); 
let hostName = location.hostname; 
let url      = location.href; 

Here, the location object is used on every line.

This code can be rewritten using the with statement as follows:

with(location) {
    let qs = search.substring(1);
    let hostName = hostname;
    let url = href;
}

In strict mode, the with statement is not allowed and is considered a syntax error.




PreviousNext

Related