Languages
[Edit]
EN

JavaScript - create object with setter

0 points
Created by:
Aleena
334

In this article, we would like to show you how to create object with setter in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const user = {
  id: '1',
  username: 'Tom',
  country: null,

  // setter
  set current(countryName) {
    this.country.push(countryName);
  }
};

// set value
user.country = 'USA';

console.log(user.country);  // USA

 

Practical example

In this example, we use the set keyword to create an object with a setter that sets the country property for the user object.

// ONLINE-RUNNER:browser;

const user = {
  id: '1',
  username: 'Tom',
  country: null,

  // setter
  set current(countryName) {
    this.country.push(countryName);
  }
};

// set value
user.country = 'USA';

console.log(user.country);  // USA

Output:

USA

Related posts

  • todo

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join