Example: Immutable Property in JavaScript

This JavaScript code shows how to prevent a property of an object from being modified.

function Vehicle(model, vin) {
    return {
        model: model,
        get vin() { return vin; }
    }
}

const vehicle = Vehicle('Bolt', 12345);

console.log(vehicle.vin); //prints 12345

vehicle.vin = 98765; //fails because there is no setter

console.log(vehicle.vin); //still prints 12345

vehicle = Vehicle('Bolt', 98765); //error: attempted to assign to readonly property

Links:
- Closures
- getter
- const
- Can I use const?

This entry was posted in Uncategorized. Bookmark the permalink.