변수의 유효 범위
변수에 접근 할 수 있는 영역을 Scope라 하며 ,스코프는 3가지 종류가 있다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 스코프(scope):변수의 접근 영역
//1.전역 scope: 코드 전체 접근 가능 ,전역변수
//전역변수 1)var 를 함수 밖에 선언 2)타입을 붙히지 않은 경우(weight) 3)let을 함수 밖에서 선언
//2.함수 scope: 함수 내에서만 접근 가능,지역 변수
//지역 변수 1)1)var 를 함수 안에 선언 2)let을 함수 선언한 경우
//3.블록 scope: {} (브레이스) 내에서 접근 가능
//블록 내 변수(사실상 지역 변수) 1)브레이스 안에 let
var name ='hong'; //전역변수
weight=100; //전역 변수
let hobby="술"; //전역 변수
**//함수 스코프**
function fun(){
console.log(name);
**var age = 30; //지역 변수**
address="대전 서구 용문동" //전역변수
console.log(hobby);
let cellphone='010-3333-3333'; //지역 변수
}
fun();
//console.log(age); //Uncaught ReferenceError: age is not defined
//console.log(cellphone);////Uncaught ReferenceError: age is not defined
console.log(address);
console.log(weight);
//**블록 스코프**
{
var height = 175; //전역 변수
**let cellphone='010-3333-3333'; //지역 변수**
}
console.log(height);
//console.log(cellphone);////Uncaught ReferenceError: age is not defined
</script>
</body>
</html>
어디서든 접근 할 수 있는 영역을 말한다. 전역변수의 경우가 블록 스코프에 해당한다.
블록 또는 함수(메소드) 안에서 선언되지 않고, 외부에서 선언된다.
함수(메소드) 또는 블록 포함 모든 코드에서 사용 가능하다.
함수내에 var 을 붙히지 않은 변수도 전역 변수이다.
var name ='hong'; //전역변수
weight=100; //전역 변수
let hobby="술"; //전역 변수
//함수 스코프
function fun(){
console.log(name);
var age = 30; //지역 변수
**address="대전 서구 용문동" //전역변수**
console.log(hobby);
let cellphone='010-3333-3333'; //지역 변수
}
//블록 스코프
{
**var height = 175; //전역 변수**
let cellphone='010-3333-3333'; //지역 변수
}