[JS] 데이터 타입
Use struct
정의되지 않은 변수 사용, 변수나 객체의 삭제, 함수 파라미터에 중복된 이름 등 비상식적인 것을 사전에 막아준다.
// 1. Use strict
// added in ES 5
// use this for Valina Javascript
'use strict';
js 상단에 'use strict'를 추가해 사용하면 된다.
Variable(변수)
: 변수는 변경될 수 있는 값을 얘기 한다. 값을 읽고 쓰는게 가능하다.
let (added in ES6)
let를 이용해 name변수를 정의하게 되면 메모리의 한 공간을 가리킬 수 있는 포인터가 생기게 된다.
name이라는 변수가 가르키는 메모리 어딘가에 name의 값 저장할 수 있게 된다.
또한 name이라는 공간에 다른 값을 넣어서 저장할 수도 있게 된다.
Block scope / Global scope
Block scope 내에 변수를 선언하면 Block scope 밖에서는 해당 변수를 사용 할 수 없다.
파일안에다가 변수를 정의하는 것을 Global scope라고 하는데 어느곳에서나 접근 가능하다.
하지만 어플리케이션이 끝날때까지 메모리에 할당되어져있기 때문에 최소한으로 사용해야한다
let globalName = 'global name';
{
let name = 'hee';
console.log(name); // hee
console.log(globalName); // global name
}
console.log(name);
console.log(globalName); // global name
var (don't ever use this!)
var는 변수를 선언하기 전에 값을 할당 할 수 있고 출력이 가능하다. 이러한 현상을 var hoisting이라고 한다.
hoisting은 어디에 선언했느냐에 상관없이 항상 제일 먼저 위로 선언을 끌어올려주는 것을 말한다.
console.log(age) // 결과 : undefined
age = 4;
console.log(age) // 결과 : 4
var age;
맨 위 콘솔로드에서 age를 출력하게 되면 값이 할당되지 않았지만 선언이 되어있기 때문에 undefined로 출력.
let 을 사용해 실행하게 되면 'Identifier 'age' has already been declared' 라는 오류가 출력된다.
또한, var는 Block scope를 철저히 무시한다.
{
age = 4;
var age;
}
console.log(age) // 결과 : 4
Constants
📝 값을 할당하면 절대 값을 바꿀 수 없다. 보안에 강하다는 장점이 있다.
📝 읽기만 가능하다.
Variable Types
Primitive type과 Object type으로 나눌 수 있다.
Primitive type : 더 이상 쪼갤수 없는 타입(single item), number, string, boolean, null, undefined, symbol등이 있다.
Object type : 여러가지의 single item을 한 단위로 묶어서 관리 할 수 있다.
function : JS에서는 데이터 타입 중 하나이다. 다른 데이터 타입처럼 변수 할당이 가능하고 함수의 인자로도 전달 되고 함수에서 return 타입으로도 사용가능하다.
Number
const count = 17; // integer
const size = 17.1; // decimal number (소수)
console.log(`value: ${count}, type: ${typeof count}`); // value : 17, type : integer
console.log(`value: ${size} , type : ${typeof size}`); // value : 17.1, type : decimal number
const infinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = 'not a number' / 2; // string 을 숫자로 나눈 경우
console.log(infinity); // Infinity -> 1/0 은 무한대 값이므로 Infinity이 출력
console.log(negativeInfinity); //-Infinity
console.log(nAn); // NaN
String
const char = 'c';
const brendan = 'brendan';
const greeting = 'hello' + brendan;
console.log(`value: ${greeting}, type: ${typeof greeting}`); // value: hellobrendan, type: string
const helloBob = `hi ${brendan}!`; // template literals (string)
console.log(`value: ${helloBob}, type: ${typeof helloBob}`); // value: hi brendan!, type: string
Boolean
Boolean에는 True와 False 두가지가 있다.
False : 0, null, undefined, NaN, ''
Ture : 그 외 다른 값
🌝 null 과 undefined
// 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
// symbol, create unique identifiers for objects
const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 === symbol2); // false
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2); // true
console.log(`value: ${symbol1.description}, type: ${typeof symbol1.description}`);
// value : id , type : string
Dynamic Typing
JavaSciprt는 선언할 때 어떤 타입인지 선언하지 않고 Run Time시 타입을 결정한다. (프로그래밍이 동작할 때 할당된 값에 따라서 타입이 변경될 수 있다.)
let text = 'hello';
console.log(`value: ${text}, type: ${typeof text}`); // value : hello , type : string
text = 1;
console.log(`value: ${text}, type: ${typeof text}`); // value : 1 , type : number
위에서 text는 string이었지만 text를 nuber로 형변환하였다. JS는 Dynamic typing language이기 때문에 가능하다.
따라서 JavaScript는 런타임에서 변수 타입이 정해지기 때문에 에러 역시 런타임으로 발생하게 된다.
Primitive type 과 Object type 의 저장 방식
const ellie = {name : 'ellie', age : '30'};
ellie는 const로 정의되어 있기 때문에 다른 ocject로 할당이 불가능하지만, ellie object 안에는 name과 age라는 변수들이 존재하므로 각각 포인트가 가리키고 있는 메모리에 다른 값이 할당 가능하다.
드림코딩 by 엘리 의 JS 강의를 시청 후 정리한 내용입니다.