javascript use strictを使用する

javascript use strictを使用する

javascriptで、use strictを使用すると厳格モードでコードを記述することができ、エラーチェックを行うことができます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.81

use strict使い方

まずは「use strict」を使用せずに記述したコードを実行してみます。

<script>

str = "文字"; // 変数宣言なし
console.log(str); // 文字と表示される

</script>

次に同様のコードに「use strict」を使用して実行してます。

<script>

"use strict";

str = "文字";
console.log(str);

</script>

変数宣言がされていないためエラーとなります。

以下のように変数宣言を行うとエラーはなくなります。

<script>

"use strict";

let str = "文字";
console.log(str); // 文字と表示される

</script>

エラーになる構文

関数の引数名重複

関数の引数名が重複した場合は
「Uncaught SyntaxError: Duplicate parameter name not allowed in this context」となります。

'use strict';

function hoge(a, a){
}

使用しない場合はエラーにならず、以下の結果となります。

function hoge(a, a){
  console.log(a + a)
}

hoge(1,2) // 4

with構文の利用

with構文を利用した場合は、
「Uncaught SyntaxError: Strict mode code may not include a with statement」が発生します。

'use strict';

with(Math){
  console.log(max(1,2,3));
  console.log(min(1,2,3));  
}

使用しない場合はエラーにならず、以下の結果となります。

with(Math){
  console.log(max(1,2,3)); // 3
  console.log(min(1,2,3)); // 1  
}

0xでの8進数の表記

0xで8進数を表示した場合は
「Uncaught SyntaxError: Octal literals are not allowed in strict mode.」となります。

'use strict';

const num = 011;

console.log(num);

使用しない場合はエラーにならず、以下の結果となります。

const num = 011;

console.log(num); // 9

外で定義したthisの関数内での利用

外で定義したthisを関数内で利用した場合は、
「Uncaught TypeError: Cannot read property ‘num’ of undefined」となります。

'use strict';

this.num = 1;

function hoge(){ console.log(this.num) }

hoge();

使用しない場合はエラーにならず、以下の結果となります。

this.num = 1;

function hoge(){ console.log(this.num) }

hoge(); // 1

将来のキーワードとして予約されているワードを使用

将来のキーワードとして予約されている「implements,interface,let,package,private,protected,public,static,yield」を変数名として使用した場合は
「Uncaught SyntaxError: Unexpected strict mode reserved word」となります。

'use strict';

let yield = 'hoge';

console.log(yield);

使用しない場合はエラーにならず、以下の結果となります。

let yield = 'hoge';

console.log(yield); // hoge

適用範囲

関数の中で、使用すると適応範囲は関数の中のみとなります。

function hoge(){
  'use strict';
}

str = "文字"; // 変数宣言だけどエラーにはならない

複数の変数に代入

複数の変数に「=」で同じ値を代入しようとしてもエラーとなります。

'use strict';

const x = y = z = 10; // Uncaught ReferenceError: z is not defined