With statement in JavaScript

JavaScript 'with statement' is a simplified way to access object properties as variables.

Take for instance;

const dog = "puppy"
const mascots = {
    'tux': "tuxedo",
    'cow': 'cow'
}

with(mascots) {
    console.log(tux)
    // tuxedo
    console.log(cow)
    // cow
    console.log(dog)
    // puppy
}

properties of mascots are converted to variables accessible within the with block 'dog' is not part of mascots and as a fallback, dog global is returned.

At the time of writing this post with statement is discouraged.

It's not allowed in 'safe mode'

With the above sample you can do the same thing using destructureing operator

const {cow, dog, tux} = mascots

console.log(tux)
// tuxedo
console.log(cow)
// cow
console.log(dog)
// puppy

Comments

Popular posts from this blog

FlappingBird Postmortem (JS13K)

JavaScript introduction to variables

FlappingBird JS13K Games

How to target all elements of a given class name in JavaScript

Zedplug will be decommissioned on November 30th