What causes the variance in my variables when comparing arrays to integers?

While researching online about JavaScript arrays and their methods, I came across something that left me puzzled. Specifically, I was diving into the Array.reverse() method:

var numbers = [60, 50, 20, 30];
var value = numbers.reverse();

console.log(numbers); // [30, 20, 50, 60]
console.log(value); // [30, 20, 50, 60]

What baffled me was why did the original "numbers" array change in this case?

I found it confusing because a similar situation does not occur here:

var number = 3;
var value = number * 2;

console.log(number); // 3
console.log(value); // 6

It struck me that in the first example, I am working with arrays, while in the second one, just integers. So, why does the "number" variable get altered when manipulating the "value" variable in the first scenario, but it remains unchanged in the second case? What sets these two examples apart?

Answer №1

Array.prototype.reverse() is a method that reverses the array in place, meaning it alters the original array.

According to MDN:

The reverse() method reverses an array by modifying the elements position in place. The first element becomes the last, and the last element becomes the first.

var a = ['one', 'two', 'three'];
a.reverse(); 

console.log(a); // ['three', 'two', 'one']

In another scenario, when you perform a simple calculation with primitive values, it does not alter the original primitives involved in the computation.

Answer №2

I was puzzled by the fact that the variable "numbers" underwent a change in value.

The reason for this is that the variable numbers serves as a reference to an array stored in memory, so when reverse is executed, it alters this array.

On the other hand, when you are dealing with primitives:

var number = 3;
var value = number * 2;

primitives remain immutable in JavaScript

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

Code snippet for scrolling in increments with Selenium WebDriver using JavaScript

Is there a way to scroll incrementally instead of directly jumping to a specific position using driver.executeScript("scroll(0,1000)")? I attempted the code below without success... for (var i = 10; i < 2000; i += 50) { driver.executeScript("scroll ...

Vanishing elements when employing the react-router library in a React project

Currently, I am in the process of developing a React application and have encountered an issue with components disappearing upon refresh. It seems to be related to React Router, suggesting that I may be implementing it incorrectly. This is what my App.js ...

What could be causing the error? And is there a way to successfully append the child div to the parent div?

Here is the error message that I am encountering: Uncaught TypeError: Cannot read property 'appendChild' of null at HTMLButtonElement.<anonymous> Error is located at app.js on line 7 const flexContainer = document.querySelector(&apo ...

Retrieve specific elements from an array based on the other elements present in the array

I am working with a result set that consists of various combinations from the following data structure: [ ["1st", "FELONY"], ["2nd", "FELONY"], ["3rd", "FELONY"], ["1st", "MISDEMEANOR"], ["2nd", "MISDEMEANOR"], ["3rd", "MISDEMEANOR"]] For example, it co ...

Exploring the possibilities of DOM events within nodeJS and express

Does anyone have experience catching a DOM event with NodeJS and Express? I've been looking into the "socket.io" module but am having trouble using it properly. My goal is to run some code whenever the content of a "file input" changes in the DOM. & ...

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

Improving methods for handling AJAX requests in PHP

I am facing an issue with a JavaScript file that sends an AJAX request to a PHP file to fetch data from a database. When the PHP file does not find any record based on the query, it returns a message like "no match found" instead of a JSON object in the ...

Distinguishing among ArrayList declarations

While researching online, I came across an interesting declaration for an ArrayList: ArrayList[] graph = new ArrayList[numCourses]; This was contrary to what I knew, as I had always seen ArrayList declared as: ArrayList<type> graph = new ArrayList ...

Angular's $http method is sending a GET request instead of a POST request

$http.post(main+'/api/getcard/', $.param({number: $scope.searchcard}), {headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} }) .then(function (response) { if(response.data != 0) ...

Saving extra parameters with MongooseJS

When saving data in my app using a POST query, how can I include additional parameters to the Item? For example, I would like to add user: req.user._id. var Item = new Model(req.body); Item.save(function (err, model) { res.send(model); }); ...

How can I modify the color of a div when a validation error occurs?

I have recently completed a contact form with validation using the constraint validation api. Although the files are functioning as intended, I am curious if there is a method to make the error boxes turn red when an error occurs and white (or hidden) when ...

Use jQuery to easily add and remove rows from a table dynamically

Is there a way to dynamically add rows to an HTML table using jQuery by utilizing a popup window? The popup would contain text fields, checkboxes, radio buttons, and an "add" button. Upon clicking the "add" button, a new row would be added to the table. ...

Encountering problems with ajax technology

As a newcomer to Laravel and Ajax, I am facing an issue with displaying the state of the selected country in a dropdown list. Although the data is successfully fetched from Laravel and received through Ajax, I am struggling to dynamically add it to the H ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...

Server-side Data Fetching with Nuxt.js

Is there a method to exclusively retrieve data from an API on the server-side in NuxtJS due to me needing to include my API_TOKEN in the request headers? Sample Code: <template> <div> <h1>Data obtained using asyncData</h1> ...

JavaScript error: "null or not an object" bug

I have implemented the JavaScript code below to display horizontal scrolling text on the banner of my website. Surprisingly, it works perfectly fine on one server but throws an error on another server with the message: Error: 'this.mqo' is nul ...

A guide on showing POST values from javascript XMLHttpRequest() in php

I have encountered an issue where I am using the XMLHttpRequest() javascript function to send parameters in Json format to another php page, but for some reason $_POST['appoverGUID'] is not receiving the posted values. Below is my Javascript cod ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

What is the mechanism behind property binding in Angular 2? Can you explain what is happening in this specific scenario?

Being a novice in the realm of Angular 2, I find myself grappling with doubts related to property binding. While this particular example seems to work fine, I can't help but wonder about what exactly goes on behind the scenes. Within my component vi ...