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) {



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() { = "Nexon";
    this.price = "11 Lac";
    this.color = "not set";
    this.set_color = set_color; //Use the function

const my_car = new car();


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


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?