Primitive Types and Reference Types

This post provides an overview of primitive types and reference types in programming, highlighting their characteristics, differences, and use cases. Understanding these two categories is crucial for effective programming, as they impact memory management, performance, and the behavior of variables in various programming languages.


Primitive Types and Reference Types


๐Ÿงฑ Primitive Types

Primitive types are the basic building blocks of data in JavaScript. They hold simple and fixed values, and are stored directly in memory.

โœ… Key Characteristics:

  • Stored by value

  • Immutable (cannot be changed)

  • Fast and lightweight

  • Compared by value

๐Ÿงช Examples:

Type Example Value
String     "hello"
Number     42, 3.14
Boolean     true, false
Undefined         A variable with no value: let x;
Null         An intentional "no value": let y = null;
Symbol     Symbol("id")
BigInt     12345678901234567890n

๐Ÿง  Example in Code:

let a = 10;
let b = a;
b = 20;
console.log(a); // 10 โ€“ `a` stays unchanged
JavaScript

๐Ÿ‘‰ b got a copy of the value of a.


๐Ÿ“ฆ Reference Types

Reference types are more complex. They store a reference (memory address) pointing to the actual data stored elsewhere.

โœ… Key Characteristics:

  • Stored by reference

  • Mutable (can be changed)

  • Compared by reference (not by value)

๐Ÿงช Examples:

Type Example
Object     { name: "Alice" }
Array     [1, 2, 3]
Function     function greet() {}
Date     new Date()
RegExp     /abc/

๐Ÿง  Example in Code:

let obj1 = { name: "Ali" };
let obj2 = obj1;
obj2.name = "Sara";
console.log(obj1.name); // "Sara" โ€“ because both point to the same object
JavaScript

๐Ÿ‘‰ obj2 and obj1 refer to the same object in memory.


Primitive Types and Reference Types




๐Ÿง  Summary Table

Feature Primitive Types Reference Types
Stored as         Value     Reference (memory address)
Mutable?         No     Yes
Compared by         Value     Reference
Examples string, number, etc object, array, function


Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

Making GUI Calculator in Tkinter Python

Unlocking Web Design: A Guide to Mastering CSS Layout Modes