JavaScript
[JavaScript] 데이터 타입, let / var, hoisting
by happenstance
2021. 8. 5.
// 1. Use strict
// added in ES5
// use this for Vanilla Javascript.
'use strict';
// 2. Variable, rw(read/write)
// Mutable 타입
// variable은 memory에 값을 읽고 쓰는 것이 가능함
// let (added in ES6) (자바스크립트에서 변수를 선언할 수 있는 단 하나의 키워드)
let globalName = 'global name'; // 전역 변수
{
let name = 'hello';
console.log(name);
name = 'hi'; // let은 재할당이 가능하기 때문에 'hi'를 저장해도 잘 출력됨
console.log(name);
console.log(globalName); // 전역 변수는 어디서나 사용이 가능함
}
console.log(name); // {} 안에서 선언한 변수로 {} 밖에선 사용이 불가능함
console.log(globalName);
// var (let이 나온 후 사용하지 않음)
// var hoisting (어디에 선언했는지에 상관없이 그것을 제일 위로 올려줌)
// 변수를 선언하기 전에 값 할당이 가능하며, 값을 할당하기 전에 출력 가능함
// 블록을 무시함 (블록 안에서 선언하더라도 밖에서 사용 가능함)
// 3. Constant, r(read only)
// Immutable 타입
// use const whenever possible.
// only use let if variable needs to change.
// 한 번 할당하면 값이 절대 변하지 않음 (읽기만 가능함)
const dayInWeek = 7;
const maxNumber = 5;
// Note!
// Mutable data types: all objects by default are mutable in JS => 변경 가능
// Immutable data types: primitive types, frozen objects (i.e. object.freeze()) => 변경 불가능
// favor immutable data type always for a few reasons:
// - security
// - thread safety
// - reduce human mistakes
// 4. Variable types
// primitive type : 더이상 작은 단위로 나눠질 수 없는 한 가지의 item
// number, string, boolean, null, undefined, symbol
// => single item
// object type : single item들을 한 box로 묶어서 관리하는 item
// => box container
// 자바스크립트는 값의 type에 관계없이 number로 할당됨
// number
const count = 17; // integer
const size = 17.1; // decimal number
console.log(`value: ${count}, type: ${typeof count}`);
console.log(`value: ${size}, type: ${typeof size}`);
// 값이 valid한 값인지 확인한 후 연산하는 것이 중요함
// valid를 확인하지 않으면 사용자에게 에러가 발생할 수 있음
const infinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = 'not a number' / 2;
console.log(infinity);
console.log(negativeInfinity);
console.log(nAn);
// string
// 자바스크립트에서는 한 글자든 여러 글자든 string으로 할당됨
const char = 'c';
const brendan = 'brendan';
const greeting = 'hello ' + brendan;
console.log(`value: ${greeting}, type: ${typeof greeting}`);
const helloBob = `hi ${brendan}!`; // template literals (string)
console.log(`value: ${helloBob}, type: ${typeof helloBob}`);
// 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}`);
console.log(`value: ${test}, type: ${typeof test}`);
// null
let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);
// undefined ( != null)
let x;
console.log(`value: ${x}, type: ${typeof x}`);
// symbol, create unique identifiers for objects
// 나중에 map이나 다른 자료구조에서 고유한 식별자가 필요하거나
// 동시다발적으로 일어날 수 있는 코드에서 우선순위를 주고 싶을 때 사용함
// 식별자를 string을 이용하면 다른 모듈이나 다른 파일에서 동일한 string을 사용하였을 때 동일한 식별자로 간주함
// 아래의 코드는 동일한 'id'를 이용하여 symbol을 생성하였으나 두 개의 symbol은 같지 않음
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
// symbol 출력하기 => .description 이용
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`);
// object, real-life object, data structure
// 물건, 물체들을 대표하는 box 형태
const kim = { name: 'kim', age: 20 };
// 한 번 할당된 object 'kim'은 다시는 다른 object로 변경이 불가능함
// 'kim' object 안의 name과 age는 다른 값으로 할당 가능함
kim.age = 21;
// 5. Dynamic typing: dynamically typed language
// 선언시 어떤 타입인지 선언하지 않고 프로그램이 동작할 때 할당된 값에 따라 값이 변할 수 있음을 의미함
let text = 'hello'; // text는 string 타입 변수가 됨
console.log(text.charAt(0)); // h
console.log(`value: ${text}, type: ${typeof text}`);
text = 1; // text는 number 타입 변수가 됨
console.log(`value: ${text}, type: ${typeof text}`);
text = '7' + 5; // text는 string 타입의 '75'가 됨
console.log(`value: ${text}, type: ${typeof text}`);
text = '8' / '2'; // text는 number 타입 변수가 됨 (나눗셈 등의 연산자의 경우 string을 number로 변환하여 값을 출력함)
console.log(`value: ${text}, type: ${typeof text}`);
console.log(text.charAt(0)); // text는 number 타입이기 때문에 에러가 발생함