Skip to content
정명주(myeongju.jung) edited this page Jan 1, 2018 · 8 revisions

리터럴, 변수, 상수, 데이터 타입

변수(es6)

let currentTempC = 22;
currentTempC = 23;

let targetTempC, root1 = "conrerence_room_a", room2 = "lobby";

상수(es6)

// 상수
const ZERO = 0;
const ROOM_TEMP_C = 21.5, MAX_TEMP_C = 30;

리터럴

// 문자열 리터럴
let room1 = "conference_room_a";
// 객체 리터럴
let obj = {};
// 배열 리터럴
let objs = []; 

원시타입(primitive)과 객체(ojbect) 타입

원시타입

  • 불변, call by value

  • number(Double)

  • string

  • boolean

  • null

  • undefined

  • Symbol

객체(object)

  • Array
  • Date
  • RegExp
  • Map, WeakMap (since es6)
  • Set, WeakSet (since es6)

숫자

let count = 10;
const = blue = 0x0000ff;    // 16진수
const = umask = 0o0022;     //  8진수
const rommTemp = 21.5       // 10진수
const c = 3.0e6;            // 지수 (3.0 * 10^6 = 3,000,000)
const e = -1.6e-19          // 지수 (-1.6 * 10^-19 = 0.00000000000000000016)
const inf = Infinity;
const ninf = -Infinity;
const nam = NaN;

Number

const small = Number.EPSILON;             // 부동소수점 연산 근사치 비교를 위함
const maxInt = Number.MAX_SAFE_INTEGER;
const max = Number.MAX_VALUE;
const minInt = Number.MIN_SAFE_INTEGER;
const min = Number.MIN_VALUE;
const nInf = Number.NEGATIVE_INFINITY;    // -Infinity
const nan = Number.NaN;                   // NaN
const inf = Number.POSITIVE_INFINITY;     / Infinity

String

escape

const dialog1 = "He looked up and said \"don't do that!\" to Max.";
const dialog2 = 'He looked up and said "don\'t do that!" to Max.';
const s = "In JavaScript, use \\ as an escape character in strings.";

template(es6)

let currentTemp = 19.5;
const message = `The current temperature is ${currentTemp}\u00b0C`;

multiline(es6)

const multiline = 
`
line1
line2
`

String, Number

const result1 = 3 + '30';    // '330'
const result2 = 3 * '30';    // 90

Symbol

const RED = Symbol('The color of a sunset!');
const ORANGE = Symbol('The color of a sunset!');
RED !== ORANGE  // true; 심볼은 서로 다릅니다.

null, undefined

let currentTemp;           // undefined
const targetTemp = null;   // null
currentTemp = 19.5;        // 19.5
currentTemp = undefined;   // undefined. 할당된 값에 다시 undefined를 쓰는 권장하지 않음. 이련 경우라면 null을 사용하길 권장

Object

const sam3 = {
    name: 'Sam',
    classification: {
        kingdom: 'Anamalia',
        phylum: 'Chordata',
        class: 'Mamalia',
        family: 'Felidae',
    },
};

// 접근
sam3.classification.family;
sam3["classification"].family;
sam3.classification["family"];
sam3["classification"]["family"];

// 속성 제거
delete sam3.classification

데이터 타입 변환

To number

const numStr = "33.3";
const num = Number(numStr);    // 33.3
const a = parseInt("16 volts", 10);   // 16
const b = parseInt("3a", 16);         // 58
const c = parseFloat("15.5 kph");     // 15.5
const d = new Date();
const ts = d.valueOf();         // timestamp milliseconds

To string

const n = 33.5             // 33.5
const s = n.toString();    // "33.5"
const arr = [1, true, "hello"];
arr.toString();            // "1,true,hello";

To boolean

const n = 0;             // false value
const b1 = !!n;          // false
const b2 = Boolean(n);   // false

연산자

비교 연산자

  • == : 동등함(loose equality)
  • === : 일치함(strict equality)
const n = 5;
const s = "5";                
n === s;            // false(타입이 다름)
n !== s;            // true
n === Number(s);    // true
n !== Number(s);    // false
n == s              // true (권장하지 않음)
n != s              // false(권장하지 않음)

const a = { name: "an object" };
const b = { name: "an object" };
a === b;            // false(객체는 항상 다름)
a !== b;            // true
a == b;             // false(권장하지 않음)
a != b;             // true (권장하지 않음)

숫자 비교

