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

JavaScript default parameters

How to wait for a promise within a loop block

Basic commands to open, zip and unzip archives

HTML minifier module for Nodejs

Tar basic commands to store and extract files