1. 데이터타입

jihyun·2021년 7월 24일
0

코어자바스크립트

목록 보기
1/6
post-thumbnail

1-1 데이터 타입의 종류

✔️ 기본형(원시형, primitive type) ⇒ 값이 담긴 주솟값 바로 복제

  • number
  const num = 33;
  const infinity = 1 / 0; // Infinity
  const negativeinfinity = -1 / 0; // -Infinity
  const nAn = Number("hi"); // NaN

  console.log(typeof num); // "number"
  console.log(typeof infinity); // "number"
  console.log(typeof negativeinfinity); // "number"
  console.log(typeof nAn); // "number"
  • string
    const str1 = "문자열"; 
    const str2 = 'string';
    const str3 = str1 + str2 + 3; // "문자열string3"

    console.log(typeof str1); // "string"
    console.log(typeof str2); // "string"
    console.log(typeof str3); // "string"
  • boolean ( true / false )
    //falsy값 제외하고 전부 truthy이므로 falsy를 기억하자
    0, -0, "", '', NaN, null, undefined, false
  • null
  • undefined
  • symbol

✔️ 참조형(객체, refernce type) ⇒ 값이 담긴 주솟값으로 이루어진 묶음을 가리키는 주솟값을 복제

  • object
    • array
    • function

⚠️ 객체처럼 사용되는 원시형 데이터?
원시형 데이터를 객체처럼 다룰 수 있도록 하기 위한 래퍼 객체(wrapper object) 제공

1-2 데이터 타입에 관한 배경지식

1-2-1 메모리와 데이터

bit: 2가지의 값(0 or 1), byte: 2 **8가지의 값

  • 자바스크립트 메모리 관리

    C, java 등 정적 타입 언어는 데이터 타입별로 할당할 메모리 영역이 달라진다.
    예를 들어 숫자도 범위에 따라 타입이 달라지고 변수 선언 시 데이터 타입을 지정해야 한다.
    동적 타입 언어인 javascript는 메모리 주솟값(=byte 단위의 식별자)을 통해 데이터를 구분, 연결한다.
    javascript에서는 숫자에 대해 8byte(64bit)를 확보한다.

1-2-2 식별자와 변수

✔️ 변수? 변할 수 있는 데이터가 담길 수 있는 공간

✔️ 식별자? 그 공간의 이름 = 변수명

1-3 변수 선언과 데이터 할당

1-3-1 변수 선언

var a; // 변수 선언
console.log(a); // undefined

  1. 변수 영역의 빈 공간(1)을 찾는다.
  2. 공간의 식별자를 a로 지정한다.

1-3-2 데이터 할당

var a; // 변수 선언
a = "Hi"; // 변수 a에 데이터 할당

  1. 변수 영역의 빈 공간(1)을 찾는다.
  2. 공간의 식별자를 a로 지정한다.
    **3. 데이터 영역의 빈 공간에 문자열 "Hi"를 저장한다.
  3. 변수 영역에서 식별자 a를 찾고, 그 공간에 문자열을 저장한 주소 @101을 대입한다.**

1-4 기본형 데이터와 참조형 데이터

1-4-1 불변값

✔️ 불변성? 데이터 영역 메모리의 "변경 가능성"

✔️ 원시형 데이터는 모두 불변값(immutable)

let a = 5; //a는 5라는 데이터를 담는 '식별자'
a = 7; // 값이 5에서 7로 바뀌는 것이 아니라 식별자 a가 데이터 5의 주소가 아닌 7의 주소를 담게 됨
//5와 7 데이터는 변하지 않음 =>"immutable"

1-4-2 가변값

✔️ 참조형 데이터는 기본적으로 가변값

const obj = {
  a: 32,
  b: 'male'
} // object인 객체는 또 다른 데이터의 주소값을 참조

1-4-3 변수 복사 비교

// 변수 복사 후 객체의 프로퍼티를 변경 => "참조형 데이터가 가변값"
let a = "Hi";
let obj = {
	age: 32,
	gender: "male"
};

let b = a;
let obj2 = obj1;

b = "Hello";
obj2.age = 33;
// 변수 복사 후 객체 자체를 변경
let a = "Hi";
let obj = {
	age: 32,
	gender: "male"
};

let b = a;
let obj2 = obj1;

b = "Hello";
obj2 = {
	age: 33,
	gender:"male"
}

1-5 불변 객체

1-5-1 불변 객체를 만드는 간단한 방법

