The object undergoes a transformation despite the console.log statement being placed before the line responsible for the change

Running the JS code below yields unexpected results in the console. Despite the console.log statement being written before a line that changes a value, the output displays the changed value. This behavior goes against my expectations, as I would assume changes to only be reflected if another console.log(courses) was added after courses[1].course="JS4".

const courses = [
  { teacher: "X", course: "JS" },
  { teacher: "X2", course: "JS2" }
];

courses.push({ teacher: "X3", course: "JS3" });
console.log(courses);

courses[1].course = "JS4";

Answer №1

The code is perfectly fine. It seems like you may be inspecting the Google Chrome console, which automatically displays the most recent value of a variable.

Therefore, if a variable is altered after a console.log statement, you will witness the updated value being shown.

Answer №2

It's not an issue with the code itself, but rather a result of browser behavior. To be able to view the response in the developer console (Chrome), you can use JSON.stringify:

console.log(JSON.parse(JSON.stringify(c)))

The following snippet should help resolve your problem:

const courses = [
  { teacher: "X", course: "JS" },
  { teacher: "X2", course: "JS2" }
];

courses.push({ teacher: "X3", course: "JS3" });
console.log(JSON.stringify(courses)); // [{"teacher":"X","course":"JS"},{"teacher":"X2","course":"JS2"},{"teacher":"X3","course":"JS3"}]

courses[1].course = "JS4";
console.log(JSON.stringify(courses)); // [{"teacher":"X","course":"JS"},{"teacher":"X2","course":"JS4"},{"teacher":"X3","course":"JS3"}]

You can also refer to the screenshot below of the code executed in the developer tool:

Code in developer tool

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

Step-by-step guide on integrating the Tawk chat widget script into a Next.js React application

I am currently working on integrating a chat widget from Tawk into a next.js react app. In my _app.js file, I have added the script import tag and attempted to set up the widget like this: import Script from 'next/script' {/* <!--Start ...

Issue with React Router: Trying to access the 'history' property of an undefined object

I am developing a styleguide app that features two dropdown components. Users can select both a brand and a specific component, and the app will display the chosen component styled according to the selected brand. I aim to have these options reflected in t ...

How can I store an access token received from the backend (in JSON format) in local storage and use it to log in?

My goal is to create a login interface using Plain Javascript. I have obtained a Token from the backend and now need assistance in utilizing this Token for the login process and storing it in LocalStorage. Although I have successfully made the API call, I ...

Error encountered: Attempting to wrap MuiThemeProvider in App resulted in an invalid hook call

Whenever I include MuiThemeProvider in App.js, I encounter an error that prevents the page from loading. This issue is puzzling to me since I have utilized it successfully in other projects. react.development.js:1476 Uncaught Error: Invalid hook call. Ho ...

Is there a more efficient method to replace the element at arr[i] without using arr.splice() that is not timing

Having trouble with my solution and suspect that the .splice() function might be in the wrong place since I keep timing out. The issue: You have an array of integers. Each move allows you to increase one element by one. Find the minimum number of moves ...

Checkbox with an indeterminate state in Angular

I'm currently working on updating an AngularJS (1.5) setup where a parent checkbox becomes indeterminate if one of its children is selected, and all the children are selected if the parent is selected. My main challenge lies in converting the old ES5 ...

Steps to display a NotFound page when the entered path does not match the route in module federation React micro frontends

Typically, if the provided path does not match, we display the NotFound page to the user using the following code snippet <Route path={"*"} component={NotFound} /> However, upon adding this code, I always get redirected to the home page ( ...

The ideal version of firebase for showing messages in the foreground

Looking to instantly display notifications as soon as they are received? I recently watched a video on Angular 8 + Firebase where version 7.6.0 was discussed. While the notification is displayed in the foreground for me, I find that I need to click on some ...

Is there a way to convert a character array to an integer in Java without resorting to parseInt or String.valueOf?

Looking for a way to convert a char array into an int value without relying on parseInt and String.valueOf() methods, Seeking to implement a custom method for this conversion public static int parseInt(char[] str) { } For example, given the input data ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Although npm successfully loads Grunt, the grunt command is unfortunately not recognized

Previously, I successfully used grunt on this computer for other projects about 4 months ago. Recently, I tried to use grunt for a new project. Despite loading grunt globally and locally, when I type in $ grunt -v, it says grunt is not recognized. It seems ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...

Guide on verifying Unicode input in JavaScript?

I am looking to create a form where the user can only input Khmer characters (Unicode characters) and display an alert if they input anything else. Khmer Name: <input type="text" class="namekh" name="namekh"> To achieve this, here is a snippet of m ...

The Stencil EventEmitter fails to send data to the Vue instance

Attempting to develop a custom component using Stencil with an input feature. The goal is to create a component with an input field that, upon value change, emits the input to the Vue instance and logs this event to the console (later updating the value in ...

The method .makePerspective() in THREE.Matrix4 has been updated with a new signature. Make sure to refer to the documentation for more information

Attempting to run a functional three.js code using release 119 of three.js (instead of r79) has resulted in an error being thrown by the previously functioning code: THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check ...

What is the best way to incorporate both year and month filters using a dropdown menu on a traditional blog website?

I am currently working on a static blog article website and I am looking to implement a 'filter by year and month' feature. This will allow users to easily sort through blog articles based on their preferences. While I have successfully added a ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Next.js does not support loading jsx files

Recently, I have been exploring Next.js, which is currently considered to be the trending JavaScript framework. Eager to start practicing with it, I encountered a major roadblock as it refuses to run on my computer through any means. The standard way of c ...

How can I retrieve the index of an element within a 2D array using JavaScript when the array is displayed on a webpage?

https://i.stack.imgur.com/GHx9p.png I am currently working on developing an Othello game board within an HTML page using Angular. The board itself is constructed from a 2D number array which I then display using the <table> tag on the webpage. Below ...