What is the reason for seeing identical results when logging an array to console both before and after performing an operation on it?

Let's consider this scenario:

        var currentHistory = ['t1', 't2', 't3', 't4', 't5'];
        console.log(currentHistory);

Next, we decide to swap an element and display the array again:

        var tmp = currentHistory[2];
        currentHistory[2] = currentHistory[0];
        currentHistory[0] = tmp;

        console.log(currentHistory);

Oddly enough, the output remains unchanged both times.

        Array[5] 't3', 't2', 't1', 't4', 't5'

        Array[5] 't3', 't2', 't1', 't4', 't5'

This peculiar consistency in results got me thinking deeply last night, seeking a resolution to this mystery. Any insights would be greatly valued.

Answer №1

Great query! Give this a shot:

console.log(currentHistory.slice(0));

Notice how the complex mess has simplified into a straightforward path from point A to point B?

This issue actually stems from the way the console functions. When you log an object, certain browsers (like Chrome) log a reference to the object for easy browsing. However, if the object undergoes changes... it may not behave as anticipated.

Answer №2

Based on the information provided in THIS link, it seems like your code is functioning properly.

I am currently using Chrome Version 34.0.1847.131 m

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

Exploring the use of jQuery autocomplete to retrieve data attributes

Looking to retrieve additional data-attributes from the Mapbox API. The autocomplete plugin I implemented can be found here. (Utilizing Python/Django for backend) My goal is to send extra information such as country code, city, and country to my databas ...

Organizing an array in JavaScript that includes both version numbers and letters, with each letter representing a specific numerical value

If given an array similar to this one: input = [ "1.1", "1.c", "1.b", "1", "D", "b", "4", "2.1.2", "5.1", "3", & ...

`Is there a way to dynamically update a nested field object in Mongoose without updating the entire object?`

const userProfile = new Schema({ name: { type: String, default: null }, contacts: { mobileNumber: { countryCode: { type: String, default: null }, digits: { type: String, default: null } }, email: { type: String, default: null }, facebook: { ...

Understanding Joi validation - setting a field as optional depending on the input received

I have been struggling to integrate the following joi validation. joiSchema = Joi.object().keys({ taskno: Joi.string().alphanum().required().uppercase().trim(), taskstatus: Joi.valid('G', 'C', 'I', 'S'), ...

Exploring the occurrence of immutation within nested arrays inside objects

let myObject = {key : 'Add', array : [0, 2, 3]} let clonedObject = Object.assign({}, myObject, {array: myObject.array}) clonedObject.array.pop() console.log(myObject) console.log(clonedObject) In the above example, let's say we want to rem ...

overwriting result in nested foreach loops

Take a look at my PHP code snippet here: 1- In my HTML code, I have JavaScript content stored in the variable $content on line 2 2- My goal is to extract the JavaScript code into an array on line 17 3- There is also an array called $allowed_js which con ...

The utilization of ng-class in a dropdown menu: A step-by-step guide

I am new to AngularJS and I am trying to figure out how to disable a selectlist when an option has been chosen and enable it when no option has been selected. My goal is to have the selectlist disabled if an object is not empty, and enabled if it's em ...

Is there a limit to the number of else if statements I can use? The final else statement

How can I enhance this code snippet? The last else if statement is not working, despite my efforts to fix it. var selectedDntTyp = $("#donationTypDD"); if (selectedDntTyp.length > 0) var DropInitValue = selectedDntTyp.val(); if(DropInitValue == &apos ...

Issues with React Material UI Modal refusing to open

I'm currently working on a React component using Material UI that is supposed to open a modal. Even though I can see the state toggle changing from false to true in the React Developer Console in Chrome, the modal does not open when I click the button ...

"Within the node.js framework, the search/query section of the URL appears

I am currently working on a website (client + server) that both operate from the same machine. Despite not encountering any issues in Chrome's developer tools, I am struggling to identify the source of a problem. My dilemma is with trying to POST a s ...

Is the variable not being initialized outside of the function?

I'm really struggling with this async issue. I can't seem to get it to work because the summonerData array is not being set. I have a feeling it has something to do with async, but I'm not sure how to troubleshoot it. var summonerName = req ...

Validating the Contents of Arrays using Closure-Compiler

When working with Google Closure, there is a question about initializing an Array of a specific @type{Array.<type>} and whether or not Google Closure will confirm the Array contents. A test case has revealed that an {Array.<string>} seems to p ...

Harnessing the Power of React with Javascript Promises

Snippet 1 async function saveToDatabase(order, ownProps) { const url = `api_url` await axios.post(url, order).then( (response) => { if (response.status == 200){ console.log("response 200") console.log(resp ...

Unable to retrieve property values from an array containing objects

I am encountering an issue with my Angular + ngrx setup, and the following output is displayed in the console: {status: true, rows: 1, data: Array(1)} data: Array(1) 0: {id: "Q", description: "QQQQQ", is_active: true, created_at: " ...

Retrieve the parent object from the policy field type

Imagine you have a query that retrieves a list of products like the one below. query ProductList() { products() { name price stockQuantity isAvailable @client # This field exists only locally } } In addition, you've set up a type ...

What steps should I take to insert a divider in a dropdown menu?

I am attempting to enhance my dropdown menu by incorporating a separator using the following code: <li class='divider'></li> Below is my HTML code with the separator included: <ul class="dropdown-menu dropdown-menu-right" id="ul ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

Having trouble parsing the BODY of a NodeJs JSON post request?

I've been working on creating a basic API using nodeJS, but I've run into a problem while trying to post data. Below is my app.js file: const express = require('express'); const feedRoutes = require('./routes/feed'); const ...

What is the best way to obtain a unique dynamic id?

This is the unique identifier retrieved from the database. <input type="hidden" name="getID" value="<?php echo $row['ID']; ?>"> <input type="submit" name="getbtn" value="Get ID"> How can I fetch and display the specific dynami ...