✔️ 참조형 데이터의 '가변'은 데이터 자체가 아닌 내부 프로퍼티를 변경할 때만 성립

1-5-2 얕은 복사와 깊은 복사

✔️ 얕은 복사 ? 바로 아래 단계의 값만 복사

✔️ 깊은 복사 ? 내부 모든 값들을 하나하나 전부 복사 => 원본과의 참조가 완전히 끊어진 객체
객체 프로퍼티 중 값이 기본형 데이터인 경우 그대로 복사, 참조형 데이터는 다시 그 내부의 프로퍼티를 복사

let one = { name: "one" };
const two = { name: "two" };

const something = one;

one = { name: "ONE" };
console.log(something); // { name: "one" };
//객체의 깊은 복사 

let copyObj = function(target) {
	var result = {};
	if (typeof target === "object" && target !== null) {
		for(var prop in target) {
			result[prop] = copyObj(target[prop]);
		}
	} else {
			result = target;
	}
	return result;
};

1-6 undefined와 null

✔️ 둘 다 "없음"을 나타내는 값

✔️ undefined? 의도치 않게 값이 존재하지 않을 때 자바스크립트 엔진이 자동으로 부여 (직접 할당은 지양)

✔️ null? 사용자가 명시적으로 "값이 없음"을 나타낼 때

let nullData = null;
console.log(typeof nullData); // object => js 버그

//동등 연산자 사용
console.log(nullData == null); //true
console.log(nullData == undefined); // true

//일치 연산자 사용
console.log(nullData === null); //true
console.log(nullData === undefined); // false

//동등연산자 아닌 일치연산자(===) 사용할 것
// 초기값이 할당되지 않은 변수
let a;
console.log(a); // undefined

// 초기값이 할당되지 않은 매개변수
function foo (a, b) {
  console.log(a); // 1
  console.log(b); // undefined
}
foo(1);

// return문이 없거나 호출되지 않은 함수의 실행 결과
function foo (a, b) {
	let result = a + b;
}
console.log(foo(1, 2)); // undefined

// 객체에서 존재하지 않는 속성을 접근하는 경우
const student = {
  name: 'jihyun'
};
console.log(student.age); // undefined
  • var, let, const

    ✔️ var와 let

    • var는 Global Scope(함수 scope)
      let은 Block Scope : 중괄호{ }를 기준으로 scope 생성(for loop 해당)
    • var를 이용하여 선언한 전역 변수는 전역 객체의 Key/Value로 추가
      let을 이용하여 선언한 전역 변수는 undefined
        var x = "global";
        let y = "global";

        console.log(window.x); // "global"
        console.log(window.y); // undefined
  • var를 이용하여 선언한 변수는 undefined로 초기화되어 시작

    let을 이용하여 선언한 변수는 해당 선언문이 실행되기 전까지 초기값 X

    초기값이 정해지지 않은 let 변수는 접근 불가능(Reference Error): temporal dead zone (TDZ)

    /* hoisting? 변수 선언문이 해당 scope 내에서 최상위로 끌어올려지는 것
    변수 선언문이 실행되기 전에 undefined로 초기화(실제로 실행되는 것은 아님) */

    console.log(a); // undefined
    var a; // 변수선언 + 초기화
    console.log(a); // undefined
    a = 20; // 할당
    console.log(a); // 20

    console.log(a) // ReferenceError
    let a; // 변수선언 + 초기화 => 실제 실행 => let변수 접근 가능해짐
    console.log(a); // undefined
    a = 20; // 할당
    console.log(a); // 20

    {
     	// This is the temporal dead zone for the age variable!
    	// This is the temporal dead zone for the age variable!
    	// This is the temporal dead zone for the age variable!
     	// This is the temporal dead zone for the age variable!
    	let age = 25; // Whew, we got there! No more TDZ
    	console.log(age);
    }

    letconstTDZ? scope의 시작점부터 선언(+초기화) 전까지
    해당 선언문이 실행되기 전까지 초기값이 정해지지 않음
    ```

    ✔️ const

    - Block Scope: 중괄호{ }를 기준으로 scope 생성
    - '='를 사용한 재할당 불가능

 ```javascript
    const obj = {
    	arr: [1,2,3]
    }
    obj = [];           // X
    obj.arr.length = 0; // arr: []
    obj.arr.push(1);    // arr: [1]

⚠️ 기본적으로 const 사용, 재할당 필요한 경우 let (var는 X)

0개의 댓글