Parameters in functions are received by value

When working with JavaScript, one common point of confusion is the way variables are treated based on their data type. Variables of primitives are passed by value, while variables of objects are passed by reference. However, in function arguments, both primitives and references are passed by value.

In my experimentation, I came up with the following code, but I'm struggling to fully understand it:

> function setName2(obj) {
... obj.name="matt";
... obj = new Object();
... obj.name="obama";
... }

If I do this:

var person = new Object();
person.name = "michelle";

And then call:

> setName2(person);

I get:

> person.name;
'matt'

This result makes sense because the new object created within the function is only local and does not affect the global 'person' object.

But what happens if I first create an object like this:

 var obj = new Object();
    obj.name = "michelle";

And then run:

  > setName2(obj);

The outcome is still the same. Does this mean that the compiler distinguishes between the global and local variables named 'obj,' recognizing each as a reference to a different memory location in the heap, or is there another explanation for this behavior?

Answer №1

In JavaScript, it is important to understand that everything is passed by value and not by reference. Despite this, some values serve as references to objects which can cause confusion between pass-by-reference and being-a-reference.

To illustrate this concept, consider the following example:

function modifyObject(obj) { ... }
var originalObj = { bar: 24 };
modifyObject(originalObj);

Regardless of what happens within the function modifyObject, the variable originalObj will always point to the same object because the argument is not passed by reference. However, the actual value of originalObj that gets copied into obj is itself a reference to an object. As a result, any changes made to properties of obj inside the function will reflect on originalObj once the function finishes executing.

Answer №2

When it comes to function arguments, both primitives and references are passed by value.

This statement is actually false. There's nothing particularly special about how function arguments are treated.