let n = 0;
while(true) {
    n += 0.1;
    console.log(n);
    if (n === 0.3) break;
}
console.log(`Stopped at ${n}`);

output : 무한루프가 돈다.

let n = 0;
while(true) {
    n += 0.1;
    if (Math.abs(n - 0.3) < Number.EPSILON) break;
}
console.log(`Stopped at ${n}`);

ouput : Stopped at 0.30000000000000004

논리 연산자

거짓 같은 값

  • undefined
  • null
  • false
  • 0
  • NaN
  • ""(빈 문자열)

참 같은 값

  • 모든 객체, valueOf()메서드를 호출했을 때 false를 반환하는 객체도 참 같은 값에 속합니다.
  • 배열, 빈 배열도 참 같은 값에 속합니다. 하지만 [](빈 배열 리터럴)는 거짓 같은 값
  • 공백만 있는 문자열(" " 등)
  • 문자열 "false" !!!

boolean 연산자

Default pattern

const options = suppliedOptions || { name: "Default" };

쉼표 연산자.

let x = 0, y = 10, z;
z = (x++, y++);                      // z = x, z = y
consol.log(`${x}, ${y}, ${z}`);      // 1, 11, 10

연산자 그룹

typeof

typeof undefined       // "undefined"
typeof null            // "object" !!!
typeof {}              // "object"
typeof []              // "object" !!!
typeof true            // "boolean"
typeof 1               // "number"
typeof ""              // "string"
typeof Symbol()        // "symbol"
typeof function() {}   // "function"

해체 할당(destructuring assignment)

const obj = { b: 2, c: 3, d: 4 };

// 해체 할당
const {a, b, c} = obj;
console.log(a);    // undefined
console.log(b);    // 2
console.log(c);    // 3
console.log(d);    // ReferenceError: "d"는 정의되지 않았습니다.
const arr = [1, 2, 3, 4, 5];

let [x, y, ...rest] = arr;
console.log(x);    // 1
console.log(y);    // 2
console.log(rest); // [3, 4, 5]
let a = 5, b = 10;
[a, b] = [b, a]
console.log(a);    // 10
console.log(b);    // 5

함수

함수와 매개변수

call by value

function f(x) {
    console.log(`f 내부: x = ${x}`);
    x = 5;
    console.log(`f 내부: x = ${x} (할당 후)`);
}

let x = 3;
console.log(`f를 호출하기 전: x = ${x}`);
f(x)
console.log(`f를 호출한 다음: x = ${x}`);

결과

f를 호출하기 전: x = 3
f 내부: x = 3
f 내부: x = 5 (할당 후)
f를 호출한 다음: x = 3

call by reference

function f(o) {
    o.message = `f 안에서 수정함 (이전 값: '${o.messsage}')`;
}
let o = {
    message: "초기 값"
};
console.log(`f를 호출하기 전: o.message = "${o.message}"`);
f(o);
console.log(`f를 호출한 다음: o.message = "${o.message}"`);

결과

f를 호출하기 전: o.message = "초기값"
f를 호출한 다음: o.message = "f 안에서 수정함 (이전값: '초기 값');

매개변수 해제

객체

function getSentence({ subject, verb, object }) {
    return `${subject} ${verb} ${object}`;
}

const o = {
    subject: "I",
    verb: "love",
    object: "JavaScript",
}

getSentence(o);    // "I love JavaScript"

배열

function getSentence([ subject, verb, object ]) {
    return `${subject} ${verb} ${object}`;
}

const arr = ["I", "love", "JavaScript"];
getSentence(arr);    // "I love JavaScript"

확산연산자

function addPrefix(prefix, ...words) {
    // 나중에 더 좋은 방법을 배웁니다.
    const prefixedWords = [];
    for(let i = 0; i < words.length; i++) {
        prefixedWords[i] = prefix + words[i];
    }
    return prefixedWords;
}

addPrefix("con", "vers", "vex");    // ["converse", "convex"]

매개변수 기본값

function f(a, b = "default", c = 3) {
    return `${a} - ${b} = ${c}`;
}

f(5, 6, 7);    // "5 - 6 - 7"
f(5, 6);       // "5 - 6 - 3"
f(5);          // "5 - default - 3"
f();           // "undefined - default - 3"

객체의 프로퍼티인 함수

const o = {
    name: "Wallace",
    es5Method: function() { return "Woof!"; },
    es6Method() { return "Woof!"; },
};
Clone this wiki locally