JavaScript(ES2015)ã§varãletã使ãå¿ è¦ã¯ã»ã¼ç¡ã
ES2015ã§varãletã使ãå ´é¢ã¯ã»ã¨ãã©ç¡ãã®ã§ãã¾ãconstã使ããconstã ã¨ãã¡ãªå ´åã«ã¯letã使ãã
èæ¯
ES2015ã§ã¯ãå¤æ°ã宣è¨ããããã®ææ³ã¨ãã¦constã¨letãå°å ¥ãããã
const foo = 'foo'; let bar = 'bar';
constã¯åä»£å ¥ã§ããªãå¤æ°ã宣è¨ã§ãããletã¯åä»£å ¥ã§ããå¤æ°ã宣è¨ã§ããã
const foo = 'foo'; foo = 'hoge'; // ERROR let bar = 'bar'; bar = 'hoge'; // OK
ããããããvarã¨letã¯åããªã®ï¼ã£ã¦ããã¨ããã§ã¯ãªããletãconstã¯varã¨ã¯éã£ã¦ãé¢æ°ã¹ã³ã¼ããããç´°ããªãããã¯åä½ã®ã¹ã³ã¼ããæä¾ãããä¾ãã°constãletã使ãã¨ãifæãforæãªã©ã®ãããã¯ä¸ã§ã®ã¿æå¹ãªå¤æ°ã宣è¨ã§ããã
ã§ãããã¸ã§ã¯ãã«ES2015ãå°å ¥ããã¨ããããvarãããªãã¦let使ãã°ãããããªï¼ãã¨è¨ããã°ããã«letã ãã使ã人ãè¦ããããã ãã©ãå®éã«ã¯letãã»ã¨ãã©ä½¿ãå¿ è¦ãªãã¦ãå¤ãã®å ´åã¯constã§åé¡ãªããã¾ããä»äººãæ¸ããã½ã¼ã¹ã³ã¼ãã®ä¸ã§letãè¦ãã¨ããããå¾ã§åä»£å ¥ããããï¼ãã£ã¦ä¸ç¬èº«æ§ããã®ã§ãåä»£å ¥ã®å¿ è¦ããªããªãconstã使ãæ¹ãå¯èªæ§ãè¯ããªãã
ES2015ã«ãªã£ã¦å¤æ°ã®ææ³ãå¢ããããã ãã©ãéçºè ã¯ã¾ãconstã使ã£ã¦ãåä»£å ¥ãå¿ è¦ãªãletã使ã£ã¦ãletã使ããªãç¹æ®ãªäºæ ãããå ´åã®ã¿varã使ããã¨ããããã«ããã¨ããã
varã¯å¥ã«éæ¨å¥¨ã«ãªã£ãããã§ã¯ãªãã®ã§æ®éã«ä½¿ãããã ãã©ãããã¸ã§ã¯ãã§æ©æ¢°çã«varã使ãããããªãå ´åã«ã¯ãESLintã§no-varãæå¹ã«ããã
Airbnbãå ¬éãã¦ããES6ã«å¯¾å¿ããJavaScriptã³ã¼ãã£ã³ã°è¦ç´ã«ããã¦ããã¾ãconstã使ããã¨ãvarã¯é¿ãããã¨ãæ¸ããã¦ããã
追è¨: ãããã調ã¹ã¦ã¿ãã¨ãESLintã«ã¯åä»£å ¥ããªãletã«è¦åãåºãprefer-constããã£ããããå³æ ¼ã«ãããå ´åã¯ãã®prefer-constãæå¹ã«ããã
ã¾ã¨ã
ES2015ã§ã¯ãvarãletã使ãå¿ è¦ã®ããå ´é¢ã¯ããã»ã©ãªããå¤æ°ã®å®£è¨ã«ã¯constã使ããåä»£å ¥ãå¿ è¦ãªå ´åã«ã®ã¿let使ãã