Search code snippets, questions, articles...

Access object properties using with() function in Javascript(ES6)

ES6 provides a new way to access object properties using the with() function. This is a more convenient way to access object properties, especially when working with large objects.
const user = {
    id: 10,
    name: 'Ankit',
    loc: 'India'
}

with (user) {
    console.log(name);
    console.log(loc)
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

Ankit
India

Try it yourself

The above code example is using the 'with' keyword. The 'with' keyword allows you to specify an object that should be used as the default object for a given scope. In the above code example, the 'user' object is specified as the default object. This means that any variables that are referenced within the 'with' block will be resolved against the 'user' object. In this case, the 'name' and 'loc' variables will be resolved against the 'user' object.

Code example 2:

function set_color(color_input) {
    with(this) {
        color = color_input;
    }
}

function car() {
    this.name = "Nexon";
    this.price = "11 Lac";
    this.color = "not set";
    this.set_color = set_color; //Use the function
}

const my_car = new car();

my_car.set_color("Green");

console.log("Car name is: " + my_car.name);
console.log("Car price is: " + my_car.price);
console.log("Car color is: " + my_car.color);

Output

Car name is: Nexon
Car price is: 11 Lac
Car color is: Green

This code creates a car object with a few properties, and a method to set the color property. When the method is called, it sets the color property of the car to the input value.

Was this helpful?
0 Comments