おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第110弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Introduction to the ES6 Challengesの中の、
Explore Differences Between the var and let Keywords
です。
さっそく見ていきましょう。
まずは本文から。
One of the biggest problems with declaring variables with the
var
keyword is that you can overwrite variable declarations without an error. var camper = ‘James’;var camper = ‘David’;console.log(camper);// logs ‘David’As you can see in the code above, the
camper
variable is originally declared asJames
and then overridden to beDavid
. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.
A new keyword calledlet
was introduced in ES6 to solve this potential issue with thevar
keyword. If you were to replacevar
withlet
in the variable declarations of the code above, the result would be an error.let camper = ‘James’;let camper = ‘David’; // throws an errorThis error can be seen in the console of your browser. So unlike
var
, when usinglet
, a variable with the same name can only be declared once. Note the"use strict"
. This enables Strict Mode, which catches common coding mistakes and “unsafe” actions. For instance:“use strict”;x = 3.14; // throws an error because x is not declared
Update the code so it only uses the
let
keyword.
解説していきます。
今回はvar とletの違いについてです。
変数を宣言する際に今まではvarを使っていましたが、ES6からはletを使うことができます。
varで宣言した変数は上書きができるという欠点があります。
"use strict"
と書いてあげると一般的なコードの間違いだけでなく、安全でないコードもエラーを出すようになります。ということで今回はES6から使えるletについて学びました。
では次回!