Variable / Hoisting / Data Type

1. Use Strict : 엄격 모드

//Use strict!
//added in ES 5
//use this for Vanilla Javascript

'use strict';

2. Variable : 변수, 변경될 수 있는 값

Variable, read & write : 메모리의 값을 읽고 쓰기가 가능

//let (added in ES6)

let name = 'ellie';
console.log(name); //ellie
name = 'hello';
console.log(name); //hello

2-1. Block scope / global scope

scope

type

Description

Block scope

{ } 블럭 안에 코드를 작성하는 변수

밖에서 접근이 되지 않음

Global scope

블록을 쓰지 않고 파일 안에 바로 정의해서 쓰는 변수

어디에서나 접근 가능

//block scope
{
    let name = 'ellie';
    console.log(name);
    name = 'hello'; 
    console.log(name);
}

//global scope
let globalName = 'global name';

2-2. var를 사용하면 안 되는 이유

  1. 선언도 하기 전에 값을 할당함

  2. 값을 할당하기 전에도 출력이 됨

  3. var hoisting?!

  4. Block scope 이 없음 → 아무리 블록 안에 변수를 선언해도 밖으로 나와버림

var hoisting (move declaration from bottom to top) 어디에 선언했는지 상관없이 항상 제일 위로 선언을 끌어올려 버리는 것

3. Constant : 상수, 한 번 할당하면 값이 절대 바뀌지 않음

Constant, read only : 값을 할당하면 읽기만 가능, 다시 다른 값을 쓰는 것이 불가능

" Favor Immutable Data type Always "

constant는 변하지 않는 값으로, 개발자들이 선호하는 immutable data type

  1. security - lock the key from virus : 해커들이 몰래 이상한 값을 넣는 것을 방지 할 수 있음

  2. thread safety : thread들 동시에 변수에 접근해서 값을 변경할 수도 있기에, constant가 이를 방지해 줌

  3. reduce human mistakes : 실수를 방지하여 편리한 유지보수가 가능

Type

Typical Variable

Kinds

Immutable Type

const

primitive types, frozen objects

Mutable Type

let

all objects by default are mutable in JS

const dayInWeek = 7;
const maxNumber = 5;

4. Variable types : 데이터 타입

Primitive Type : 더 이상 작은 단위로 나눠질 수 없는 한 가지의 작은 아이템(single item)

  • number

  • string

  • boolean

  • null

  • undefined

  • symbol

Primitive Type = value로 값이 저장됨 ex) let name → ellie

Object Type = 실제로 object를 가리키는 reference 메모리에 저장됨 ex) const ellie 객체 할당 → reference → name / age → ellie / 20

const count = 17; //integer(정수)
const size = 17.1 //decimal number(소숫점)
console.log(`value:${count}, type:${typeof count}`);
console.log(`value:${size}, type:${typeof size}`);

5. Dynamic typing (동적타이핑, Dynamically typed language)

JS는 선언 시 어떤 타입인지 선언하지 않고 프로그램이 동작할 때 할당 타입이 변경될 수 있음

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 = '7' + 5; //string + number = ? 
console.log(`value : ${text}, type : ${typeof text}`);
// value : 75, type : string\
// 5를 string type으로 변환해서 string + string이 됨

text = '8'/ '2';
console.log(`value : ${text}, type : ${typeof text}`);
// value : 4, type : number(문자를 나누었지만 숫자값으로 타입이 변경됨)

Last updated