function changeName(obj) {

Here, we're accepting a reference to an object as the argument.

obj.name = "John";

This line of code changes the `name` property of the object that the reference points to.

obj = new Object();

By executing this code, we replace the reference to the original object with a reference to a brand-new object.

obj.name = "Doe";

Now we're changing the name property of the new object. The original object remains untouched.

Answer №3

There is often confusion surrounding the concept of "pass by reference," as it is commonly misunderstood or used incorrectly.

When passing parameters, they are actually passed by value. This means that altering the value within a method does not affect the original value.

For primitive data types, the value itself is what is passed. However, for objects, a reference to the object is passed. While you can modify an object's contents, you cannot alter the reference value itself.

In languages like C++ or C#, "passing by reference" involves passing a reference to either a primitive type or a reference to an object. In this scenario, both the object's content and the reference itself can be modified.

It's important to note that JavaScript does not support passing by reference.

Answer №4

When it comes to Javascript, it utilizes pass-by-value.

One common source of confusion is the fact that objects are held by reference variables, which act like pointers. However, the reality is that most popular programming languages (such as Java and JavaScript) do not exhibit true pass-by-reference behavior. An alternate way to interpret this concept could be described as pass-reference-by-value, even though such a term doesn't formally exist.

This essentially means that when an object is passed as a parameter, what actually occurs is that a reference to the object by-value is passed along.

function setName2(obj) {
  ...
}

setName2(person);

In this scenario, the contents of person (which can be perceived as a reference or "pointer") are copied by-value to a new local variable named obj.

As a result, both obj and person are distinct variables that simply point to the same underlying object.

Thus, executing the command obj = new Object(); will cause obj to reference the newly created object. Nevertheless, this action does not affect person in any way since it remains an entirely separate variable.

Answer №5

I am not sure where you got that information from, but it is completely false. Objects are always passed by reference, regardless of whether they are function parameters or not.

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

Having trouble getting $.ajax to function properly in conjunction with fullcalendar js?

Currently in the process of utilizing the Smart Admin Theme, specifically focusing on the functionality within the calendar page. The calendar's core features are operational, allowing for the creation and placement of new events on the map. My curr ...

Optimizing my AngularJS bundle is pushing me towards upgrading to Angular 5

Regarding my AngularJS application, it was initially created using 'yo angular-fullstack' with JS scripting instead of TS. It is functional but experiencing performance and user experience issues. The deployment is on AWS ElasticBeanstalk nano i ...

Guide on displaying applicant name in the show route of your node.js/mongoDB application

Currently working on a website where applications are being accepted. In the admin panel, I want to display a list of all applicants and allow users to click on a name to view more information. However, I'm facing an issue where the same applicant is ...

Custom label slots in q-file for the Quasar file picker for personalized file selection label

Can you provide guidance on how to properly display custom label slots in Quasar? I am looking to incorporate icons or images using the label slot. Below is my data(): data() { return { showLabel: true, labelText: "My custom Label& ...

Changing characters to asterisks using Javascript

I am currently working on a function that transforms all characters after the first word into asterisks. For example, if I have MYFIRSTWORD MYSECONDWORD, I would like it to show as: MYFIRSTWORD *** Currently, I'm using the code below which replaces ...

A JavaScript right-click menu that updates a variable when clicked

Within my three-dimensional application created with three.js, I have implemented a functionality where right-clicking on floors (BoxGeometry) triggers a context menu to select from various textures. While this feature works as intended for a single floor, ...

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

Structuring JavaScript in Rails' asset pipeline

Overall: What are the most effective strategies for structuring JavaScript within the Rails pipeline? Specifically: My JS files are growing rapidly and while I'm okay with including them in the main application.js bundle and using Sprockets to minify ...

Unveiling the Magic Bytes: Extracting the Image File in Multer for Magic Byte Verification in Express.js

Utilizing the fileFilter option within the multer plugin to determine whether an image should be saved on the server or not. Within the fileFilter function, there is a need to verify the magic bytes of these images in order to ensure they are legitimate a ...

Implement the parent jQuery library within a child iframe

I have a query regarding the use of two iframes in my HTML page. I am trying to implement a single jQuery file that is loaded on the parent page. The code snippet provided below works perfectly on all browsers, except for one issue with Chrome when using t ...

The contents of req.body resemble an empty {}

Does anyone know why the req.body is empty in this code snippet? Even though all form data is submitted, it doesn't seem to be recognized in the req.body. Strangely enough, it works perfectly fine in postman. Take a look at the server-side code: con ...

What are the distinctions between altering the value of a textarea with JS and user input?

I've come across an interesting scenario that I'm hoping someone with more expertise in JavaScript can help me with. There is a popular online forum site that I frequently use. In the past, I was able to easily update a comment textarea using Jav ...

guide to setting up router access using token

I've received a token from the backend axios.post(process.env.VUE_APP_LOGIN, payload) .then(response => { const {access_token, token_type, user} = response.data; this.token = access_token this.$store.commit(&a ...

Tips for extracting information from a JSON file using $routeParams in AngularJS

https://i.stack.imgur.com/NQCpy.png I am currently encountering an issue with retrieving data using $routeparams. Here is a description of my problem: Retrieving the URL to redirect console.log($routeParams); console.log($routeParams.json_url); $.getJS ...

JS not functioning properly in specific pages causing display issues with page height set to 100%

I am facing an unusual issue where certain pages do not stretch to 100% page height in the middle section, causing the left-hand border to be incomplete. For example, on the 'Brentwood' site (please click on the 'Login' link in the top ...

Load a page from a different domain using uframe

Looking for a solution to successfully load an external URI using uFrame. Currently encountering an "Access Denied" issue when attempting to do so on Firefox. Any suggestions? ...

Binding events within other events can be achieved using D3

Trying to implement code from Scott Murray's book "Interactive Data Visualization for the Web" to create versatile bar graphs. Though the code successfully generates and updates graphs, it seems that the sorting functionality is not functioning as exp ...

Use the row().data function with the datatables.net plug-in to fetch data from a specific column in a

UPDATE: Removed my video on YouTube, but here is a straightforward solution: $(document).on('click', '.edit_btn', function() { var rowData = $('#example').DataTable().row($(this).parents('tr')).data(); }); "Funct ...

Unable to replicate the exact Bootstrap template found on their website

Attempting to replicate a template from bootstrap.com, but encountering issues with the copied version. The navigation bar is turning white instead of remaining black, and I'm unable to change the color. Additionally, facing problems with the toggle ...

Calculating the percentage difference between two dates to accurately represent timeline chart bar data

I am in the process of creating a unique horizontal timeline chart that visually represents the time span of milestones based on their start and finish dates. Each bar on the timeline corresponds to a milestone, and each rectangle behind the bars signifies ...