TIL08 Javascript

shnae·2023년 10월 30일
1
post-thumbnail

서버리스, planetscale


Var의 예측 불가능성을 보완하기 위해 ES6부터 let, const 키워드가 추가되었다. var는 잘 사용하지 않는다.

let

let x = "Global X"; // 전역변수
function a() {
  let x = "Local X"; // 지역변수
  console.log(x);
}

function b() {
  console.log(x);
}

a(); 
b();

결과
Local X
Global X

  • Let을 사용하면 지역변수로 사용된다

var

var x = "Global X";

if (true) {
  var x = "If X";

  console.log("1", x);
}

console.log("2", x);

결과
1 If X
2 If X

  • 지역변수와 전역변수를 출력하길 기대하고 있었지만 예상대로 출력되지 않았다
    • 이미 초기화를 했지만, 또 선언 및 초기화를 하게 되면 새로 덮어쓰인다

const

let a = 10;

console.log(a);

const b = "abc";

console.log(b);

b = "abcd";

결과
10
abc
오류 발생

  • const 키워드는 상수를 선언할 때 사용한다
  • 값을 변경할 수 없다
const myProfile = {
  name: "ksh",
  age: 20,
  isRich: false,
};

console.log(myProfile);

myProfile.age = 30;

console.log(myProfile);

결과
{ name: 'ksh', age: 20, isRich: false }
{ name: 'ksh', age: 30, isRich: false }

  • 상수는 값을 변경할 수 없다고 했는데, 변경되었다
const myProfile = {
  name: "ksh",
  age: 20,
  isRich: false,
};

console.log(myProfile);
Object.freeze(myProfile);
myProfile.age = 30;

console.log(myProfile);

결과
{ name: 'ksh', age: 20, isRich: false }
{ name: 'ksh', age: 20, isRich: false }

  • Object.freeze()를 통해 변경할 수 없도록 설정했다

hoisting

console.log(x);
var x = "Hi!";
console.log(x);

결과
undefined
Hi!

  • 변수는 읽어드리긴 하지만 초기화되지 않았다
console.log(x);
let x = "Hi!";
console.log(x);

결과
ReferenceError: Cannot access 'x' before initialization

  • 변수는 아예 읽어드릴 수 없다

0개의 댓글