JavaScript のステートメント

Jan 24 2023
JavaScript ステートメントは、何らかのアクションまたはタスクを完了するコードのブロックです。デフォルトでは、JavaScript インタープリターはこれらのステートメントを、記述された順序で次々に実行します。

JavaScript ステートメントは、何らかのアクションまたはタスクを完了するコードのブロックです。デフォルトでは、JavaScript インタープリターはこれらのステートメントを、記述された順序で次々に実行します。

以下の JS のさまざまな種類のステートメントを理解してみましょう

1. 式ステートメント

副作用のある式は、代入ステートメント、関数呼び出し、インクリメント演算子とデクリメント演算子、代入ステートメントに関連する ++ と —、および削除演算子などの式ステートメントとみなされます。

let greeting = “Hello “ + name; //assignment statement
counter ++; // increment operator which is changing a variable value
delete o.x; // deleting a property of an object O
cx = Math.cos(x);; // function invocation and assign the value to a variable

1 つのステートメントに複数のサブ ステートメントを含めることができます。サブ ステートメントは、JS の複合 ステートメントまたはステートメント ブロックと見なされます。次の行は 1 つのステートメントとして機能します

{ 
 x = Math.PI; 
 cx = Math.cos(x);
 console.log(“cos(π) = “ + cx);
}

3. 条件文

ifステートメントやswitchステートメントなど、式の値に応じて JS インタープリターに他のステートメントを実行またはスキップさせるステートメント。

3.1 if ステートメント
JS が条件付きでステートメントを決定し、実行できるようにする基本的な制御ステートメントです。

//syntax
If (expression) 
 Statement1
else 
 Statement 2

//example
if (n === 1) { //curly braces are optional in case of single statement
 console.log("You have 1 new message.");
} else {
 console.log(`You have ${n} new messages.`);
}

3.2 switch ステートメント
同じ式の値を 2 つ以上の選択肢から決定するために使用できる場合、JS は switch ステートメントを提供します。

//Syntax
switch(expression) {
 case label1: statement1; // if expression value === label1 execute statement1
 case label2: statement2; // if expression value === label2 execute statement2
 … 
 default: default_statement; // optional
}

//Example:
switch(n) {
  case 1:                        
   // Start here if n === 1.(sameness is determined by the === operator)
   // Execute code block #1.
   break;                         // stop here
  case 2:                         
    // Start here if n === 2
    // Execute code block #2.
   break;                         // Stop here
  case 3:                         
    // Start here if n === 3
    // Execute code block #3;
   break;                         // Stop here
  default:                        
    // If no case match the value of n
    // Execute code block #4.
}

4. ループステートメント

whileやforなど、他のステートメントを繰り返し実行するステートメント。

4.1 While ループ
インタプリタは最初に式を評価します。式の値が false の場合、インタプリタはループ本体として機能するステートメントをスキップし、プログラム内の次のステートメントに進みます。一方、表現が真実である場合、インタープリタはそのステートメントを実行し、それを繰り返します。

//Syntax
while (expression) { //curly braces are optional in case of single statement
  //statment or statement block
}

//Example
let count = 0;
while(count < 10) {
 console.log(count);
 count++;
}

//Syntax
do { //curly braces are optional in case of a single statement
 //statement / statement block
} 
while (expression);

//Example
let count = 0;
do {
 console.log(count);
 count++;
}
while (count < 10);

//syntax
for(initialize ; test ; increment) { //curly braces are optional in case of single statement
 //statement / statement block
}
//Example:
for(let count = 0; count < 10; count++) {
 console.log(count);
}

//Syntax with example
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let element of data) {
 sum += element;
}

// for of with map
let m = new Map([[1, "one"]]);
for(let [key, value] of m) {
 key    // => 1
 value  // => "one"
}

//syntax
for (variable in object) {
 //statement / statement block
}

//Example:
for(let p in o) { // Assign property names of o to variable p
 console.log(o[p]); // Print the value of each property
}

インタプリタをプログラムの別の部分にジャンプさせるステートメント ( Break、return、 throw など) 。

5.1 ラベル付き
ステートメントの前に識別子とコロンを付けることにより、ステートメントにラベルを付けることができます。ステートメントにラベルを付けることで、プログラム内の他の場所で参照できる名前が付けられます。

//syntax
identifier: statement

//example
mainloop: while(token !== null) {
 // Code omitted…
 continue mainloop; // Jump to the next iteration of the named loop(mainloop)
 // More code omitted…
}

5.2 Continue
continue ステートメントが実行されると、外側のループの現在の反復が終了し、次の反復が開始されます。

//example
for(let i = 0; i < data.length; i++) {
 if (!data[i]) continue; // jump to the next iteration of the loop
 total += data[i];
}

//syntax
return expression;

//Example
function square(x) { return x*x; } // A function that has a return statement
square(2) // => 4

// A generator function that yields a range of integers
function* range(from, to) {
  for(let i = from; i <= to; i++) {
    yield i;
  }
}

try/catch/finally
try/catch/finally ステートメントは、JavaScript の例外処理メカニズムです。

//syntax
try {
 //Normally, this code runs from the top of the block to the bottom
 //without problems. But it can sometimes throw an exception,
 //either directly or with a throw statement.
} catch(e) {
 // The statements in this block are executed if, and only if, the try
 // block throws an exception. These statements can use the local variable
 // e to refer to the Error object or other value that was thrown.
} finally {
 // This block contains statements that are always executed, regardless of
 // what happens in the try block. They are executed whether the try
 // block terminates:
}

//example
try {
  // Ask the user to enter a number
  let n = Number(prompt("Please enter a positive integer", ""));
  // Compute the factorial of the number, assuming the input is valid
  let f = factorial(n);
  // Display the result
  alert(n + "! = " + f);
} catch(e) {     // If the user's input was not valid, we end up here
  alert(e);  // Tell the user what the error is
}

次のいくつかの投稿は、JavaScript の基本および高度なトピックについて説明するシリーズの一部になります。

このストーリーを楽しんでいただけた場合は、 ボタンをクリックして共有してください。そうすれば、他の人も見つけることができます。また、お気軽に下記にコメントを残してください。

Groww Engineering は、技術的な逸話、最新テクノロジー、一般的なプログラミングの問題に対処するためのより良い方法を公開しています。ここから購読して最新の更新情報を入手できます。

私達は雇っています。ここで求人情報を表示します。