The function Object.defineProperties() allows for reassigning a property's value after it has been initially

The issue arises in the initial code snippet provided below, specifically when dealing with the object book. Initially, the value of book.year is set to 2013. Even after updating the value by setting book.year = 2015, retrieving the value using book.year still returns 2013 instead of 2015. The question remains - where am I making a mistake?

Below is the code snippet in question:

var book = {};
Object.defineProperties(book, {
    _yearOrigin: {
        value: 2013
    },
    edition: {
        value: "1st"
    },
    year: {
        get: function(){return this._yearOrigin},
    
        set: function(newValue){
            //assigning this._yearOrigin
            this._yearOrigin = newValue; 
    
            //operations for evaluating the 'subscript' to add in this.edition
            var diff = String(newValue - 2013); 
            var diffLast2ndChar = diff.charAt(diff.length - 2);
            var diffLastChar = diff.charAt(diff.length - 1);
            var subscript = "";
    
            if (diff.length > 1 && diffLast2ndChar == "1") {
                subscript = "th"; 
            } else {
                subscript = diffLastChar == "1"
                                ? "st"
                                : diffLastChar == "2"
                                    ? "nd"
                                    : diffLastChar == "3"
                                        ? "rd"
                                        : "th" ;
            }
            
            //assignment operation for this.edition
            var rawEdition = Number(this.edition.charAt(0)) + Number(diff);
            this.edition = String(rawEdition) + subscript;
        }
    }
});

>>> book.year = 2015
>>>book.year //the output comes as 2013, but it should be 2015

In contrast, another similar code excerpt presented below showcases an expected behavior. When attempting to retrieve the value of book2.year, and subsequently setting it as 2013, the output correctly reflects 2013.

var book2 = {
    _year: 2004,
    edition: 1
};
Object.defineProperty(book2, "year", {
    get: function(){
        return this._year;
    },
    set: function(newValue){
        if (newValue > 2004) {
            this._year = newValue;
            this.edition += newValue - 2004;
        }
    }
});

book2.year = 2005;
console.log(book2.year); //2005 (In this instance, the output is as expected)

Answer №1

It slipped my mind that when using

Object.Property/Object.properties
to define a property of an object, the default value for writable is false, meaning the defined value cannot be changed (non-writable). This was pointed out by some individuals in the comments.

After including writable = true as shown below, the issue was resolved and the expected outcome appeared:

_yearOrigin: {
    value: 2013,
    writable: true
},

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

FormData enables uploading of several images through distinct fields simultaneously

Looking to upload images to the server before submitting the form? Unable to nest forms, FormData() is being utilized. The form includes a title and 5 images with captions. The goal is to initiate the upload once an image is selected without clicking &apo ...

Invoke Office script from beyond MS Excel WebApp

Within the Excel WebApp on Office 365, users have the ability to incorporate Office Scripts through the "Automate" tab. These scripts utilize JavaScript syntax and can automate Excel functions similar to a VBA macro, specifically designed for the Excel Web ...

Ways to incorporate sass:math into your vue.config.js file

While using vue-cli with Vue 2.6 and sass 1.49, I encountered errors in the console related to simple division calculations: Deprecation Warning: Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0. I attempted to ...

The Vuejs single-file component fails to display on the page

Even though there are no errors in the browser and Webpack compiles successfully, the message "hello from dashboard" is not displaying on the page. I am currently using Vue version 2.6 In my main.js file: import Vue from 'vue' Vue.component(&a ...

Switching between vertical and horizontal div layouts while reorganizing text fields within the top div

function toggleDivs() { var container = document.querySelector(".container"); var top = document.querySelector(".top"); var bottom = document.querySelector(".bottom"); if (container.style.flexDirection === "column") { container.style.flexDirec ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly ins ...

User retrieval failed following successful passport authentication

After a successful authentication, the user is directed to the "/profile" route, as demonstrated in the code snippet below. app.get( "/auth/google/callback", passport.authenticate("google", { successRedirect: "/profile", failureRedirect: " ...

The button is converting my text to a string instead of the integer format that I require

Hello everyone, I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below. (html) <div class="action"> ...

Can you build and run a production-ready Vue application on your local system?

After running the npm run build command in my vue project, I placed the dist folder in C:\xampp\htdocs\ and launched the apache server to test the app on my local machine. However, when I try to access http://localhost/dist/index.html in my ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

What is the process of creating a model instance in a Nodejs controller?

Trying to work with the model object in Node using the sequelize module. It looks something like this: File structure: models index.js user.js controllers userController.js routes route.js ========================== models/users.js //created us ...

AngularJS promise fails to resolve when attempting to read a file using the FileReader

Can someone assist me with a function I am trying to create in my service? I want the function to use FileReader to read a small image file and return the result in a promise to my controller. The issue is that while the file reaches the service without an ...

What could be the reason behind the app.get middleware not functioning properly following the app.use middleware in ExpressJS?

My server.js file includes the following code. However, I've encountered an issue where the code in app.get() function works fine when the app.use() middleware is commented out. But, when both are included, the get request doesn't seem to run. An ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

fullPage.js with linear scroll

Is there a way to implement fullpage.JS without any transitions between slides? I attempted the following setup, but it didn't work as expected: $('#fullpage').fullpage({ licenseKey: 'XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX', ...

Performing a single AJAX call from a JavaScript loop is more efficient than iterating through multiple AJAX calls

I am working with a 2D array in JavaScript. Currently, I have a for loop where I make an AJAX call to update the database. I understand that this approach is not efficient, and I am seeking a way to update the database with just one AJAX call within the ...

In JavaScript, an HTTP request file includes a JavaScript variable

I am currently working on a Node.js project that involves making an HTTP request to fetch a JavaScript file. For example, let's say we have a file named a.js: var a = 'i am a.js'; var b = 'please convert me to js'; Here is the a ...