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 make a Snake Game using JavaScript and html5

How to get user's ip address in JavaScript

Adding Gameover and introduction screen on HTML Canvas

JavaScript intro to classes

How to use canvas context rect method for drawing rectangles