JavaScript Setters and Getters Defining an Setter/Getter in a Newly Created Object

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


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}-${}`
    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];
   = parsedDate[3];
        else {
            throw new Error('Date string must be in YYYY-MM-DD format');

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

Got any JavaScript Question?