Self-study/Javascript

[JavaScript] 함수/ Scope/상수

Munyoung 2023. 8. 25. 09:00

함수에서 return문을 따로 작성하지 않으면 'undefined' 출력 

파라미터에 아무값도 넣지 않으면 'undefined' 출력 

 

옵셔널 파라미터(Optional Parameter)

※ 가장 뒤쪽으로 선언해줘야지 밀리지 않음 주의!

function introduce(name, age, nationality = 'Korea'){
	console.log(`My name is ${name}.`); 
    console.log(`I am ${age} years old.`); 
    console.log(`I am from ${nationality}.`); 
}

introduce('moon', 25, 'Canada') // 값을 모두 전달한 경우 => nationality가 Canada로 뜸
introduce('Dong', 30) // 파라미터 값 생략한 경우 => nationality Korea로 뜸.

Scope : 범위 , 영역 

변수의 유효범위 

function myFunction(){
	let x = 3; 
    console.log(x); 
}

myFunction(); // 결과값: 3
console.log(x); // 결과값: undefined

{ }: 블럭문 안에 선언된 변수 => local variables(로컬변수, 지역변수) 블록안에서만 사용 가능

 

let x = 3; 

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

myFunction(); // 결과값: 3
console.log(x); // 결과값: 3

블럭문 밖에서 선언된 변수는 글로벌 변수(global variables), 어디서든 사용할 수 있음. 

 

let x = 3; // 글로벌변수 선언 후 

function myFunction(){
	let x = 5; //지역변수 선언 해줌. 
    console.log(x); 
}

myFunction(); // 결과값: 5
console.log(x); // 결과값: 3

블럭문이 있다면, 먼저 로컬변수가 있는지 확인 후, 글로벌 변수 확인. 

 

상수(constant)

변하지 않고 일정한 값을 유지하는 것. 

  • 선언할 때 const 사용. 
  • 값을 재할당하려고 했을 때, 오류 발생
  • 값을 할당하지 않고 선언하려고 할 때 오류 발생. 
  • 변수 이름을 모두 대문자로 쓰고, 두 단어는 _ (underbar)로 연결해줌