javascriptreadonly-attribute

What is the definition of a read-only property in JavaScript? What does it mean?


I am a little confused on what a read-only property means? I know that classList is a read only property by MDN's definition but what does that exactly mean?


Solution

  • A read-only property means it cannot be overwritten or assigned to. Any such assignment will silently do nothing in non-strict mode. E.g.:

    var obj = {};
    Object.defineProperty(obj, 'property', {value: 123, writeable: false})
    
    
    // Assign 456 to obj.property using the . syntax, but it's still 123
    obj.property = 456;
    console.log(obj.property);
    
    // Assign 789 to obj.property using the [] syntax, but it's still 123
    obj['property'] = 789;
    console.log(obj['property']);

    Or just error out with a TypeError in strict mide:

    'use strict';
    
    var obj = {};
    Object.defineProperty(obj, 'property', {value: 123, writeable: false})
    
    
    // Assign 456 to obj.property in strict mode will result in a TypeError
    obj.property = 456;
    console.log(obj.property);