Skip to content

Latest commit

 

History

History
executable file
·
176 lines (150 loc) · 3.28 KB

4. default parameter.md

File metadata and controls

executable file
·
176 lines (150 loc) · 3.28 KB

4. default parameter (매개변수 기본값)

4-1. 소개

const f = function (x, y, z) {
  x = x ? x : 4
  y = y || 5
  if (!z) {
    z = 6
  }
  console.log(x, y, z)
}
f(1)

f(0, null)
const f = function (x, y, z) {
  x = x !== undefined ? x : 3
  y = typeof x !== "undefined" ? y : 4
  console.log(x, y)
}
f(0, null)
const f = function (a = 1, b = 2, c = 3, d = 4, e = 5, f = 6) {
  console.log(a, b, c, d, e, f)
}
f(7, 0, "", false, null)

4-2. 상세

1) undefined 혹은 누락된 파라미터에 대해서만

2) 식?

// a(1, 2, 3) 일때 벌어지는 일 
function a(a, b, c) {
  var a = 1;
  var b = 2;
  var c = 3;
}
a(1, 2, 3)

// default parameter 할당하면? let과 동일해진다. 
function a(a = 1, b = 2, c = 3) {
  // let _a = a !== undefined ? a : 1;
  // let _b = 2;
  // let _c = 3;
}
a(1, 2, 3)

// 식이 와도 동일해짐
// 앞에 들어온 인자를 활용하여 식을 쓸수도 있음
function a(a = 1, b = a + 1 , c = 3) {
  // let _a = a !== undefined ? a : 1;
  // let _b = b !== undefined ? b : a + 1;  
  // let _c = 3;
}
a(1, undefined, 3);

// let 과 동일하게 작동하기 때문에 안되는 것
function a(a = 1, b = c + 1 , c = 3) {
  // let _a = a !== undefined ? a : 1;
  // let _b = b !== undefined ? b : c + 1;  // c 를 찾을 수 없음 TDZ에 걸림  
  // let _c = 3;
}
a(1, undefined, 3);
const f = function (x = 1, y = 3 + x) {
  console.log(x, y)
}
f()
// 식이 되니까 함수 call 도 문제 없음
const getDefault = function () {
  console.log('getDefault Called.')
  return 10
}
const sum = function (x, y = getDefault()) {
  console.log(x + y)
}
sum(1, 2)
sum(1)

// 에러처리도 가능 
const notValid = function () {
  console.error('notValid Called')
}
const sum = function (x = notValid(), y = notValid()) {
  console.log(x + y)
}
sum(1, 2)
sum(1)

4) let 선언과 동일한 효과

const f = function (x = 1, y = 2 + x) {
  let z = y + 3
  x = 4
  console.log(x, y, z)
}
f()

4-1) TDZ

const multiply = function (x, y = x * 2) {
  console.log(x * y)
}
multiply(2, 3)
multiply(2)
const multiply = function (x = y * 3, y) {
  console.log(x, y)
}
multiply(2, 3)
multiply(undefined, 2)

4-2) 기본값으로 할당하고자 하는 값이 변수일 경우 주의사항

// 기본 값으로 할당하고 하는 변수와 매개변수가 달라야함 
let a = 10
let b = 20

function f (aa = a, b = b) {
  console.log(aa, b)
}

f(1, 2) // 문제없음
f(undefined, 2) // 문제없음
f(1) // 에러 Cannot access 'b' before initialization
f() // 에러	Cannot access 'b' before initialization

// 왜 문제가 생기는 걸까? 
let a = a // 일 때 실제로는 
------------------------
let a 
a = (a) //할당식은 오른쪽 피연산자부터 평가하는데 a를 평가하려고 보니까 a는 TDZ 여서 a is notdfined

// f() 일때
function f (aa = a, b = b) {
  let aa = a;
  let b = b;  //에러	annot access 'b' before initialization
}

4-3) arguments에도 영향을 줄까?

  • arguments 에 영향을 주지 않는다.
  • arguments 는 실제 인자로 전달된 것만 가진다.
const a = function(a = 1, b = 2, c = 3) {
	console.log(arguments)
	console.log(a, b, c)
}
a()
a(4)
a(4, 5)
a(4, undefined, 6)
a(4, 5, 6)