Home Web Front-end JS Tutorial Discussion on whether values ​​in JavaScript are passed by value or by reference_javascript skills

Discussion on whether values ​​in JavaScript are passed by value or by reference_javascript skills

May 16, 2016 pm 04:16 PM
javascript

I encountered an interesting question recently: "Are values ​​in JS passed by value or by reference?"

Before analyzing this problem, we need to understand what is call by value and what is call by reference. In computer science, this part is called Evaluation Strategy. It determines how values ​​are passed between variables and between actual parameters and formal parameters when calling functions.

Pass by value VS. Pass by reference

Call by value is the most commonly used evaluation strategy: the formal parameters of a function are copies of the actual parameters passed when called. Changing the value of the formal parameter does not affect the actual parameter.

When passing by reference (call by reference), the formal parameters of the function receive implicit references to the actual parameters, rather than copies. This means that if the values ​​of function parameters are modified, the actual parameters will also be modified. At the same time both point to the same value.

Passing by reference makes it more difficult to trace function calls and sometimes causes subtle bugs.

Passing by value requires a clone every time, so the performance is lower for some complex types. Both methods of passing values ​​have their own problems.

Let’s first look at a C example to understand the difference between passing by value and reference:

Copy code The code is as follows:

void Modify(int p, int * q)
{
p = 27; // Pass by value – p is a copy of the actual parameter a, only p is modified
*q = 27; // q is a reference to b, both q and b are modified
}
int main()
{
int a = 1;
int b = 1;
Modify(a, &b); // a is passed by value, b is passed by reference,
// a has not changed, b has changed
Return(0);
}

Here we can see:

a => When p is passed by value, modifying the value of formal parameter p does not affect the actual parameter a, which is just a copy of a.
b => q is passed by reference. Modifying the value of the formal parameter q also affects the value of the actual parameter b.
Explore how JS values ​​are passed
The basic types of JS are passed by value.

Copy code The code is as follows:

var a = 1;
function foo(x) {
x = 2;
}
foo(a);
console.log(a); // Still 1, not affected by x = 2 assignment

Let’s look at the object again:
Copy code The code is as follows:

var obj = {x : 1};
function foo(o) {
o.x = 3;
}
foo(obj);
console.log(obj.x); // 3, modified!

Explain that o and obj are the same object, and o is not a copy of obj. So it's not passed by value. But does this mean that JS objects are passed by reference? Let’s look at the following example:
Copy code The code is as follows:

var obj = {x : 1};
function foo(o) {
o = 100;
}
foo(obj);
console.log(obj.x); // Still 1, obj has not been modified to 100.

If it is passed by reference, modifying the value of formal parameter o should affect the actual parameter. But modifying the value of o here does not affect obj. Therefore objects in JS are not passed by reference. So how is the value of the object transferred in JS?

call by sharing

To be precise, basic types in JS are passed by value, and object types are passed by sharing (call by sharing, also called passing by object and passing by object sharing). It was first proposed by Barbara Liskov in the GLU language in 1974. This evaluation strategy is used in Python, Java, Ruby, JS and other languages.

The key point of this strategy is: when calling a function to pass parameters, the function accepts a copy of the object argument reference (neither a copy of the object passed by value, nor an implicit reference passed by reference). The difference between it and pass by reference is that the assignment of function parameters in shared transfer will not affect the value of the actual parameter. As in the following example, the value of obj cannot be modified by modifying the value of the formal parameter o.

Copy code The code is as follows:

var obj = {x : 1};
function foo(o) {
o = 100;
}
foo(obj);
console.log(obj.x); // Still 1, obj has not been modified to 100.

However, although the reference is a copy, the object referenced is the same. They share the same object, so modifying the property values ​​of the formal parameter object will also affect the property values ​​of the actual parameters.
Copy code The code is as follows:

var obj = {x : 1};
function foo(o) {
o.x = 3;
}
foo(obj);
console.log(obj.x); // 3, modified!

For object types, since the object is mutable, modifying the object itself will affect the references and reference copies that share the object. As for basic types, since they are all immutable, there is no difference between passing by sharing and passing by value (call by value). Therefore, JS basic types conform to both passing by value and passing by sharing.
Copy code The code is as follows:

var a = 1; // 1 is number type, immutable var b = a; b = 6;

According to the pass-by-share evaluation strategy, a and b are two different references (b is a reference copy of a), but refer to the same value. Since the basic type number 1 here is immutable, there is no difference between passing by value and passing by sharing.

Immutable nature of basic types

Basic types are immutable (immutable), only objects are mutable (mutable). For example, the numerical value 100, Boolean values ​​true, false, modify these values ​​(for example, change 1 to 3, change true to 100 ) has no meaning. What is easier to misunderstand is string in JS. Sometimes we try to "change" the contents of a string, but in JS, any operation that appears to "modify" a string value actually creates a new string value.

Copy code The code is as follows:

var str = "abc";
str[0]; // "a"
str[0] = “d”;
str; // Still "abc"; assignment is invalid. There is no way to modify the content of the string

But objects are different, objects are mutable.
Copy code The code is as follows:

var obj = {x : 1};
obj.x = 100;
var o = obj;
o.x = 1;
obj.x; // 1, modified
o = true;
obj.x; // 1, will not change due to o = true

Here we define the variable obj, the value is object, and then set the value of the obj.x attribute to 100. Then define another variable o, whose value is still the object object. At this time, the values ​​of the two variables obj and o point to the same object (share a reference to the same object). Therefore, modifying the content of the object will affect both obj and o. But the object is not passed by reference. The value of o is modified by o = true, which will not affect obj.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles