Open In App

JavaScript with Statement

Last Updated : 29 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The with statement in JavaScript allows for simplified access to object properties by establishing a default object scope. While it can reduce code repetition, it is generally discouraged due to potential confusion and negative impacts on code maintainability and performance.

Syntax:

with (object) {
// Statement(s) that access properties of `object`
}

Parameters:

  • object: It refers to any expression that can be evaluated as an object. When you use braces the first thing it does is search, for any identifier within the object, before checking the usual scope chain.

Why We Avoid using with statement ?

Please note that while the, with statement in JavaScript is still supported by browsers it is highly recommended to avoid using it. This recommendation is based on three concerns:

  • Scope ambiguity: There can be confusion and hidden bugs when there is uncertainty, about access within the block.
  • Performance impact: In codebases performance can be affected by lookups, within the with object.
  • Security vulnerabilities: Using the with statement can introduce some kind security vulnerabilities by accessing properties, which poses potential risks to security.

Example 1: The below example will access properties within a nested object structure without repeatedly using dot notation.

JavaScript
const GFG = {
    designation: "Writer",
    details: {
        name: "Pankaj",
        age: 20,
    },
};

with (GFG.details) {
    console.log(`${name} ${age}`);
}

Output
Pankaj 20

Example 2: The below code modifies the properties of an object passed as an argument to a function.

JavaScript
function GFG(user) {
    with (user) {
        name = "Pankaj";
        age += 2;
        address.city = "Surat";
    }
}

const myUser = 
{ 
    name: "Neeraj", 
    age: 18, 
    address: { city: "Prayagraj" } 
};
GFG(myUser);
console.log(myUser);

Output
{ name: 'Pankaj', age: 20, address: { city: 'Surat' } }

Next Article

Similar Reads