JS Tip of the Day: with Statements

with Statements
Level: Beginner

with statements allow you to create a dynamic scope block with variable values based on the properties of an object. Accessing variables directly by name in a with block will access the properties of the same name in the object specified if they exist within that object.

let superLongAndDontWantToWriteOutAllTheTime = {
    short: 1,
    sweet: 2
};

with (superLongAndDontWantToWriteOutAllTheTime) {
    console.log(short); // 1
    sweet = 3;
}

console.log(superLongAndDontWantToWriteOutAllTheTime);
// {short: 1, sweet: 3}

While with blocks can be convenient, they can also be confusing and cause undesirable side effects. For example, if the sweet property didn’t exist in the object when assigned within the with block, that value would be, most likely quite unintentionally, assigned as a global.

let superLongAndDontWantToWriteOutAllTheTime = {
    short: 1
};

with (superLongAndDontWantToWriteOutAllTheTime) {
    console.log(short); // 1
    sweet = 3;
}

console.log(superLongAndDontWantToWriteOutAllTheTime);
// {short: 1}
console.log(window.sweet); // 3

So today’s tip is, now that you know about with blocks, don’t use them :stuck_out_tongue:. Instead, you should refer to properties directly from their objects or use something like destructuring to copy them into short and sweet local variables first.

More Info: