When printing a json object in typescript, its value is dynamically updated before any changes are made to one of its properties

// Here we are declaring a variable called var1
let var1 = {
    item: "bat",
    sport: "cricket"
};

// Next, we are printing the values of var1 and only its 'item' property without any changes
console.log(var1);
console.log(var1.item);

// Then, we are updating the value of the 'item' property within var1 from "bat" to "ball"
var1.item = "ball";
console.log(var1);  // Now we are printing the entire updated var1 object
console.log(var1.item); // And just the 'item' property 

The output of running the above lines of code can be viewed here.

I am curious to know why the value of var1 gets updated even when printed before explicitly making a change to var1.item. Can someone provide an explanation for this behavior?

Answer №1

It is important to note that when logging objects in the latest versions of Chrome and Firefox, the output displayed on the console is a reference to the object itself. This may not necessarily reflect the current value of the object, but rather the value at the moment it is clicked open.

For more information, visit this link

To accurately capture the current state of the object, you can use

console.log(JSON.stringify(var1))

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

Challenges with type checking in Angular TypeScript arise when attempting to import TensorFlow into a web worker

I have been experimenting with incorporating tensorflow/tfjs (TF) into a web-worker within an angular project. The process of creating a web-worker using the ng generate worker command has been successful. Importing TF in a component works without any is ...

Exploring Angular2 components featuring setInterval or setTimeout functions

I have a basic ng2 component that interacts with a service to retrieve carousel items and automatically cycle through them using setInterval. Everything functions properly, but I encounter the error "Cannot use setInterval from within an async test zone" w ...

Angular has got us covered with its latest feature - combining Async Await with an EventListener

I have been facing this issue for the past day and need help creating a specific scenario: <img [src]="userdp | async" /> In my component.ts file, I want to include only this line: this.userdp = this._userService.getUserDp(); Here is the ...

Is there a way to access configurations from a module import in NestJS?

If my module is defined as shown below: @Module({ imports: [ PassportModule.register({ defaultStrategy: 'jwt' }), JwtModule.register({ // Use ConfigService here secretOrPrivateKey: 'secretKey', signOptions: ...

pressing buttons on user interfaces nested two levels deep

There is a 3rd party library (which cannot be altered) with the following interface: interface MyInterface { x: { a: 1, b: 2, c: 3, }, y: { d: 4, e: 5, f: 6, }, z: { g: 7, ...

Can you explain the significance of { 0: T } in this particular type definition?

I stumbled upon this type declaration in my codebase which is meant for non-empty arrays: type NonEmptyArray<T> = T[] & { 0: T } and it functions as expected: const okay: NonEmptyArray<number> = [1, 2]; const alsoOkay: NonEmptyArray<n ...

Exploring Typescript's 'Conditional' Typing Features

My function has a straightforward task in theory, but its type description is lacking, leading to the need for type assertions whenever I work with the data. The function: const fetch_and_encode = <T, E extends Encoded, C>({ source, encode, context ...

Encountering a 'scheduler flush execution error' and an Uncaught TypeError due to VueJS and Axios integration

After carefully examining my code, I have pinpointed the cause of this error to the following line: treeNodes.value = documentStore.convertToTree((await axios.get('/File')).data); Initially, I receive a warning: Vue warn]: Unhandled error during ...

Using RxJS subjects to switch maps and call another observable

Whenever a value is emitted in the subject, I want to call another observable. The issue I am currently facing is that when the first value is emitted to the subject, it triggers the switchMap and calls the confirmCsvUpload(...) function. However, subsequ ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

checkbox with an option tag

I need help with implementing multi-select checkboxes inside an Angular 4 application. The checkboxes are not appearing next to the team names as intended. Can anyone assist me with this issue? Below is a snippet of my HTML code: <select class="form-c ...

Is it possible for Angular to detect when an rxjs observable subscription begins?

Is it possible to detect the beginning of a subscription to an RxJS observable within the pipe? I am looking to activate a loading indicator when a HTTP observable is subscribed (which will be destroyed once the response has been finalized). Alternativel ...

Enhancing TypeScript functionality by enforcing dynamic key usage

Is there a way to ensure specific keys in objects using TypeScript? I am attempting to define a type that mandates objects to have keys prefixed with a specific domain text, such as 'create' and 'update': const productRepoA: Repo = { } ...

Showing Angular dropdown menu using Java HashMap

I am trying to fetch and display data from a HashMap in my Angular application by making a GET request to a Spring Application. Here is the code I have tried: Spring code: @GetMapping("gateways") public ResponseEntity<?> getGateways() { Map< ...

Creating interactive PDFs with dynamic content in React using pdfmake

I have been working on creating a dynamic PDF using pdfMake in ReactJS. While I was successful in generating a PDF from static data, when I attempted to make it dynamic by creating a function that takes parameters to update variables of the pdfMake object, ...

Vue3's onMounted hook fails to function properly when page is reloaded

I've implemented a function that checks for truncated text and, if found, displays a button to expand the hidden content. I have created a code demo with detailed explanations. Although I am not encountering any errors, the logic does not seem to be ...

While performing compilation, Angular's ngFor triggers an error when used with SVG elements

I am attempting to create a recursive function of lines in order to generate a graph, but I am encountering a strange error in the console. It works fine on node.js. Below is the code snippet: <svg height = "200" width = "300"> ...

Mapping a response object to a Type interface with multiple Type Interfaces in Angular 7: A step-by-step guide

Here is the interface structure I am working with: export interface ObjLookup { owner?: IObjOwner; contacts?: IOwnerContacts[]; location?: IOwnerLocation; } This includes the following interfaces as well: export interface IObjOwner { las ...

Troubleshooting Problems with Angular 6 Inheritance

After creating a base class named AncientWisdom and multiple subclasses representing different aspects of ancient wisdom, I encountered an issue in Angular. When the end value triggers the logic for exceeding the maximum unlocks, all subclasses inheriting ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...