TIL19 - JS - Scope

Peter D Lee·2020년 8월 30일
0

JavaScript

목록 보기
8/19

In JavaScript, variables have a scope in which they exist

  • global scope
  • block scope

Global Scope
Variables with global scope are those declared in the scope of the entire code, and thus callable from anywhere within the program - these variables are called global variables
> global variables are declared 'outside a function'

Block Scope
Variables with block scope are those declared inside a particular block (inside the {} notation) and thus only callable from within that block - these variables are called local variables
> local variables are declared 'inside a function'
> if called from outside the function, you will get a ReferenceError

If there are too many globally scoped variables or if the same variable names are re-used within the program, scope pollution can occur

It is best practice to not use global variables if you can - you should scope your variables tightly

0개의 댓글