From 38cf678ec310eee46a82a87aeb8fcd43b81a89a8 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Sat, 9 Jan 2021 18:54:39 +1100 Subject: [PATCH] Finished Chapter 3.8 Immutable Primitive and Mutable Objectives --- notes/chap3_types_values_and_variables.md | 60 +++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/notes/chap3_types_values_and_variables.md b/notes/chap3_types_values_and_variables.md index 784ef70..470728f 100644 --- a/notes/chap3_types_values_and_variables.md +++ b/notes/chap3_types_values_and_variables.md @@ -536,6 +536,66 @@ Since ES2020, `globalThis` is used to refer to the global obj. ## 3.8 Immutable Primitive Values and Mutable Object References +Summary: in JS, primitive values are immutable, object values are mutable + +Primitives are immutable: +* Only new values can be created/returned +* Can be compared by value: + * Two string/array are equal iif they have same lenght, and char at index is the same. +```js +let s = "hello"; // Start with some lowercase text +s.toUpperCase(); // Returns "HELLO", but doesn't alter s +s // => "hello": the original string has not changed +``` + +Objects are mutable: +* Their values can change +* Not compared by value. Two distinct/independent obj are not equal even if they have the same properties and values. +* They are also called **reference types** to be distinguished from JS's primitive types. + * Two obj values are the same iff they **refer** to the same underlying object. e.g. `let b = a` + +Mutable obj +```js +let o = { x: 1 }; // Start with an object +o.x = 2; // Mutate it by changing the value of a property +o.y = 3; // Mutate it again by adding a new property + +let a = [1,2,3]; // Arrays are also mutable +a[0] = 0; // Change the value of an array element +a[3] = 4; // Add a new array element +``` + +Two distinct/independent obj +```js +let o = {x: 1}, p = {x: 1}; // Two objects with the same properties +o === p // => false: distinct objects are never equal +let a = [], b = []; // Two distinct, empty arrays +a === b // => false: distinct arrays are never equal +``` + +Obj are same if they refer the same obj: +```js +let a = []; // The variable a refers to an empty array. +let b = a; // Now b refers to the same array. +b[0] = 1; // Mutate the array referred to by variable b. +a[0] // => 1: the change is also visible through variable a. +a === b // => true: a and b refer to the same object, so they are equal. +``` + +How to compare 2 distinct objs: +* Compare their properties/elements one by one + +```js +function equalArrays(a, b) { + if (a === b) return true; // Identical arrays are equal + if (a.length !== b.length) return false; // Different-size arrays not equal + for(let i = 0; i < a.length; i++) { // Loop through all elements + if (a[i] !== b[i]) return false; // If any differ, arrays not equal + } + return true; // Otherwise they are equal +} +``` + ## 3.9 Type Conversions ### 3.9.1 Conversions and Equality