Defining an SetterGetter in a Newly Created Object

suggest change

JavaScript allows us to define getters and setters in the object literal syntax. Here’s an example:

var date = {
    year: '2017',
    month: '02',
    day: '27',
    get date() {
        // Get the date in YYYY-MM-DD format
        return `${this.year}-${this.month}-${this.day}`
    },
    set date(dateString) {
        // Set the date from a YYYY-MM-DD formatted string
        var dateRegExp = /(\d{4})-(\d{2})-(\d{2})/;
        
        // Check that the string is correctly formatted
        if (dateRegExp.test(dateString)) {
            var parsedDate = dateRegExp.exec(dateString);
            this.year = parsedDate[1];
            this.month = parsedDate[2];
            this.day = parsedDate[3];
        }
        else {
            throw new Error('Date string must be in YYYY-MM-DD format');
        }
    }
};

Accessing the date.date property would return the value 2017-02-27. Setting date.date = '2018-01-02 would call the setter function, which would then parse the string and set date.year = '2018', date.month = '01', and date.day = '02'. Trying to pass an incorrectly formatted string (such as "hello") would throw an error.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Setters and getters:
* Defining an SetterGetter in a Newly Created Object

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
99 Setters and getters
102 Tilde