# JS Tip of the Day: with Statements

**URL:** <https://forum.kirupa.com/t/js-tip-of-the-day-with-statements/643144>\
**Category:** web dev\
**Created:** [March 23, 2020, 12:53pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-with-statements/643144 "2020-03-23T12:53:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [March 23, 2020, 12:53pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-with-statements/643144/1 "2020-03-23T12:53:57Z")

</div>

**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.

```javascript
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.

```javascript
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 😛. 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:

- [with on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with)
