What could be causing the issue in this simple code snippet?

While immersed in a personal project, I encountered an issue within my code. After some debugging, I managed to identify the problem and implement a workaround solution. However, the original issue remains unresolved.

Take a look at this code snippet:

interface Animals {
    id: number;
    name: string;
    color: string;
}

// More TypeScript code here...

Click here to test the code in Typescript Playground.

Upon analysis, two major problems surfaced:

  • Surprisingly, both arrays get modified despite the fact that "filter()" is not supposed to alter the original array according to JavaScript documentation.

  • Additionally, both arrays undergo modification before the filter function call, which seems counterintuitive.

The proposed workaround involves transforming "zoobis" into an Animal[] instead of retaining the entire Zoo object. This adjustment appears to resolve the issues encountered.

Am I overlooking a fundamental concept in JavaScript or am I committing errors that lead to unexpected outcomes in my code execution?

Answer №1

When you assign zoobis = zoo;, both the zoobis and zoo variables point to the same object in memory. Any changes made through one variable will be reflected when accessing the object through the other variable.

zoobis.animals = zoo.animals.filter((animal) => animal.color === "brown");

This line modifies the shared object by filtering its animals property based on a condition.

Both zoobis and zoo now refer to the same updated object, as shown in this simplified ASCII-art representation:

Object.assign({}, zoo) or using property spread {...zoo} can create a new object similar to zoo, but it only copies properties at the first level. If a deep copy is needed for nested objects, a different approach must be taken. More information on deep copying can be found in answers to related questions available online.

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

Upon clicking the link, the JavaScript functionality failed to activate

When I click on a link and try to add a class, it's not working. I want to create a "modal" div. Here is the PHP/HTML code: <?php if(isset($_GET['ido'])) { ?> <div id="modal" class="modal" style="background: blue; width: 1 ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Error message on Android Web Console: ReferenceError - Worker object is not defined

As someone who is new to javascript, I have been struggling to understand why popular browsers seem to handle the definition "new Worker("BarcodeWorker.js")" differently than Android WebView. The original code for this Barcode Reader is from Eddie Larsso ...

What is the appropriate JQuery event to handle when a new div is generated?

I've implemented a prettify function that formats dates in a more user-friendly way. However, I only want the JavaScript to execute after the page has fully loaded and all the dates have been retrieved from the database. Currently, I have the script c ...

Tips for saving the recently assigned IP address from Terraform?

My current project involves cloud provisioning with Terraform on an EC2 instance, where the process is automated to begin when a request is sent from the front end to the back end. In the backend, I am using Node.js and implementing shell scripts to execu ...

Reacts Router Link does not refresh page content

My React and Redux application features a Movie component that displays movie data fetched from an API. To enhance user experience, I decided to create a Similar Movies section at the bottom of the page. This section contains components that allow users t ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

Error message signaling that the dollar sign symbol is not defined in the Laravel framework

Hello there, I'm currently learning Laravel and following a tutorial on building a student CMS. I have integrated a datepicker and a bootstrap modal that are supposed to pop up when clicking form buttons. However, despite everything appearing correct, ...

How to overcome iframe sandbox restrictions?

My website is experiencing an issue with someone using iframes to display it. They are employing the following code: <iframe src="http://example.org" sandbox=""></iframe> By utilizing the sandbox attribute, they are preventing my site from im ...

How can you use the MongoDB Aggregation Framework to filter by a range of dates, group results by individual days, and calculate the average value for each day

I'm currently exploring the possibilities of MongoDB's Aggregation Framework and would appreciate some assistance in enhancing this query to achieve the following objectives: Retrieve Records with Dates falling within a specified range Organize ...

Different methods to avoid using $scope.$watch in a directive when dealing with an undefined variable

As I work on my angularjs application, I find myself utilizing directives for reusable UI elements across different pages. However, I encounter a challenge when a directive depends on a value from a promise. In such cases, I have to employ $scope.$watch al ...

Is it possible to exchange CSS classes for a specific group of elements using JQuery?

I have two list items listed below: <li name="luxury" class="cars luxury> <div id="featured_lux" name="featured" class="carImg_lux col2_lux "> My Luxury Car<img border="0" class="car-im ...

Showing key-value pairs from an array of objects using Angular TypeScript

Within my angular application, I am fetching a dynamic list of objects from an API. A sample of the data structure is as follows: [ { "_id": "some id", "DATE": "2021/01/08", "COUNT&qu ...

Smooth scrolling in JavaScript can lead to unexpected jumps when using scroll-margin-top

I am currently working on implementing smooth scrolling into my website using JavaScript. However, I have run into a problem with CSS property scroll-margin-top causing a sudden jump at the end. The CSS I am using for scroll margins looks like this: class ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

Extracting data from websites using Python's Selenium module, focusing on dynamic links generated through Javascript

Currently, I am in the process of developing a webcrawler using Selenium and Python. However, I have encountered an issue that needs to be addressed. The crawler functions by identifying all links with ListlinkerHref = self.browser.find_elements_by_xpath( ...

The error message I'm receiving is saying that the map function is not recognized for the posts variable (posts.map

I encountered a puzzling error, even though everything seems fine: posts.map is not a function import React from 'react' import { useSelector } from 'react-redux' export const PostsList = () => { const posts = useSelector(state = ...

I'm curious, in which environment does SvelteKit, Next.js, and Nuxt.js code execute? Also, is it possible to create HTTP request handlers within

My experience with using SvelteKit in my personal projects has been quite enjoyable. However, coming from a background of working with frameworks like Next.js and Nuxt.js, I often find myself confused about where the code I write actually runs. In my day ...

Having trouble with PHP not receiving data when using a $.ajax POST request?

I'm facing an issue where my code seems to be correctly passing a JavaScript variable to PHP. On the JavaScript side, everything works fine - I receive success messages and see the data in the network tab. However, on the PHP side, I am unable to retr ...

Set the current time to ISO8601 format

I need assistance with creating a "time passed" counter for my website based on an API call that returns data in the following format: "created_at": "2018-05-16T14:00:00Z", What is the best approach to calculate and display the time that has passed since ...