JavaScript Course
JavaScript
/
Intermediate

Primitive vs Reference Types

Definition

Primitive types (string, number, boolean, null, undefined, symbol) are stored directly in memory. Reference types (objects, arrays, functions) are stored as a pointer (reference) to a location in memory.

Explain Like I'm New

Primitives are like giving your friend a photocopy of a recipe. If they spill coffee on their copy, your original is safe. Reference types are like giving your friend the keys to your house. If they break a window, YOUR house is broken.

Real World Example

If you pass an object into a function `updateUser(user)`, and modify `user.name` inside the function, the original object outside the function is permanently altered because they share the same memory reference.

Common Use Cases

  • •Understanding immutability in React
  • •Preventing accidental data mutation

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Are arrays copied by value or by reference?

intermediate

  • How do you copy an object without mutating the original?

advanced

  • Is JavaScript pass-by-value or pass-by-reference?

Flash Cards

Question

Are arrays copied by value or reference?

Click to reveal answer
Answer

Reference. `const a = [1]; const b = a; b.push(2);` will result in `a` also becoming `[1, 2]`.

Question

Is JS pass-by-value or pass-by-reference?

Click to reveal answer
Answer

JavaScript is ALWAYS pass-by-value. However, when you pass an object into a function, the 'value' being passed is the memory address reference. This is known as 'Call-by-sharing'.