> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/func/closure/examples/grades.md).

# closure: manage grades

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [function](/web/js/val/func.md) ⟩ [closure](/web/js/val/func/closure.md) ⟩ [example](/web/js/val/func/closure/examples.md) ⟩ manage grades

{% hint style="success" %}
[closure](/web/js/val/func/closure.md) can be used as a [function](/web/js/val/func.md) with <mark style="color:red;">**private**</mark> [property](/web/js/val/obj/prop.md) (functions/variables):exclamation:
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit：[manage grades](https://replit.com/@pegasusroe/closure-manage-grades#index.js)

```javascript
// return a function (closure) that can add new grade.
function AddGrade(records) {

    // • original grades are imported from `records`
    // • record example : { id: 14, name: "Kyle", grade: 86 }
    let grades = records.map(recordToGrade);

    // ⭐ this function is returned
    return function addGrade(grade) {
        grades.push(grade);            // add new grade
        onlyKeepTop10Grades();
        log(grades);
        return grades;
    }

    // -------- other helper functions ---------

    function recordToGrade(record) {
        return record.grade;
    }

    function onlyKeepTop10Grades() {
        grades.sort((a, b) => b - a);   // sort in place, descending
        grades = grades.slice(0, 10);   // only keep top 10 grades
    }

}

// a closure instance
const addGrade = AddGrade([
    { id:  14, name: "Kyle" , grade: 86 },
    { id:  73, name: "Suzy" , grade: 87 },
    { id: 112, name: "Frank", grade: 75 },
    // many more records ...
    { id:   6, name: "Sarah", grade: 91 }
]);

// later
addGrade(81);    // [ 91, 87, 86, 81, 75 ]
addGrade(68);    // [ 91, 87, 86, 81, 75, 68 ]
addGrade(98);    // [ 98, 91, 87, 86, 81, 75, 68 ]
```

{% endtab %}

{% tab title="📗 參考" %}

* [YDKJS: Scope & Closures (v.2)](/web/master/ref/book/you-dont-know-js-series-v.2/ydkjs-scope-and-closures-v.2.md) > Ch.7 > [Per Variable or Per Scope?](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch7.md#per-variable-or-per-scope)
  {% endtab %}
  {% endtabs %}
