동적 타입 Dynamic Type
JS는 느슨한 타입의 동적 언어 (loosely typed dynamic language)
JS에서 변수는 특정 타입과 연결되지 않고, 모든 타입의 값으로 (재)할당 가능하다.
- 한 변수가 여러개의 타입을 가질 수 있다.
- 타입을 명시하지 않아도 된다.
- 대부분의 다른 언어는 정적(static) 타입 언어이다. (Java, C#, C++ 등)
let user = 'tang' // string
user = 25 // number
user = true // boolean
let anything // undefined
const car = null
const sym = Symbol()
원시 타입 Primitive Types
: 변수에 값을 직접 할당 → 불변성
string, number, bigint, boolean, undefined, symbol, null
*symbol(ES6) : 변경 불가능한 유일한 값을 생성할 때 사용하며,
값 자체의 확인이 불가하여 외부로 노출되지 않습니다.
📦 저장
1) 실제 값은 고정된 크기로 Call Stack 메모리에 저장
2) 변수는 Call Stack 속 데이터의 주소를 바라봄
📑 복사
1) Call Stack 에 있던 데이터 복사본, 즉 실제 값 복사
2) 수정시 원본 유지
참조 타입 Objecty Types (Reference Values)
: 변수에 값 주소를 할당
object, array, class, function
📦 저장
1) 실제 값은 HEAP 메모리에 저장
2) 데이터의 메모리 주소는 크기가 정해지지 않고 Call Stack 에 복사
3) 변수는 Call Stack 속 데이터의 메모리 주소의 위치를 바라봄
📑 복사
1) Call Stack 에 있던 데이터 복사본 생성
2) 데이터의 주소 복사되어 새 변수에 할당
그렇게 되면?
얕은 복사 Shallow Copy
❗️ 원본과 복사본들끼리 HEAP 에 저장된 한 데이터를 같이 바라봄
‼️ 하나 수정시 다른 것들 또한 모두 수정됨
function increasePriceByTen(fruit) {
fruit.price += 10;
}
let apple = {name: 'Apple', price: 120}
let copyOfApple = apple
increasePriceByTen(apple)
console.log(apple.price) // => 130
console.log(copyOfApple.price) // => 130
그래서 제대로 된 복사를 하려면?
깊은 복사 Deep Copy
const fruits = ['apple', 'banana', 'orange']
const basket = {
contents: ['banana', 'cherry']
type: 'fruits'
}
Case. 1 depth
**1 depth일때만 유효. 2 depth 부터는 얕은 복사
/* 1 depth only */
// 1. for...in loop
const copyFruits1 = []
const copyBasket1 = {}
for (index in fruits) {
copyFruits1[index] = fruits[index]
}
for (key in Basket) {
copyBasket1 = basket[key]
}
// 2. Object.assign()
const copyFruits2 = Object.assign([], fruits)
const copyBasket2 = Object.assign({}, basket)
// 3. spread operator ...
const copyFruits3 = [...fruits]
const copyBasket3 = {...basket}
// 4. Array.splice(0) - only Array
const copyFruits4 = fruits.splice(0)
// 5. _.clone() - lodash library
const _ = require('lodash')
const copyFruits5 = _.clone(fruits)
const copyBasket5 = _.clone(basket)
Case. 2 depth
/* over 2 depth */
// 6. JSON.parse(JSON.stringfy())
const copyFruit6 = ?
const copyBasket6 = JSON.parse(JSON.stringfy(basket))
// 7. _.cloneDeep() - lodash library
const _ = require('lodash')
const copyFruits7 = ?
const copyBasket7 = _.clone(basket)
https://119taeyoung.tistory.com/78
[JS] 깊은 복사(deep copy)와 얕은 복사(shallow copy)
1. 객체 복사란 / 중첩 객체 복사 참조에 의한 객체 복사 ko.javascript.info 2. 깊은 복사와 얕은 복사의 차이점 [JavaScript] 얕은 복사(shallow copy) vs 깊은 복사(deep copy) - 하나몬 💡 얕은 복사(shallow copy) vs
119taeyoung.tistory.com
stack
parameters, automatic and temporary variables
함수의 호출과 관계되는 지역 변수와 매개변수가 저장되는 영역
heap
dynamically allocated variables
사용자에 의해 직접 동적으로 할당되고 해제되는 메모리 공간
ref.
배열, 객체를 const로 선언했는데 요소나 속성을 추가할 수 있는 이유?
배열, 객체를 const 키워드로 선언했는데 요소나 속성을 추가할 수 있는 이유에 대해서 설명해주세요. Const 변수에 할당된 값은 바뀌지 않지만, 배열/객체가 변수에 할당될 때에는 배열/객체의 요
intothenight.tistory.com
https://akkisdiary.medium.com/pass-by-value-and-pass-by-reference-in-javascript-f621b43bc2e9
Pass by Value and Pass by Reference in JavaScript
Let's look at how values are passed, copied, and stored in memory by JavaScript.
akkisdiary.medium.com
'A-HA💡 > JS' 카테고리의 다른 글
[JS/알고리즘] 백준1085. 최솟값 최댓값 (0) | 2024.04.02 |
---|---|
[JS] sort(), toSorted() (0) | 2024.01.31 |
[JS] console 객체 (log, dir, ..) (0) | 2023.12.27 |
[JS] 배열에 요소 추가하는 방법⭐️⭐️ (0) | 2023.12.27 |
[JS] 배열에서 특정 값 찾는 방법 ⭐️ (0) | 2023.12.22 |