Can you explain the concept of a read-only property in JavaScript and its significance?

I'm a bit puzzled about the concept of a read-only property. While MDN defines classList as such, can you clarify what this really entails?

Answer №1

When a property is declared as read-only, it means that it cannot be changed or reassigned. Any attempt to do so will have no effect in non-strict mode. For example:

var obj = {};
Object.defineProperty(obj, 'property', {value: 123, writeable: false})


// Trying to update obj.property with the value 456 using the . syntax will not change its value
obj.property = 456;
console.log(obj.property);

// Attempting to set obj.property to 789 using the [] syntax will also keep the value as 123
obj['property'] = 789;
console.log(obj['property']);

In strict mode, any such attempts will result in a TypeError:

'use strict';

var obj = {};
Object.defineProperty(obj, 'property', {value: 123, writeable: false})


// Trying to assign 456 to obj.property in strict mode will throw a TypeError
obj.property = 456;
console.log(obj.property);

Answer №2

When a property is marked as read-only, it is considered to be "non-writable" and cannot be changed or reassigned.

For instance, you are unable to update or modify the value of the classList property for an element, but you can still access its current value.

If you want more information on this topic, check out these resources:

  1. Objects — Writable, Configurable & Enumerable
  2. JavaScript Object Accessors

Answer №3

In addition to the information shared by @Mureinik, there is an alternative method to create a read-only object using the freeze function. Here is an example of how you can implement it:

let myObj = {id: 45, title: 'title here'}

Object.freeze(myObj);

myObj.title = 'update title' // this change will not be applied

console.log(myObj)

// To modify a frozen object, you must reassign all its properties
// For instance:
myObj = {id: myObj.id, title: 'Another title here'}

console.log(myObj)

If you want to learn more about Object.freeze() and the proper way to update it, visit the mdn documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When tapping on grid items in the Safari browser using React Material-UI, they mysteriously switch positions

I've encountered an issue with grid Items in my React MATERIAL-UI project, specifically in the Safari browser. The problem does not occur in Chrome or Firefox. Within the grid, there are checkboxes that move from one place to another when clicked, a ...

The React initialization and construction process leads to excessive memory consumption

Hi there, I am facing an issue while trying to start or build my React app as it keeps giving me a heap out of memory error. Despite adding the --max_old_space_size=8192 flag to my script, the problem persists. yarn run v1.22.5 $ react-scripts --max_old_ ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

Access a component from the @ViewChild without resorting to nativeElement

Is there a way to access the underlying div element using a @ViewChild? I have attempted the following approaches without success: ElementRef.prototype.nativeElement -- returns ElementRef HTMLDivElement -- returns undefined ElementRef -- returns ElementRe ...

The Complex World of JavaScript Variable Mutation

Currently, I have a loop in my code that checks the id of the last div on the page and uses AJAX to replace it with an updated div. However, if the loop runs again and the id remains the same, it just adds another duplicate of the updated div. My goal is ...

Tips for including descriptions on individual images within the jQuery PhotoStack gallery

Recently, I encountered a challenge. I am currently utilizing a PHP file for accessing images stored in a specific folder. Here is the snippet of my PHP code: <?php $location = 'albums'; $album_name = $_GET['album_name']; $files ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Display advertisement in full screen on mobile devices with no need for scrolling bars

I am looking to develop a webpage using HTML/CSS/Javascript that can display an advertisement in full screen on mobile devices like smartphones and tablets. The ad should expand to the maximum width and height of the screen without any scrollbars. I have ...

Applying a blur effect using CSS to all divs underneath

I have multiple divs and would like to apply a blur effect to all of them simultaneously. However, currently only the first div with the blur effect class is affected by the blur. When I click the button, I want the text "hello world" to become blurred. U ...

Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. C ...

Assistance is needed in integrating pinch zoom into the css3d_youtube demo in three.js. The trackball controls are causing issues with the

I am facing the challenge of convincing my boss to implement three.js for a CSS3D interface integrated with video providers like YouTube. One of the key requirements is that it must work seamlessly on mobile devices, so I have chosen to demonstrate it on a ...

Steps for creating a Java Script method within a Java Script constructor

Is having a method inside my constructor possible? This is how I call my constructor: new EnhancedTooltip($("taskPreview1")) and this is how it's defined: ///<var> Represents the controls</var> var EnhancedTooltip = function (toolTipObj ...

Styling JSON data in a jQuery Mobile list display

Currently working on a jQuery Mobile application that aims to achieve a similar output as shown in this image: https://i.sstatic.net/CfUHB.png The HTML code responsible for generating the image is as follows: <ul data-role="listview" data-i ...

What is the most common method for creating a dropdown menu for a website's navigation?

Is there a common approach to creating an interactive drop-down navigation menu in the industry? I have searched on Google and found multiple methods, but as a student working on my first big web project, I am hoping to find a standard practice. I don&apo ...

What is the best method to retrieve an 'Array' within an Array utilizing Angular framework?

I have a custom array structure within my component that includes a name paired with another array indicating the number of times the name has been selected. I am facing difficulty in extracting the length of the second nested array or using something lik ...

What is the best way to mark a specific photo as a favorite in an array of Photo objects?

I am working with a basic array of photo categories that follows this structure: [ { category: 1001, photos: [ { id: 100101, url: 'url.com/100101', favorite: false}, { id: 100102, url: 'url.com/100102', favorite: ...

Error encountered in Jest (a testing tool for React) - Parse Error: Line 1 contains an invalid import declaration

Currently, I am utilizing node.js version 0.10.x and jest version 0.4.x to conduct tests on react.js. Prior to testing my react components, I was utilizing node.js version 0.12.x. I switched to version 0.10.x using nvm. I proceeded to rebuild all modules ...

Is it possible to implement Ionic components on a website without using the Ionic framework?

Having utilized and appreciated Ionic for many mobile apps, I am now in the process of creating a web client for my application. It has come to my attention that Ionic was not designed for desktop applications. However, I am curious if I can still utilize ...