[JS] Javascript #2 Summary

3 minute read

Javascript #2 Summary


Block Scope {}

block 외부 변수정의: global scope

  • block 외부, 내부 모두 접근 가능
  • global 변수는 application 실행한 순간부터 끝날 때 까지
    항상 메모리에 탑재되기 때문에 최소한으로 사용하는 것을 권장
  • 가능하면 class, 조건문, 반복문 등에서 필요할 때만 사용
let global_variable = 3;
console.log(global_varaible);
{
    console.log(global_variable);
}

>>> 3
>>> 3 (block 내부에서도 global variable 에 접근 가능)



block 내부에 정의: block scope

  • block 내부에서만 접근 가능
{
    let inner_variable = 7;
    console.log(inner_variable);
}
console.log(inner_variable);

>>> 7
>>> Uncaught ReferenceError: inner_variable is not defined (block 외부에서 접근 불가)



Declaration

  • let

  • const

  • var (Don’t use it)



let

  • Added in ES6
  • Mutable type
let name = 'bruce';
console.log(name);
name = 'hello';
console.log(name);

>>> bruce
>>> hello



const

  • constant (상수): 값을 한번 할당하면 변경되지 않음
  • Immutable type


favor immutable data type always for a few reasons

  • security
  • thread safety
  • reduce human mistakes
const name = 'bruce';
name = 'bruce kim'

>>> Uncaught TypeError: Assignment to constant variable.



var

  • ES6 이전에 사용
  • 잘못된 코드에 대한 에러반환 안해줘서 위험부담이 크다.
    • var hoisting: 변수를 선언한 Line 에 상관없이 var 선언문을 항상 제일 위로 끌어올려주는 것
    • block scope 가 없다.
{
    console.log(a);
    var a = 7;
}
console.log(a);

>>> undefined (var hoisting 에 의해 undefined 가 반환)
>>> 7 (block scope 가 적용되지 않아 7 이 할당된 변수 a 를 호출)



Variable Types

Primitive Type

  • 더 이상 작은 단위로 나누어질 수 없는 single item

  • 메모리에 value 저장

  • Immutable data type

  • ex) number, string, boolean, null, undefined, symbol


bigInt (fairly new, don’t use it yet)

javascript 는 기본적으로 (-2**53) ~ (2**53) 까지 표현가능

  • 현재 크롬과 파이어폭스만 지원

  • 숫자끝에 n 을 붙이게 되면 bigInt 로 간주

const bigInt = 1237123981739812732198371273192371237213912937n;
console.log(`value: ${bigInt}, type: ${typeof bigInt}`);

>>> value: 1237123981739812732198371273192371237213912937, type: bigint



Special numeric values

  • infinity, -infinity, NaN
const infinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = 'not a number' / 2;

console.log(infinity);
console.log(negativeInfinity);
console.log(nAn);

>>> Infinity
>>> -Infinity
>>> NaN



boolean

  • false: 0, null, undefined, NaN, '' (empty string)

  • 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}`);

>>> value: true, type: boolean
>>> value: false, type: boolean



null

  • 텅텅비어있음, 아무것도 아님을 지정
let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);

>>> value: null, type: object



undefined

  • 선언만 되어있고, 값은 지정되어 있지 않음
let x;  // let x = undefined; 와 동일
console.log(`value: ${x}, type: ${typeof x}`);

>>> value: undefined, type: undefined



symbol

  • 고유한 식별자가 필요할 때 사용

  • 동시 다발적으로 일어날 수 있는 코드에서 우선순위를 주고싶을 때 사용

  • 식별자를 string type 을 사용할 경우 다른 모듈이나 다른 파일에서 동일한 string 을 사용할 경우 동일한 식별자로 간주

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 print (.description 을 통해 string type 으로 변환 필요)
console.log(`value: ${symbol1.description}, type: ${typeof symbol1.description}`);

>>> value: id, type: string



Object Type

  • single item 들을 여러개 묶어서 한 단위로 관리해준다.

  • Reference 를 저장하며 이 Reference 는 특정값이 저장된 여러개의 메모리 주소를 가리킨다.

  • mutable data type 이지만 object.freeze() 를 통해 immutable data type 으로 변경가능

  • box container

  • object, real-life object, data structure

const bruce = {name: 'bruce', job: 'developer'};
// bruce 는 const 로 선언되어 메모리 포인터는 잠겨있다.
// 따라서 다른 object 로 할당은 불가능하다.
// 하지만 object 내부의 name 과 job 은 다른값으로 할당가능
bruce.job = 'front_developer';



function

  • javascript 는 function 도 Data Type 중 하나이다.

  • first-class function

    • 변수에 할당가능
    • 함수의 파라미터로 전달 가능
    • 함수에서 return 가능



Dynamic Typing

dynamically typed languaged

let text = 'hello';
console.log(text.charAt(0));
console.log(`value: ${text}, type: ${text}`);

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

text = '7' + 5;
console.log(`value: ${text}, type: ${text}`);

text = '8' / '2';
console.log(`value: ${text}, type: ${text}`);
console.log(text.charAt(0));  // Error

>>> h
>>> value: hello, type: hello
>>> value: 1, type: 1
>>> value: 75, type: 75
>>> value: 4, type: 4
>>> TypeError: text.charAt is not a function

Leave a comment