简体   繁体   中英

How exactly is does pass by value and pass by reference work in javascript?

I have been reading up about pass by value vs pass by reference in javascript and I read that JavaScript always passes by value, only with non-primitive types, the value is an address in memory. But is this not the case with primitive types also? Are primitive types not also stored in memory and the variables assigned to them need to point to their location also? I will use this table to try explain what I am saying.

Variable Address Value
a 0x01 10
b 0x02 10
c 0x03 [1, 2]
d 0x03 [1, 2]

When the variable 'b' is assigned to the value of 'a' (b=a), the value at the address of 'a' (10) is copied and this copy is placed in a different location in memory with the new address being assigned to 'b'?

When d = c, instead of making a copy of the value at the address of 'c', the variable d is given the same address as c - they now both point to the same location in memory which stores the array [1, 2]?

Is table accurate or... ?

Thank you.

When you declare variables, the JavaScript engine allocates the memory for them on two memory locations: stack and heap .

Static data is the data whose size is fixed at compile time. Static data includes:

  • Primitive values (null, undefined, boolean, number, string, symbol, and BigInt)
  • Reference values that refer to objects.

Because static data has a size that does not change, the JavaScript engine allocates a fixed amount of memory space to the static data and store it on the stack.

For example, the following declares two variables and initializes their values to a literal string and a number:

let name = 'John';
let age = 25;

Because name and age are primitive values, the JavaScript engine stores these variables on the stack as shown in the following picture: 在此处输入图像描述

Unlike the stack, JavaScript stores objects (and functions) on the heap. The JavaScript engine doesn't allocate a fixed amount of memory for these objects. Instead, it'll allocate more space as needed.

The following example defines the name, age, and person variables:

let name = 'John';
let age = 25;

let person = {
  name: 'John',
  age: 25,
};

在此处输入图像描述

In this picture, JavaScript allocates memory on the stack for the three variables name, age, and person.

The JavaScript engine creates a new object on the heap memory. Also, it links the person variable on the stack memory to the object on the heap memory.

Because of this, we say that the person variable is a reference that refers to an object.

Please check here for details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM