TIL | 자바스크립트 데이터 타입

이은빈 EUNBIN·2021년 2월 18일
0

JavaScript

목록 보기
3/5
post-thumbnail

* 본 게시글은 '드림코딩 by 엘리'의 유튜브 영상을 기반으로 간략히 정리하여 작성되었습니다.



👩🏻‍💻 변수 선언

💡 let

ES6에서 추가된 변수 선언 방법
변수를 정의하면 일정 크기의 메모리를 가리킬 수 있는 포인터 생성
포인터를 이용하여 메모리 안에 원하는 값을 저장 또는 변경(mutable) 가능

포인터(pointer)란? 다른 변수, 혹은 그 변수의 메모리 공간주소를 가리키는 변수

포인터 위키백과



💡 const

const는 constant의 의미로, 값을 한번 할당하면 값이 절대 변경 불가
즉, 메모리를 가리키는 포인터가 잠겨있음

[ 변경되지 않는 데이터타입을 사용해야 하는 이유 ]

  • Security : 다른 해커들이 코드를 삽입하여 값을 변경시키지 못하게 하기 위해 필요
  • Thread Safety : 어플리케이션이 실행되면 한 가지의 프로세스가 할당되고 프로세스 안에서는 다양한 스레드가 동시에 돌아가면서 어플리케이션이 잘 돌아갈 수 있도록 도와줌. 이때 다양한 스레드가 동시에 변수에 접근하여 값을 변경할 수 있는데 이는 위험하다는 의미도 포함하고 때문에 가능하면 변경되지 않는 값을 이용하는 것이 좋음
  • Reduce Human Mistakes : 코드가 수정될 일이 있을 때 인간의 실수를 방지할 수 있음


💡 Block Scope {}

블록 안에서 선언한 변수는 블록 안에서만 접근 가능

↔ Global Scope : 선언한 변수는 어느 곳에서나 접근이 가능하며, 어플리케이션이 실행되는 순간부터 끝날 때까지 메모리에 탑재돼있기 때문에 필요한 블록 안에서 변수를 선언하여 접근하는 것이 효율적



💡 var를 사용하면 안되는 이유

선언하기 전에 값 할당이나 심지어 출력이 가능 → var hoisting
varblock scope을 무시하기 때문에 오류를 발생시킬 가능성이 큼

hoisting : 어디서 선언했느냐와 상관 없이 항상 제일 위로 선언을 끌어올려주는 것




👩🏻‍💻 Variable Types

💡 primitive

더 이상 작은 단위로 나눠질 수 없는 single item
ex) number, string, boolean, null, undefined, symbol


① string

한 가지의 글자든 여러 개의 글자든 상관 없이 string 타입으로 분류

const char = 'c';
const brendan = 'brendan';
const greeting = 'hello ' + brendan;

console.log(`value: ${greeting}, type: ${typeof greeting}`);
//value: hello brendan, type: string

const helloBob = `Hi ${brendan}`;
console.log(`value: ${helloBob}, type: ${typeof helloBob}`);
//value: Hi brendan, type: string

② boolean

false : 0, null, undefined, NaN, ''
true : any other value

const canRead = true;
const test = 3 < 1; //false

console.log(`value: ${canRead}, type: ${typeof canRead}`);
//value: true, type: boolean
console.log(`value: ${test}, type: ${typeof test}`);
//value: false, type: boolean

③ null

null값을 할당할 경우 비어 있는 값으로 지정해주는 것

let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);
//value: null, type: object

④ undefined

선언은 되었지만 아무 값도 정해지지(할당되지) 않은 상태

let x;
console.log(`value: ${x}, type: ${typeof x}`);
//value: undefined, type: undefined

⑤ symbol

동시에 다발적으로 발생할 수 있는 코드에 우선순위를 주고 싶거나 고유한 식별자가 필요할때 사용

const symbol1 = Symbol('id');
const symbol2 = Symbol('id');

console.log(symbol1 === symbol2); //false
//동일한 값을 이용해서 symbol을 만들었으나 두 symbol은 고유한 식별자로 구분됨

//데이터타입이 동일하여 동일한 symbol을 만들고 싶다면 for을 사용
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');

console.log(gSymbol1 === gSymbol2); //true
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`);
//value: id, type: symbol
//symbol을 출력하고 싶다면 .description을 사용하여 string으로 변환 후 출력

💡 object

single item을 묶어서 한 단위로 관리할 수 있게 해주는 타입
ex) box container

const ellie = { name: 'ellie', age: 20 };
ellie.age = 21;


💡 function

자바스크립트에서는 function도 하나의 데이터타입으로 간주
ex) first-class function (function도 다른 데이터타입처럼 변수에 할당이 가능, 함수의 파라미터나 return 으로도 사용 가능)



💡 special numeric values

infinity, -infinity, NaN
연산 시 오류가 나지 않도록 타당한 값인지 확인하는 것이 중요!

const inifinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = 'not a number' / 2;

console.log(infinity); //Infinity
console.log(negativeInfinity); //-Infinity
console.log(nAn); //NaN


💡 bigInt (아직 사용하지는 않음)

자바스크립트에서는 -2의 53승 ~ 2의 53승 범위의 숫자만 표현 가능한데 숫자에 n을 붙이면 bigInt로 간주
최근에 추가된 것이기 때문에 chrome과 firefox에서만 지원

const bigInt = 1234567890123456789012345678901234567890n; //over (-2**53) ~ 2*53
console.log(`value: ${bigInt}, type: ${typeof bigInt};
//value: 1234567890123456789012345678901234567890, type: bigint
Number.MAX_SAFE_INTEGER;



👩🏻‍💻 Dynamic Typing (dynamically typed language)

선언할 때 어떤 타입인지 선언하지 않고 런타임일 때(프로그램이 동작할 때) 할당된 값에 따라 타입이 변경될 수 있다는 의미

let text = 'hello';
console.log(`value: ${test}, type: ${typeof text}`);
//value: hello, type: string

text = 1;
console.log(`value: ${test}, type: ${typeof text}`);
//value: 1, type: number

text = '7' + 5; 
console.log(`value: ${test}, type: ${typeof text}`);
//value: 75, type: string
//문자열 다음에 +가 있으므로 string과 string을 합해주는 것으로 처리

text = '8' / '2'; 
console.log(`value: ${test}, type: ${typeof text}`);
//value: 4, type: number
//숫자를 나누는 '나누기 연산자'를 파악하고 
//string안에 값이 실제로는 number값임을 파악하여 number로 처리

text라는 변수가 처음에는 string 타입이었으나 중간에 number로 변경되었는데 개발자가 여전히 string으로 간주하고 text.charAt(0); 과 같은 함수를 부르게 되면 런타임 때 오류 발생
→ 이러한 오류로 인해 TypeScript 등장






참고 자료
드림코딩 by 엘리

이미지 출처
드림코딩 by 엘리

profile
Frontend Engineer & Value Creator

0개의 댓글