Properties that cannot be modified, known as read-only properties,

While browsing through this post on read-only properties, I stumbled upon the following code snippet:

var myObject = {
    get readOnlyProperty() { return 42; }
};

alert(myObject.readOnlyProperty); // 42
myObject.readOnlyProperty = 5;    // Assignment allowed but has no effect
alert(myObject.readOnlyProperty); // 42

I understand that using an IIFE can help in hiding scope and making variables or properties "private". However, what confuses me is:

Why does the assignment work if it doesn't actually change anything? With no explicit scope indicated in this example, I find it puzzling how JavaScript treats a property as private.

Answer №1

Why is assignment allowed, and if it's allowed, how can nothing happen? In this code excerpt, there is no implicit scope available, so I am puzzled by how JavaScript can infer a private property.

The reason assignments are permitted (before strict mode implementation) without throwing an error is to maintain the consistency that users expect. Although it is still possible to override this behavior by creating a setter function that generates an error when called, this non-throwing behavior is the default in JavaScript for properties. It may not be ideal, but it is the way it currently operates.

If you enable strict mode, you should encounter:

TypeError: setting a property that has only a getter

Answer №2

Using getters and setters in object literal expressions provides a convenient shorthand compared to using Object.defineProperty() in ES5.

A getter retrieves a specific value when a property of an object is accessed.

let obj = {};
obj.foo = 3; // Setting a property value
obj.foo; // Getting the property value

By defining a getter, each time you request a property, you will receive the value that the getter returns.

For example, if you have:

let obj = {};

Object.defineProperty(obj, 'readOnly', {
    'get': function() { return 42; }
});

Or

let obj = {
    get readOnly() { return 42; }
};

Your variable will always be 42, as it will consistently return that value. Attempting to set a different value for the property will not change the returned result.

To prevent assignment, you can include a setter that throws an Error.

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

Form submission is not functioning as expected

I am having trouble with my form submission. When I try to submit the form, nothing happens. I have tried various solutions but have not been able to resolve the issue. I have reviewed all available resources but still cannot figure out why my code is not ...

What is the best way to execute the app functions, such as get and post, that have been defined

After creating a file that sets up an express middleware app and defines the app function in a separate file, you may be wondering how to run the app function. In your app.js file: const express = require('express') const cors = require('c ...

What is the reason for Next.js and Gatsby.js necessitating the installation of Node.js, while React.js does not have that requirement?

Have you ever thought about the connection between Next.js and Gatsby.js, both being built on React.js? Could it be that the development environments are Node applications themselves? Or maybe there's something else I'm not seeing? While I have ...

Having trouble with loading a new page on an HTML website

My website is successfully updating the database, printing all values, but for some reason the new page is not opening. The current page just keeps refreshing and I'm receiving a status of 0. Below is my code snippet: try{ console.log("here1 "+e ...

Using regular expressions in JavaScript to extract the value following a colon, without including the colon itself

I've attempted using the tool, along with a similar stackoverflow question, but I'm still unable to solve or comprehend it. I hope someone here can shed some light on what I might be missing. I've provided as detailed and step-by-step examp ...

Error Occurs While Getting Request Parameters with Ajax Post and Express.js

When utilizing ajax to send data from a JavaScript frontend to an Express.js backend server, I am having trouble retrieving the posted data in the API method of my express.js. Below is the code where I attempt to parse the request data. Your assistance i ...

What is the NodeJs Event loop and how does it work with libuv and V8

NodeJs is made up of the V8 engine and the libuv library. The V8 engine has its own event loop with a call stack, event queue, and micro task queue to run our main code. The libuv also has an event loop with phases like times, callbacks, poll, check, and ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

Adjust positioning of navigation when hovered over

Need help creating a cool navigation effect like this. Live example: https://hookandbarrelrestaurant.com/ Here is my code: https://codepen.io/Dhaval182/pen/rQPMoW ...

What is the best way to access the text content of a nested HTML element for automation tasks with Selenium or Protractor?

Can anyone help me with this HTML code snippet? I want to extract and display only the text within the desc class - "Print this", ignoring the text in the spell class. This needs to be done using either Protractor or Selenium. <span class="desc"> Pr ...

Making an AJAX call to a PHP script to add data

Could you assist me in understanding why my code is resulting in a double insert? I have a JavaScript function that makes an AJAX request to a save.php file to insert data into a database. However, each time I submit it, it performs the insertion twice, al ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

Methods for eliminating curly braces from HTTP response in JavaScript before displaying them on a webpage

When utilizing JavaScript to display an HTTP response on the page, it currently shows the message with curly braces like this: {"Result":"SUCCESS"} Is there a way to render the response message on the page without including the curly braces? This is the ...

What steps do I need to follow to create a 3D shooting game using HTML5 Canvas?

I'm eager to create a 3D shooter game with HTML5 Canvas, focusing solely on shooting mechanics without any movement. Can anyone provide guidance on how to accomplish this? I've looked for tutorials online, but haven't come across any that m ...

I have an npm package that relies on X (let's say material-ui). What is the best way to prevent users from having to install

Hey everyone, I recently released an npm package called X that relies on material-ui as a dependency. While many users of X already have material-ui installed, there are some who do not. How can I ensure that those who have material-ui installed continue t ...

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

The functionality of the Hubot script is restricted to Slack conversations where I initiate a direct message with the

At this very moment, my automated Hubot assistant is functioning properly. When I send the following message via direct message to the robot in Slack: qbot !npm bower The response provided by the robot contains a link: https://www.npmjs.com/package/bowe ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

Sending the ID of a mapped button to a component

I need help with my React mapping function that displays a series of cards, each with its own button to open up a dialog box. Right now, I'm struggling to pass the unique ID from each object to the correct dialog box. Instead, all IDs are being passed ...