Web/JavaScript

(JavaScript) Primitives vs References types

haramang 2021. 10. 31. 15:08

 

'use strict';

 

// Primitives vs. Objects (Primitive vs. Referece Types)

 

// Primitive Types : Number, String, Boolean, Undefined, Null, Symbol, BigInt

// Object Types: Object literal, Array, Functons, Many more

// Primitive types are stored in CALL STACK

// Object Types are stored in HEAP

 

// Primitive data types are immutable in JS, so every time we assign a new value,

// a new address is created to store it.

 

// Object types that is const can be changed because it is on the heap which doesn't get affected by

// READ-only RULE since we never try to modify the addresss in the stack

 

let age = 30;

let oldAge = age;

 

age = 31;

console.log(age); // 31

console.log(oldAge); // 30

 

const me = {

  name: 'Hongsik',

  age: 34,

};

 

const friend = me;

friend.age = 27;

console.log(friend); // Both age are 27 - changed!

console.log(me);

 

// Primitive types

let lastName = 'Williams';

let oldLastName = lastName;

lastName = 'Davis';

console.log(lastName, oldLastName);

 

// Referece types

const jessica = {

  firstName: 'Jessica',

  lastName: 'Williams',

  age: 27,

};

 

const marriedJessica = jessica;

marriedJessica.lastName = 'Davis';

console.log('Before marriage: ', jessica);

console.log('After marrriag: ', marriedJessica);

 

// marriedJessica = {};      // Let - possible, but now error

 

// Copying objects

const jessica2 = {

  firstName: 'Jessica',

  lastName: 'Williams',

  age: 27,

  family: ['Alice', 'Bob'],

};

 

// Shallow copy - only assign first level of object - inner object still be the same

const jessicaCopy = Object.assign({}, jessica2); // Create New objecy copying jessica 2

 

jessicaCopy.lastName = 'Davic';

 

jessicaCopy.family.push('Mary'); // jessica changed since object.assign is shallow copy

jessicaCopy.family.push('John');

 

console.log('Before marriage: ', jessica2);

console.log('After marrriag: ', jessicaCopy);



'Web > JavaScript' 카테고리의 다른 글

(JavaScript) Rest Pattern  (0) 2021.11.01
(JavaScript) Destructuring  (0) 2021.10.31
(JavaScript) Regular vs Arrow function  (0) 2021.10.31
(JavaScript) THIS Keyword  (0) 2021.10.31
(JavaScript) Hoisting and TDZ  (0) 2021.10.31