JavaScript

variable, let vs var, hoisting, data types

김꼬알 2023. 6. 2. 18:34

Variable, rw(read/write 가능)

let (Mutable data type, added in ES6)

let globalName = 'global name';    // 글로벌 변수
{
  let name = SA;    // name 이라는 변수에 값을 할당
  console.log(name);
  
  name = 'hello';
  console.log(name);
}    // {}는 블록 스코프

console.log(name);    // 블록 스코프 안에서 선언했으므로 출력 불가
console.log(globalName);    // global name 이 출력됨

 

var (don't ever use this!)

  • 이전에 변수 선언을 했으나, ES6 부터는 사용하지 않음
  • 블록 스코프를 철저히 무시함
{
  age = 4;
  var age;
}
console.log(age);    // 변수를 블록 스코프 안에서 선언해도 4가 출력됨

 

var hoisting

  • 어디에 선언했는지 상관 없이 항상 제일 위로 선언을 끌어 올려주는 것

 

constant (Immutable data type), r(read only 읽기만 가능)

  • 변수를 한 번 선언하면 값이 절대 바뀌지 않음
  • 한 번 작성한 값을 다른 사람이 변경할 수 없기 때문에 보안성 유지
  • 쓰레드들이 동시에 접근해도 값이 바뀌지 않음
  • 개발자의 실수를 줄일 수 있어서 효율적임
const daysInWeek = 7;
const maxNumber = 5;

 

 

Variable types

primitive, single item(값이 바로 메모리에 저장됨): number, string, boolean, null, undefined, symbol

  • number
// 숫자는 number로 선언하지 따로 않아도 됨, 정수, 소수 구분 안해도 됨

const count = 17;    // integer
const size = 17.1;    // decimal number

 

  • number - special numeric values
1st infinity = 1 / 0;    // 값이 무한대
1st negativeInfinity = -1 / 0;    // 값이 무한대인 음수
1st nAn = 'not a number' / 2;    // 숫자가 아닌 값을 연산

console.log(infinity);    // Infinity
console.log(negativeInfinity);    // -Infinity
console.log(nAn);    // NaN

 

  • string
const char = 'c';
const brendan = 'brendan';
const greeting = 'hello' + brendan;    // + 로 문자열 이어 붙이기 가능

const helloBob = `hi ${brendan}!`;    // template literals (string)

 

  • boolean
// false: 0, null, undefined, NaN, ''
// true: any other value

const canRead = true;
const test = 3 < 1;    // false

 

  • null, undefined
let nothing = null;    // 변수 nothing 에 null 로 값을 할당

let x;    // 선언은 되었지만 값을 지정해주지 않았을 때 undefined

 

  • symbol - create unique identifiers for objects
const symbol1 = Symbol('id');    // 각각의 고유한 식별자를 만들때 사용
const symbol2 = Symbol('id');
console.log(symbol1 === symbol2);   // false 가 출력됨

console.log(`value: ${symbol1.description}, type: ${symbol1.description});   // symbol을 출력할 때는 .description을 붙여줘야 함


const gSymbol1 = Symbol.for('id');    // .for 를 붙이면 string 으로 인식
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2);   // true 가 출력됨

 

object, box container(오브젝트를 가리키는 레퍼런스가 메모리에 저장됨)

  • 물건, 물체들을 모아둔 박스 형태로, single item 들을 묶어서 한 단위로 관리할 수 있게 해주는 것
const ellie = {name: 'ellie', age: 20};
ellie.age = 21;

 

function, first-class function

 

Dynamic typing: dynamically typed language

  • 자바스크립트는 타입이 런타임에서 결정되기 때문에 조심해야 함!
let text = 'hello';
console.log(text.charAt(0));    // h
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 + sting 
console/log(`value: ${text}, type: ${typeof text});    // value: 75, type: string

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