おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第112弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Introduction to the ES6 Challengesの中の、
Declare a Read-Only Variable with the const Keyword
です。
さっそく見ていきましょう。
まずは本文から。
The keyword
let
is not the only new way to declare variables. In ES6, you can also declare variables using theconst
keyword.const
has all the awesome features thatlet
has, with the added bonus that variables declared usingconst
are read-only. They are a constant value, which means that once a variable is assigned withconst
, it cannot be reassigned.“use strict”;const FAV_PET = “Cats”;FAV_PET = “Dogs”; // returns errorAs you can see, trying to reassign a variable declared with
const
will throw an error. You should always name variables you don’t want to reassign using theconst
keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.Note: It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array.
Change the code so that all variables are declared using
let
orconst
. Uselet
when you want the variable to change, andconst
when you want the variable to remain constant. Also, rename variables declared withconst
to conform to common practices, meaning constants should be in all caps.
解説していきます。
今回は変数を宣言する新たなワード、constについてです。
ES6からはletだけでなくconstというものを使って新たに変数を宣言できるようになりました。
constはletとが持つすべての機能もち、さらに再割り当てできないという機能ももっています。
という事で今回はconstについて学びました。
では次回!