0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScript_var、let、const変数宣言違い

Last updated at Posted at 2022-08-17
  • var,let,constの違いは
    ブロックスコープ : let, const
    関数スコープ : var
    ※ブロックは{}

例:

<body>
	<button onclick="testVar()">click me</button>
	<p id="test1"></p>
	<p id="test2"></p>
	<script>
	function testVar(){
		if(true){
		   var varTest = "you are the best";
		   let letTest = "have a good night"; 
		   }
        // you are the best出力
		document.getElementById("test1").innerHTML = varTest;
        // エラー:Uncaught ReferenceError: letTest is not defined
		document.getElementById("test2").innerHTML = letTest;
	}
	</script>
</body>
  • let,constの違い
    定数宣言:const
    非定数宣言:let
    ※varも非定数宣言可能だが、より狭いスコープでは可読性高いし、バグが少ない

<body>
	<button onclick="testLet()">click me</button>
	<p id="test1"></p>
	<p id="test2"></p>
	<script>
	function testLet(){
		const constTest = "you are the best";
		let letTest = "have a good night"; 
        // have a good night出力
		document.getElementById("test1").innerHTML = letTest;
        // エラー:Uncaught TypeError: Assignment to constant variable.
		constTest = "have a fun day";
		document.getElementById("test2").innerHTML = constTest;
	}
	</script>
</body>
  • 注意:

例:

<body>
	<button onclick="testConst()">click me</button>
	<p id="test1"></p>
	<p id="test2"></p>
	<script>
	function testConst(){
		const constTest = {
 			a : "hava a fun day",
			b : 2
		}
        // hava a fun day出力
		document.getElementById("test1").innerHTML = constTest.a;
		constTest.a = "kitty is lovely";
        // kitty is lovely出力
		document.getElementById("test2").innerHTML = constTest.a;
	}
	</script>
</body>
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?