惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
T
The Exploit Database - CXSecurity.com
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
T
Tailwind CSS Blog
V
V2EX
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家
PCI Perspectives
PCI Perspectives
腾讯CDC
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Commits to openclaw:main
Recent Commits to openclaw:main
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog
N
News and Events Feed by Topic
博客园 - 三生石上(FineUI控件)
Help Net Security
Help Net Security
雷峰网
雷峰网
有赞技术团队
有赞技术团队
Last Week in AI
Last Week in AI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
量子位
GbyAI
GbyAI
O
OpenAI News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AI
AI
S
Security Affairs
F
Fortinet All Blogs
L
LINUX DO - 最新话题
博客园 - 【当耐特】
Webroot Blog
Webroot Blog
Schneier on Security
Schneier on Security
W
WeLiveSecurity
Security Latest
Security Latest
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tenable Blog
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
Simon Willison's Weblog
Simon Willison's Weblog
Cyberwarzone
Cyberwarzone
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
CERT Recently Published Vulnerability Notes
Engineering at Meta
Engineering at Meta
P
Palo Alto Networks Blog
博客园 - 叶小钗
T
Threatpost
H
Heimdal Security Blog
Microsoft Security Blog
Microsoft Security Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
The Difference Between Values and References in JavaScript
Dmitri Pavlutin · 2021-03-23 · via Dmitri Pavlutin Blog

In JavaScript, you can pass by value and by reference.

The main difference between the two is that passing by value happens when assigning primitives while passing by reference when assigning objects.

Let's discuss values and references in more detail in this post.

1. Understanding primitive and objects

JavaScript provides 2 categories of data types: primitives and objects.

The primitives are numbers, booleans, strings, symbols, and special values null and undefined.


// Primitives

const number = 10;

const bool = false;

const str = 'Hello!';

const missingObject = null;

const nothing = undefined;


The second category is objects. Particularly the plain object, arrays, functions, and more — are all objects.


// Objects

const plainObject = {

prop: 'Value'

};

const array = [1, 5, 6];

const functionObject = (n1, n2) => {

return n1 + n2;

};


Saying it differently, anything that is not a primitive value is an object.

2. Values

The simple rule of passing by value is that all primitive values in JavaScript are passed by value. Simple as that.

Passing by value means that every time you assign a value to a variable, a copy of that value is created. Every single time.

Values in JavaScript

Let me show you how pass by value manifests itself.

Let's say you have 2 variables a and b:


let a = 1;

let b = a;

b = b + 2;

console.log(a); // 1

console.log(b); // 3


The first statement let a = 1 defines a variable a initialized with the number 1.

The second statement let b = a defines another variable b and initializes it with the value of a variable — which is passing by value. Simpler, a copy of the number 1 is assigned to b.

Later, b = b + 2 increases by 2 and becomes 3. b variable changes, and this change doesn't affect the value of a.

3. References

The pass by reference, however, manifests itself differently.

When creating an object you're given a reference to that object. If 2 variables hold the same reference, then changing the object reflects in both variables.

References in JavaScript

Let's check the following code sample:


let x = [1];

let y = x;

y.push(2);

console.log(x); // [1, 2]

console.log(y); // [1, 2]


The first statement let x = [1] creates an array, defines a variable x, and initializes the variable with a reference to the created array.

Then let y = x defines a variable y, and initializes y with the reference stored in x variable. This is a pass by reference.

y.push(2) mutates the array by pushing an item 2. Because x and y variables reference the same array, this change is reflected in both variables.

Note: for simplicity, I say that variables hold references to objects. But strictly saying variables in JavaScript hold values that are references to objects.

4. Comparing values and comparing references

Understanding the difference between values and references is important when you want to compare objects.

When using the strict comparison operator ===, 2 variables having values are equal if they have the same value. All of the below comparisons are equal:


const one = 1;

const oneCopy = 1;

console.log(one === oneCopy); // true

console.log(one === 1); // true

console.log(one === one); // true


one and oneCopy have the same value 1. The operator === evaluates to true as longs as both operands are 1, no matter where the value is taken from: a literal 1, variable's value, expression 2 - 1.

But the comparison operator === works differently when comparing references. 2 references are equal only if they reference exactly the same object.

ar1 and ar2 hold references to different array instance:


const ar1 = [1];

const ar2 = [1];

console.log(ar1 === ar2); // false

console.log(ar1 === [1]); // false

const ar11 = ar1;

console.log(ar1 === ar11); // true

console.log(ar1 === ar1); // true


ar1 and ar2 reference arrays of the same structure, however ar1 === ar2 evaluates to false because ar1 and ar2 reference different array objects.

The comparison operator returns true only when comparing references pointing to the same object: ar1 === ar11 or ar1 === ar1.

5. Summary

In JavaScript primitive types are passed around as values: meaning that each time a value is assigned, a copy of that value is created.

On the other side objects (including plain objects, array, functions, class instances) are references. If you modify the object, then all variables that reference that object are going to see the change.

The comparison operator distinguishes comparing values and references. 2 variables holding references are equal only if they reference exactly the same object, but 2 variables holding values are equal if they simply have 2 same values no matter where the value originates: from a variable, literal, etc.

Often, however, you might want to compare objects by their structure rather than by reference. Check out the post How to Compare Objects in JavaScript.