JavaScriptにおけるvar/let/constの使い分け
2016年7月14日 by 古都こと
JavaScriptの3つある変数宣言、varとletとconstは、よく混乱を生みます。
どれも変数を宣言することに変わりはないので、違いがわかりにくいのです。
このことが初学者を混乱させている場面をたびたび目にしますし、プログラミングに慣れ親しんだ人でも役割を意識しないまま書いていることがあります。
そこでこの記事では、3つの変数宣言の役割とその使い分けについて、それぞれ簡単に紹介してみます。
Contents
1 3種類の変数宣言とその使い分け
1.1 var – 変数を宣言する
1.2 let – 変数を宣言する(ブロックスコープ)
1.3 const – 再代入不可能な変数を宣言する
1.4 つまり…
2 let vs. const
2.1 再代入はほとんど必要ない
2.2 基本的にはconstを使用する
2.3 再代入が必要になる(letを使用する)場面
3 まとめ
3種類の変数宣言とその使い分け
var – 変数を宣言する
varは、JavaScriptにおいて変数を宣言する上で、最も基本的な方法になります。
varで宣言された変数は関数スコープとなり、宣言のスコープ先頭への巻き上げ(Hoisting)が行われます。
(※変数のスコープおよび巻き上げについてはここでは解説しません。)
var x = 10;
x = 20;
もともと、JavaScriptの変数宣言にはvarしかありませんでした。
変数を宣言する唯一の方法だったのです。letとconstは新参者ということになります。
よって古いブラウザでも何の問題なく動くのがこのvarになります。
しかし、現在ではvarを使う理由はありません。関数スコープおよび巻き上げのせいで、
挙動の予測が困難になるからです。varを使うのは、古いブラウザを対象にした場合のみになります。
モダンブラウザを対象にする場合は、varの代わりにletを使用してください。
let – 変数を宣言する(ブロックスコープ)
letは比較的新しい変数宣言の方法です。varと同じく変数を宣言できますが、
letで宣言した変数はブロックスコープになります。巻き上げは行われますが、宣言前に参照するとエラーとなります。
let x = 10;
x = 20;
つまり、letは他のプログラミング言語における変数宣言とほぼ同じ動きをします。
プログラマにとって直感的で、扱いやすい挙動をするということです。
初学者にとっても、letは不思議な挙動をしないので、わかりやすいはずです。
letの用途は、varの代わりです。varでも変数は宣言できますが、letのほうが、
よりわかりやすい動きをします。モダンブラウザを対象にしたコードでは、かつてvarを使っていた場面全てで
letを使うことを推奨します。極めて特殊な処理をしていないかぎり、varをletに置き換えても問題は出ないはずです。
const – 再代入不可能な変数を宣言する
constはletと同時期に提案された変数宣言の方法です。letと同じくブロックスコープで、
巻き上げは行われるが宣言前の参照がエラーになる点も同じです。ただし、
constで宣言された変数は、再代入が不可能になります。
const x = 10;
x = 20; // 再代入はerror
注意したい点としては、他のプログラミング言語ではconstというキーワードはコンパイル時定数になることがほとんどですが、
JavaScriptでは単に再代入不可になるだけということです。つまり、JavaScriptにおけるconstは、
他のプログラミング言語におけるfinalと同じ動きをします。
constは、ほぼletと同じです。letとの違いは再代入が可能か否かだけです。constを使うのは変数への再代入が不要な場合、
あるいは再代入されたくない場合になります。
つまり…
つまり、JavaScriptにおいて、実際に変数の宣言に使用するのは、
letとconstだけということになります。varのことは忘れてしまってかまいません。
再代入が必要な場合はlet、不必要な場合はconstを使用すればいいのです。
let vs. const
さて、varは脱落しました。残る問題はletとconstの使い分けです。
再代入が必要か不必要か、どうやって見分けるのでしょうか。
それぞれどんな場面で使用することになるのでしょうか。
再代入はほとんど必要ない
実は、実際のプログラミングにおいて、再代入というのはほとんど必要ないのです。
あなたが今まで書いたプログラムを思い浮かべてください。変数を書き換える場面というのは、めったになかったはずです。
多くの変数は、一度値が代入されると、その値のまま生涯を終えます。
簡単なプログラムを想像してみましょう。円の面積を求めるプログラムです。
const pi = 3.14;
const radius = 5;
const area = pi * radius * radius;
const message = `半径${radius}の円の面積は約${area}です。`;
console.log(message);
このプログラムに再代入は一切出てきません。それもそのはずです。
まず、意味が異なる値には、それぞれ違う名前が割り当てられます。
そして計算して値が変われば、意味も変わり、別の名前が割り当てられます。
つまり、違う値が同じ名前に割り当てられることは、普通ありません。再代入は発生しないのです。
基本的にはconstを使用する
再代入が発生しない場面でletを使うのは得策ではありません。不必要な変数の再代入を許せば、
バグの発生に繋がることがあります。また、コードの読み手に「この変数は値が変わる可能性があるのか?
値の変化を追いかける必要がありそうだ」と不要な懸念を抱かせることになり、デバッグの手間も増えます。
以上のことから、変数の宣言には、基本的にはconstを使うことを推奨します。
constを使うことで、値が変化しないという保証をすることができるのです。
再代入が必要になる(letを使用する)場面
逆に再代入が必要になるのは、どんな場面なのでしょうか。再代入は、
主にイテレーション(繰り返し)処理が行われる場面で必要とされます。
代表的な例としてはfor文があります。for文ではイテレータ変数(多くの場合iという名前が使用される)の値を増減させ、
イテレーションを行います。このときに再代入が必要になります。
for(let i = 0; i < 100; i++) {
console.log(i);
}
ループ中にiの値が何度も書き換わっています。こういったときはletが必要になります。
ただしforループ内の変数宣言については、基本通りconstを使うべきです。
for(let i = 0; i < 100; i++) {
const value = i * 2;
console.log(value);
}
まとめ
varは使わず、letとconstだけを使う。
ほとんどの変数は再代入の必要が無いので、基本的にはconstを使う。
どうしても再代入が必要なときだけletを使う。
2017년 12월 10일 일요일
2017년 12월 9일 토요일
javascript memo list1
https://www.javatpoint.com/javascript-form-validation#email
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
var str="javascript";
document.write(str.charAt(2));
var stringname=new String("hello javascript string");
document.write(stringname);
object={property1:value1,property2:value2.....propertyN:valueN}
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
Current Date and Time: <span id="txt"></span>
var today=new Date();
document.getElementById('txt').innerHTML=today;
Current Date and Time: Sun Dec 10 2017 09:59:52 GMT+0900 (JST)
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
Date is: 10/12/2017
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
Current Time: 9:59:52
Events Description
onclick occurs when element is clicked.
ondblclick occurs when element is double-clicked.
onfocus occurs when an element gets focus such as button, input, textarea etc.
onblur occurs when form looses the focus from an element.
onsubmit occurs when form is submitted.
onmouseover occurs when mouse is moved over an element.
onmouseout occurs when mouse is moved out from an element (after moved over).
onmousedown occurs when mouse button is pressed over an element.
onmouseup occurs when mouse is released from an element (after mouse is pressed).
onload occurs when document, object or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel
button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
var n=new Number(value);
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
Constant Description
MIN_VALUE returns the largest minimum value.
MAX_VALUE returns the largest maximum value.
POSITIVE_INFINITY returns positive infinity, overflow value.
NEGATIVE_INFINITY returns negative infinity, overflow value.
NaN represents "Not a Number" value.
JavaScript Number Methods
Let's see the list of JavaScript number methods with description.
Methods Description
toExponential(x) displays exponential value.
toFixed(x) limits the number of digits after decimal value.
toPrecision(x) formats the number with given number of digits.
toString() converts number into string.
valueOf() coverts other type of value into number.
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
var number=document.getElementById("number").value;
var allgenders=document.getElementsByName("gender");
var totalpara=document.getElementsByTagName("p");
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
var s1="javascript from javatpoint indexof";
var n=s1.lastIndexOf("java");
document.write(n);
var s1="javascript from javatpoint indexof";
var n=s1.indexOf("from");
document.write(n);
var str="javascript";
document.write(str.charAt(2));
var stringname=new String("hello javascript string");
document.write(stringname);
object={property1:value1,property2:value2.....propertyN:valueN}
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
Current Date and Time: <span id="txt"></span>
var today=new Date();
document.getElementById('txt').innerHTML=today;
Current Date and Time: Sun Dec 10 2017 09:59:52 GMT+0900 (JST)
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
Date is: 10/12/2017
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
Current Time: 9:59:52
Events Description
onclick occurs when element is clicked.
ondblclick occurs when element is double-clicked.
onfocus occurs when an element gets focus such as button, input, textarea etc.
onblur occurs when form looses the focus from an element.
onsubmit occurs when form is submitted.
onmouseover occurs when mouse is moved over an element.
onmouseout occurs when mouse is moved out from an element (after moved over).
onmousedown occurs when mouse button is pressed over an element.
onmouseup occurs when mouse is released from an element (after mouse is pressed).
onload occurs when document, object or frameset is loaded.
onunload occurs when body or frameset is unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and cancel
button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
var n=new Number(value);
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
Constant Description
MIN_VALUE returns the largest minimum value.
MAX_VALUE returns the largest maximum value.
POSITIVE_INFINITY returns positive infinity, overflow value.
NEGATIVE_INFINITY returns negative infinity, overflow value.
NaN represents "Not a Number" value.
JavaScript Number Methods
Let's see the list of JavaScript number methods with description.
Methods Description
toExponential(x) displays exponential value.
toFixed(x) limits the number of digits after decimal value.
toPrecision(x) formats the number with given number of digits.
toString() converts number into string.
valueOf() coverts other type of value into number.
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
var number=document.getElementById("number").value;
var allgenders=document.getElementsByName("gender");
var totalpara=document.getElementsByTagName("p");
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
피드 구독하기:
글 (Atom)