Home Web Front-end JS Tutorial JavaScript Variables: Understanding Primitives and Reference Types

JavaScript Variables: Understanding Primitives and Reference Types

Nov 21, 2024 pm 07:42 PM

JavaScript Variables: Understanding Primitives and Reference Types

Two basic sorts of data are stored in variables in JavaScript: primitives and reference types. Understanding the distinction between these two types is essential for memory management and for regulating the sharing, storing, and altering of data. This article delves into the distinctions, provides real-world examples, and examines methods for efficiently handling both kinds.


1. Primitives vs Reference Types

Primitives

The simplest kinds of data are called primitives. They directly store unchangeable data in the variable. The primitive types that JavaScript supports are as follows:

  • string: "hello"
  • number: 42
  • boolean: true or false
  • null
  • undefined
  • symbol
  • bigint

Key characteristics:

  • Immutable: Their value cannot be altered directly.
  • Stored by value.

Reference Types

On the other hand, reference types store the memory locations of objects. Rather than storing the actual value, variables save a reference to the memory address. Among the examples are:

  • object: { name: 'Alice' }
  • array: [1, 2, 3]
  • function: function() { console.log('hello'); }
  • Date: new Date()

Key characteristics:

  • Mutable: Their contents can be modified.
  • Stored by reference.

2. Primitives and Reference Types in Action

// Primitive Example
let a = 10;
let b = a;
b = 20;
console.log(a); // Output: 10

// Reference Example
let obj1 = { name: 'Alice' };
let obj2 = obj1;
obj2.name = 'Bob';
console.log(obj1.name); // Output: 'Bob'
Copy after login
Copy after login

Explanation:

  • Primitives: Assigning a to b creates a copy of the value. Changing b does not affect a since they are independent.
  • Reference Types: Both obj1 and obj2 point to the same memory location. Changing the content via obj2 also updates obj1.

3. Visualizing the Concept

  • Primitives: Imagine each variable as its own box containing a value. Copying creates a new box with an independent value.
  • Reference Types: Think of variables as labels pointing to a shared container. All labels referencing the same container are affected by changes made to its content.

4. Mutation vs Assignment

Understanding the difference between mutation and assignment is key when working with reference types.

Mutation: Modifies the contents of the existing object.

// Primitive Example
let a = 10;
let b = a;
b = 20;
console.log(a); // Output: 10

// Reference Example
let obj1 = { name: 'Alice' };
let obj2 = obj1;
obj2.name = 'Bob';
console.log(obj1.name); // Output: 'Bob'
Copy after login
Copy after login

Assignment: Changes the reference to a new object.

let arr = [1, 2, 3];
let arr2 = arr;
arr2.push(4);
console.log(arr); // Output: [1, 2, 3, 4]
Copy after login

5. Copying Objects and Arrays

Shallow Copy:

To create a separate copy of an object or array, use the spread operator (...) or Object.assign().

let arr = [1, 2, 3];
let arr2 = arr;
arr2 = [4, 5, 6];
console.log(arr); // Output: [1, 2, 3]
Copy after login

Deep Copy:

For nested objects, a deep copy is required. A common approach is using JSON.parse(JSON.stringify()).

let original = { name: 'Alice' };
let copy = { ...original };
copy.name = 'Bob';
console.log(original.name); // Output: 'Alice'
Copy after login

6. Pass by Value vs Pass by Reference

Primitives (Pass by Value):

When passing primitives to a function, a copy of the value is passed.

let nested = { person: { name: 'Alice' } };
let deepCopy = JSON.parse(JSON.stringify(nested));
deepCopy.person.name = 'Bob';
console.log(nested.person.name); // Output: 'Alice'
Copy after login

Reference Types (Pass by Reference):

When passing reference types, a reference to the memory location is passed.

function modifyValue(x) {
  x = 20;
}
let num = 10;
modifyValue(num);
console.log(num); // Output: 10
Copy after login

7. Primitive Wrapper Types

Even though primitives are immutable, JavaScript temporarily wraps them in objects to allow access to methods and properties.

function modifyObject(obj) {
  obj.name = 'Bob';
}
let person = { name: 'Alice' };
modifyObject(person);
console.log(person.name); // Output: 'Bob'
Copy after login

Explanation:

The string primitive 'hello' is temporarily wrapped in a String object to access the length property. The wrapper is discarded after the operation.


8. Best Practices

  1. Use const for Reference Types: Declaring objects and arrays with const prevents reassignment but allows mutation of contents.
let str = 'hello';
console.log(str.length); // Output: 5
Copy after login
  1. Avoid Unintended Mutations:
    If you need an independent copy, ensure you create one using the spread operator or deep copy techniques.

  2. Know When to Use Deep Copies:
    For shallow objects, a spread operator is sufficient, but nested structures require deep copies to avoid reference issues.

  3. Leverage Immutability:
    Use libraries like Immutable.js or embrace functional programming techniques to minimize bugs caused by unintended mutations.


9. Common Pitfalls

  1. Confusing Assignment with Mutation:
    Be mindful of whether you’re modifying an object or reassigning a reference.

  2. Modifying Shared References:
    Changes to a shared object can have unintended consequences if other parts of the program also use it.

  3. Assuming All Copies Are Independent:
    Remember that shallow copies do not protect against changes in nested structures.


Conclusion

One of the core ideas of JavaScript is the distinction between primitives and reference types. It affects how you send data to functions, manage variables, and prevent unexpected side effects in your code. You can build more dependable and maintainable JavaScript code by grasping these ideas and using best practices.

Follow me on : Github Linkedin

The above is the detailed content of JavaScript Variables: Understanding Primitives and Reference Types. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1654
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

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...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

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.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

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/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

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...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles