본문 바로가기

JS

JS - variable

JS 강의 필기 + 추가

 

'use strict';

added in ES5. use this for Vanilla JS. 맨 위에 넣기.

 

Variable declaration

1. constant: read-only. immutable.

2. let: mutable. added in ES6.

problem: IE 지원 안 됨. 해결: ES6로 개발한 뒤 BARBEL에서 변환해서 배포

3. var: had used until ES5. don't ever use this.

problems

  • var hoisting(move declaration from bottom to top)
  • has no block scope

Datatype

1. Immutable: primitive types, frozen objects

2. Mutable: all objects by default are mutable in JS

favor immutable data type always because of security, thread safety, reduce human mistakes.


Scope

let globalName = 'global name';
{
    console.log(globalName);
    let name = 'phin'
}
console.log(globalName);
console.log(name);	// error

이 예제에서 { } 바깥은 global scope로, { } 바깥에서 선언된 변수는 global variable이고 { } 안팎에서 접근 가능.

{ } 안은 block scope(local scope)로 이 안에서 선언한 변수는 local variable이고 바깥에서 접근 불가.


Variable types

1. primitive(single item): number, string, boolean, null, undefined, symbol

2. object(box container)

3. function

first-class function을 지원한다는 말은 function을 변수로 할당할 수 있고 function의 param, return으로도 사용할 수 있다는 뜻

 

number

any numeric values can be declared as number type

const infinity = 1 / 0;             // Infinity로 출력됨
const negativeInfinity = -1 / 0;    // -Infinity로 출력됨
const nAn = 'not a number' / 2;     // NaN으로 출력됨

 

string

`${변수}` template literals (string). quotation mark( ' )말고 backtick( ` ) 사용

const brendan = 'brendan';
const greeting = 'hello';
console.log(`${greeting} ${brendan}`);  // hello brendan
const helloBob = `${greeting} Bob`;
console.log(`value: ${helloBob}, type: ${typeof helloBob}`); // value: hello Bob, type: string
console.log(`string literals: 
1 + 2 = ${1 + 2}`); 
// \없이도 줄바꿈, 따옴표 사용 가능

console.log('phin\'s \nbook') // 비교

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}`);  // true
console.log(`value: ${test}, type: ${typeof test}`);    // false

 

null

null은 primitive value지만 object로 나오는 오류가 있다. 참고 링크

let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);  // value: null, type: object

 

undefined

let x = undefined;
console.log(`value: ${x}, type: ${typeof x}`);  // value: undefined, type: undefined

 

symbol

template literals에 symbol을 넣을 때 반드시 .desription을 붙여야 된다.

Symbol()과는 다르게, Symbol.for() 함수는 전역 심볼 레지스트리 리스트에 심볼을 만든다. Symbol.for()는 또한 매 호출마다 새로운 심볼을 만들지 않고 현재 레지스트리에 해당 키를 가진 심볼이 있는지 먼저 검사를 한다. 있다면 그 심볼을 반환한다. 만약 키에 해당하는 심볼이 없다면 Symbol.for()는 새로운 전역 심볼을 만들 것이다. 참고 링크

const symbol1 = Symbol('id');
const symbol2 = Symbol('id');

console.log(symbol1 === symbol2);   // false
console.log(`value: ${symbol1.description}, type: ${typeof symbol1}`) // value: id, type: symbol

const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2); // true

 

object

data structure. object를 가리키는 reference가 memory에 저장됨

const ellie = { name: 'ellie', age: 20 };
ellie.age = 21;
console.log(ellie); // {name: "ellie", age: 21}

Dynamic typing: dynamically typed language

let text = 'hello';
console.log(`value: ${text}, type: ${typeof text}`);    // value: hello, type: string

console.log(text.charAt(0));    // h

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

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

text ='8' / '2';
console.log(`value: ${text}, type: ${typeof text}`);    // value: 4, type: number

text = text + 5;
console.log(`value: ${text}, type: ${typeof text}`);    // value: 9, type: number

console.log(text.charAt(0));    // text 변수의 type이 number라 에러남

'JS' 카테고리의 다른 글

JS - array  (0) 2020.12.24
JS - object  (0) 2020.12.23
JS - class  (0) 2020.12.22
JS - function  (0) 2020.12.21
JS - operator  (0) 2020.12.21