Home  >  Article  >  Web Front-end  >  Introduction to default parameters in ES6 (code example)

Introduction to default parameters in ES6 (code example)

不言
不言forward
2018-11-14 15:34:261687browse

This article brings you an introduction to the default parameters in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Grammar

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { 
    statements 
}

Use

function sum(a=0, b=0){
    return a+b
}
sum() // 0
sum(1) // 1
sum(1, 2) // 3

Use babelTranslate

function sum() {
    var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    return a + b;
}

Pass value detection

From babel It can be seen from the translation results that the default parameters only check two situations

  • No parameters are passed

  • Pass in undefined

function sum(a=0){
    return typeof a
}
sum() // 'number'
sum(undefined)// 'number'
sum(1) // 'number'
sum('1') // 'string'
sum(null) // 'object'
sum(false)// 'boolean'

Use before and after parameters

The previous parameter can be used as the default value of the subsequent parameter, and you can even perform some special operations on the previous parameter, such as simple addition, subtraction, multiplication and division

function sum(a=1, b=a, c=a+b){
    return [a, b, c]
}
sum() // [1, 2, 3]
sum(2)  // [2, 2, 4]
sum(2,2) // [2, 2, 4]
sum(2,2,2) // [2, 2, 2]

Default parameter call function

Assigning default parameters can even call the function. If you can call the function, it already shows that it is omnipotent~

function sum(a=1, b=(()=>4)()){
    return [a, b]
}
sum() // [1, 4]
sum(2) // [2, 4]
sum(2,2) // [2, 2]

Note: Unable to call The functions declared inside the function are used as default values ​​

function sum(a=1, b=num2()){
    function num2(){
        return 4
    }
    return [a, b]
}
sum() // Uncaught ReferenceError: num2 is not defined

Overwritten in order

The parameters are overwritten one by one in the order transmitted when called, and the form will not be skipped just because it has a default value. Assignment of parameters

function sum(a=1, b ){
    return [a, b]        
}
sum() // [1, undefined]
sum(2)// [2, undefined]
sum(1,2) //[1, 2]

Destructuring assignment default parameters

Default parameters can also be used in structures, although structures have not appeared in this series yet

function sum([x, y] = [1, 2], {z: z} = {z: 3}) { 
  return [x, y, z]; 
}
sum() // [1, 2, 3]
sum([2,4],{z: 6}) // [2, 4, 6]

The above is the detailed content of Introduction to default parameters in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete