---
description: 🚧 under construction -> previous parameters
---

# default parameter



[JS](../../..) ⟩ [object](../../obj) ⟩ [function](..) ⟩ [parameter]() ⟩ default parameter

{% hint style="success" %}
🚧

```javascript
const a = 3;     // ❗this one is NEVER referenced in h0 ~ h3 below
const obj = {a}; // { a: 3 }

// ---------------------------------------------------------------------------
// ⛔ "default value" 與 "paremeter name" 沒辦法用「同一個名字」❗
// ---------------------------------------------------------------------------
function h0({a} = {a: a}) { return a } // ⛔ ReferenceError: Cannot access 'a' before initialization
function h1({a} = {a}) { return a }    // ⛔ ReferenceError: Cannot access 'a' before initialization
function h2({a} = { }) { return a }    // ❗ a = undefined (by default)
function h3({a}      ) { return a }    // ❗ 
function h4({a=a} = {}) { return a }   // ⛔ ReferenceError: Cannot access 'a' before initialization

// this one is OK.
function g ({a} = {a: 0}) { return a } // ✅
```
{% endhint %}

{% tabs %}
{% tab title="🧨 雷區" %}
* :floppy\_disk: replit: [referencing previous parameters](https://replit.com/@pegasusroe/referencing-previous-parameters#index.js)

```javascript
const {log} = console;

const a = 3;     // ❗this one is NEVER referenced in h0 ~ h4 below
const obj = {a}; // { a: 3 }

// ---------------------------------------------------------------------------
// ⛔ "default value" 與 "paremeter name" 沒辦法用「同一個名字」❗
// ---------------------------------------------------------------------------
function h0({a} = {a: a}) { return a } // ⛔ ReferenceError: Cannot access 'a' before initialization
function h1({a} = {a}) { return a }    // ⛔ ReferenceError: Cannot access 'a' before initialization
function h2({a} = {} ) { return a }    // ❗ a = undefined (by default)
function h3({a}      ) { return a }    // ❗ 
function h4({a=a} = {}) { return a }   // ⛔ ReferenceError: Cannot access 'a' before initialization

// this one is OK.
function g ({a} = {a: 0}) { return a } // ✅

// ⭐ default value + previous parameters + object destructuring
function f1({x=1, y=x+2}={}) { return x+y }
function f2(x=1, {y=x+3}={}) { return x+y }

// ⭐ default value + previous parameters 
function f3(x=1, y=x+2) { return x+y }

// ⭐ default value
function f4(x=1, g = (t) => 2*t){ return x + g(x) }

// log
// ---------------------------------------------------------------------------
;[
    f1(),        // 4: x=1, y=3, x+y=4
    f2(),        // 5: x=1, y=4, x+y=5
    f3(),        // 4: x=1, y=3, x+y=4
    f3(2),       // 6: x=2, y=4, x+y=6
    f4(),        // 3: x=1, x + 2*x = 3
    f4(2),       // 6: x=2, x + 2*x = 6
    f4(2, (x) => x / 3),    // 2.6666666666666665: x = 2, return x + x/3

    g(),         // 0
    h2(),        // undefined❗
    h3(1),       // undefined❗
    
].forEach(x => log(x));

// ❗ log expressios that throw
// ---------------------------------------------------------------------------
[
    `f1({y: x + 5})`,  // ⛔ [ReferenceError] x is not defined
    `f2({y: x + 5})`,  // ⛔ [ReferenceError] x is not defined

    `h0()`,            // ⛔ [ReferenceError] Cannot access 'a' before initialization
    `h1()`,            // ⛔ [ReferenceError] Cannot access 'a' before initialization
    `h3()`,            // ⛔ [TypeError] Cannot destructure property 'a' of 'undefined'
    `h4()`,            // ⛔ [ReferenceError] Cannot access 'a' before initialization
    
].forEach(exprStr => {
    try { log(eval(exprStr)) } 
    catch (e) { log(`⛔ [${e.constructor.name}]`, e.message); }
});
```
{% endtab %}

{% tab title="💈範例" %}
💾 程式：[replit](https://replit.com/@pegasusroe/JS-Clock#index.js)        📗 參考：[JS.info](https://javascript.info/class-inheritance#extended-clock)

```javascript
// Clock
class Clock {

    // usage: 
    // • const clock = new Clock()
    // • const clock = new Clock({template: 'h:m:s'})
    // ⭐️ default parameter (by object destructuring)
    constructor({ template = 'h:m:s' } = {}) {
        this.template = template;
    }

    // ex: "16:43:03"
    render() {
        
        let date = new Date();
        
        let [h, m, s] = [
            date.getHours(), date.getMinutes(), date.getSeconds()
        ].map(x => `${x}`.padStart(2, '0'));

        let output = this.template
            .replace('h', h)
            .replace('m', m)
            .replace('s', s);

        console.log(output);
    }

    stop() {
        clearInterval(this.timer);
    }

    start() {
        this.render();
        this.timer = setInterval(() => this.render(), 1000);
    }
}

const clock = new Clock();
// const clock = new Clock({ template: '_:m:s' });
clock.start();
```
{% endtab %}

{% tab title="👥 相關" %}
* [initial-value](../../../variable/declare/initial-value "mention")
* [obj](../../../grammar/op/assign/destruct/obj "mention")
* [args](../../../grammar/op/assign/destruct/args "mention").
{% endtab %}

{% tab title="📗 參考" %}
* [ ] JS.info ⟩ [Destructuring assignment](https://javascript.info/destructuring-assignment)
* [ ] CSS-Tricks ⟩ [Using Default Parameters in ES6](https://css-tricks.com/using-default-parameters-es6/) ⭐️
* [ ] Medium ⟩ [Passing functions as arguments in JavaScript — tips and pitfalls](https://cmorinan.medium.com/passing-functions-as-arguments-in-javascript-tips-and-pitfalls-d29bbd4522a9)
{% endtab %}

{% tab title="🗣 討論" %}
* [Pass a JavaScript function as parameter](https://stackoverflow.com/a/13286241/5409815)
{% endtab %}
{% endtabs %}
