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!

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.