Arguments
logical shortcut in ES5
tip
- The value value || defaultValue is value, whenever value is true. If the first operand of a || expression is true, the second operand is not even evaluated. This phenomenon is called a logical shortcut.
- When value is false, value || defaultValue becomes defaultValue.
let num1 = undefined
console.log(num1 || -1) // output is -1
let num2 = null
console.log(num2 || -2) // output is -2
let num3 = 0 // zero is always false
console.log(num3 || -3) // output is -3
let num4 = false // always false
console.log(num4 || -4) // output is -4
let num5 = 'hello world'
console.log(num5 || '你好') // output is hello world
ES6 default arguments in a function
s
ES6 can assign default value for function arguments
function testDefaultArgumentsFunc(name = 'someone') {
console.log(name + ' says Hi')
}
testDefaultArgumentsFunc('Jonathan') // output is Jonathan
testDefaultArgumentsFunc() // output is someone
s
arguments array is not affected by the default parameter values in any way.
function printArgs(first,second) {
console.log(first); // Jonathn
console.log(second); // Programmer
console.log(arguments); // output : [Arguments] { '0': 'Jonathn', '1': 'Programmer' }
}
printArgs('Jonathan','Programmer');