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 get user's ip address in JavaScript

How to make a static http server in nodejs using express

Array concat method in JavaScript

What is 'this.' keyword in JavaScript

How to create promises in JavaScript