The "use strict" Directive
It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables.
Strict Mode는 말그대로 코드가 strict mode에서 실행되어야 함을 의미함
그럼 여기서 말하는 strict mode란? 선언되지 않은 variable을 사용하면 안됨 🙅♀️
Strict mode를 사용하는 방법은 아래 코드를 코드 맨 위 상단에 적어준다.
'use strict';
Strict mode를 켠 상태에서는 이렇게 hasDriversLicense를 initialize를 안하고 사용하면 에러가 난다.
'use strict';
// let hasDriversLicense = false;
const passTest = true;
if (passTest) hasDriversLicense = true;
if (hasDriversLicense) console.log('I can drive :D');
// script.js:6 Uncaught ReferenceError: hasDriversLicense is not defined
만약 strict mode를 적용하지 않는다면?
hasDriversLicense를 initialize 하지 않고도 에러 없이 콘솔에 로그가 찍히는 걸 확인할 수 있음!
// 'use strict';
// let hasDriversLicense = false;
const passTest = true;
if (passTest) hasDriversLicense = true;
if (hasDriversLicense) console.log('I can drive :D');
// I can drive :D
'Programming > JavaScript' 카테고리의 다른 글
Arrow Functions (0) | 2022.09.03 |
---|---|
Function Declarations vs. Expressions (0) | 2022.09.03 |
Functions (0) | 2022.09.02 |
Coding Challenge #4 - tip calculator using ternary operator (0) | 2022.08.30 |
The Conditional (Ternary) Operator (0) | 2022.08.30 |