Pass By Value vs. Pass By Reference, Does It Matter?
Pass by value vs. pass by reference: an in-depth discussion
In my first technical interview, I was asked this question: What is the difference between passing by value and passing by reference? My answer is: Pass by value passes a value, pass by reference passes a reference. While this answer is basic and even superficial, it's not entirely wrong and just needs further explanation.
Value passing: The value of the variable is copied and passed to the function as a parameter. The function uses this copied value to perform various operations, and the value of the original variable remains unchanged . Almost all known programming languages, including JavaScript and Java, use passing by value.
Passing by reference: A reference refers to a variable that points to a value in memory. Think of it as a pointer. It is passed to the function as a parameter and it is given an alias (alias reference) using the parameter. The function performs various operations using this parameter, which provides access to the memory location of the value. Therefore, any operation using this parameter will affect the value of the original variable, and the value of the original variable will be changed. Only a few programming languages use pass by reference, for example C has this capability, but even in C the default mode is pass by value.
Value passing example:
The following example uses JavaScript, which strictly follows value passing, regardless of whether it is a primitive type or a reference type (object). Here is a classic example of a swap function:
const firstPrimitive = 1; //传递给firstArgument的原始值 const secondPrimitive = 2; //传递给secondArgument的原始值 const firstObject = {name: "first", reason: "Test pass-by-value"}; //传递给firstArgument的对象 const secondObject = {name: "second", reason: "Test pass-by-value"}; //传递给secondArgument的对象 function swap(firstArgument, secondArgument){ const placeholder = secondArgument; secondArgument = firstArgument; firstArgument = placeholder; console.log('当前位于函数内部。'); console.log('firstArgument = ', firstArgument, ', secondArgument = ', secondArgument, '\n'); } console.log('函数执行前。'); console.log('firstPrimitive = ', firstPrimitive, ', secondPrimitive =', secondPrimitive); console.log('firstObject = ', firstObject, ', secondObject =', secondObject, '\n'); swap(firstPrimitive, secondPrimitive); console.log('当前位于函数外部。'); console.log('firstPrimitive = ', firstPrimitive, ', secondPrimitive =', secondPrimitive, '\n'); swap(firstObject, secondObject) console.log('当前位于函数外部。'); console.log('firstObject = ', firstObject, ', secondObject =', secondObject, '\n');
After executing this code, the results are as follows:
<code>函数执行前。 firstPrimitive = 1 , secondPrimitive = 2 firstObject = { name: 'first', reason: 'Test pass-by-value' } , secondObject = { name: 'second', reason: 'Test pass-by-value' } 当前位于函数内部。 firstArgument = 2 , secondArgument = 1 当前位于函数外部。 firstPrimitive = 1 , secondPrimitive = 2 当前位于函数内部。 firstArgument = { name: 'second', reason: 'Test pass-by-value' } , secondArgument = { name: 'first', reason: 'Test pass-by-value' } 当前位于函数外部。 firstObject = { name: 'first', reason: 'Test pass-by-value' } , secondObject = { name: 'second', reason: 'Test pass-by-value' }</code>
Note that inside the swap function, the two values are swapped; however, outside the function, the values remain the same.
Example of passing by reference:
The following example uses C and can be implemented by passing by reference. This can be achieved using the address operator (&). Again, it uses a version of the swap function:
#include <stdio.h> void swap(int &i, int &j) { int temp = i; i = j; j = temp; } int main(void) { int a = 10; int b = 20; swap(a, b); printf("A is %d and B is %d\n", a, b); return 0; }
The output result is:
<code>A is 20 and B is 10</code>
Here the values of a and b are changed because they are used as references.
Summary: Pass by reference means that the function receives the memory address of the variable (by reference), allowing it to modify the original variable directly; while pass by value means that a copy of the variable value is passed without modifying the original variable .
Is this important?
Most programming languages use passing by value, and we seem to have no choice. So, how does this apply? Here’s what I found:
- Use passing by value when you are just "using" a parameter to do some calculations without changing it for the client program.
- Use pass by reference when you need a function to modify the original value of a variable passed as an argument, as it directly operates on the memory location of the variable instead of creating a copy, which makes it more efficient, especially when dealing with large data structures ( like a complex object or array); it avoids the overhead of copying the data and allows the original variable to be changed directly inside the function. Passing by reference can improve performance.
Comments welcome. Thanks.
Reference materials: Is JavaScript pass by reference? Pass by reference (C only)
The above is the detailed content of Pass By Value vs. Pass By Reference, Does It Matter?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
