Open In App

JavaScript with Statement

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:

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:



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




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.




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' } }

Article Tags :