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

How to resume a suspended web audio api context

Tar basic commands to store and extract files

How to change a String's Case in JavaScript

FlappingBird JS13K Games

How to use fetch api submit an html form