おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第113弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Introduction to the ES6 Challengesの中の、
Mutate an Array Declared with const
です。
さっそく見ていきましょう。
まずは本文から。
The
const
declaration has many use cases in modern JavaScript.Some developers prefer to assign all their variables using const
by default, unless they know they will need to reassign the value. Only in that case, they uselet
.However, it is important to understand that objects (including arrays and functions) assigned to a variable usingconst
are still mutable. Using theconst
declaration only prevents reassignment of the variable identifier.“use strict”;const s = [5, 6, 7];s = [1, 2, 3]; // throws error, trying to assign a consts[2] = 45; // works just as it would with an array declared with var or letconsole.log(s); // returns [5, 6, 45]As you can see, you can mutate the object
[5, 6, 7]
itself and the variables
will still point to the altered array[5, 6, 45]
. Like all arrays, the array elements ins
are mutable, but becauseconst
was used, you cannot use the variable identifiers
to point to a different array using the assignment operator.
An array is declared as
const s = [5, 7, 2]
. Change the array to[2, 5, 7]
using various element assignment.
解説していきます。
今回はconstの特徴についてです。
一部の開発者は変数の値が変化することがない限りデフォルトでconstを使い、変数の値が変化する場合はletを使う事を好みます。
しかし、constを使っても変数に割り当てられたオブジェクトの値が変更可能である事を理解する必要があります。constを使用すると、変数識別子の再割り当てのみが防止されます。
例を見てみましょう。
という事で今回はconstを使っても配列の要素は変化できるという事を学びました。
では次回!