再也不用擔心 undefined。
function 的用法
如果不幫參數用一個預設值的話,再碰到一些 edge case 的時候會比較麻煩一點:
| 12
 3
 4
 5
 6
 7
 8
 
 | function repeat(str, times) {let result = ''
 for(let i=0; i<times; i++) {
 result += str
 }
 return result
 }
 console.log(repeat('a'))
 
 | 
(times 會是 undefined 所以不會進入迴圈,最後得到空字串)
加上預設值世界就不一樣了:
| 12
 3
 4
 5
 6
 7
 8
 
 | function repeat(str = '', times = 1) {let result = ''
 for(let i=0; i<times; i++) {
 result += str
 }
 return result
 }
 console.log(repeat('a'))
 
 | 
解構的用法
原來這個用法也能搭配解構來用:
| 12
 3
 4
 
 | let arr = [1, 2, 3]let [n1, n2, n3=100, n4 = 'abc'] = arr
 console.log(n3)
 console.log(n4)
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 
 | let obj = {a: 1,
 b: 2,
 c: 3
 }
 let {a, b, c=true, d='ddd'} = obj
 console.log(c)
 console.log(d)
 
 |