Instrukcje w JavaScript

Jan 24 2023
Instrukcje JavaScript to blok kodu, który wykonuje jakąś akcję lub zadanie. Domyślnie interpreter JavaScript wykonuje te instrukcje jedna po drugiej w kolejności, w jakiej zostały zapisane.

Instrukcje JavaScript to blok kodu, który wykonuje jakąś akcję lub zadanie. Domyślnie interpreter JavaScript wykonuje te instrukcje jedna po drugiej w kolejności, w jakiej zostały zapisane.

Spróbujmy zrozumieć różne rodzaje instrukcji w JS poniżej

1. Wyrażenia

Wyrażenia, które mają skutki uboczne, są uważane za instrukcje wyrażeń , takie jak instrukcje przypisania, wywołania funkcji, operatory inkrementacji i dekrementacji, ++ i — związane z instrukcjami przypisania oraz operatory usuwania.

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

Pojedyncza instrukcja może zawierać więcej niż jedną instrukcję podrzędną, uważaną za instrukcję złożoną lub blok instrukcji w JS. Poniższe wiersze działają jak pojedyncza instrukcja

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

3. Oświadczenie warunkowe

Instrukcje, które sprawiają, że interpreter JS wykonuje lub pomija inne instrukcje w zależności od wartości wyrażenia, takie jak instrukcje if i switch .

3.1 if Instrukcja
podstawowa instrukcja kontrolna, która pozwala JS na podejmowanie decyzji i warunkowe wykonywanie instrukcji.

//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 Instrukcja switch
Kiedy wartość tego samego wyrażenia może być użyta do podjęcia decyzji pomiędzy więcej niż 2 możliwościami, w takich przypadkach JS udostępnia instrukcję 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. Instrukcja pętli

Instrukcje, które powtarzają inne instrukcje, takie jak while i for.

4.1 Pętla while
Interpreter najpierw ocenia wyrażenie . Jeśli wartość wyrażenia jest fałszywa, to interpreter pomija instrukcję , która służy jako treść pętli i przechodzi do następnej instrukcji w programie. Jeśli natomiast wyrażenie jest zgodne z prawdą, tłumacz wykonuje zdanie i je powtarza.

//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
}

Instrukcje, które powodują, że interpreter przechodzi do innej części programu, takie jak break , return i throw .

5.1 Oznaczone
Dowolna instrukcja może być oznaczona przez poprzedzenie jej identyfikatorem i dwukropkiem: Przez etykietowanie instrukcji nadajesz jej nazwę, której możesz użyć, aby odnieść się do niej w innym miejscu programu.

//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 Kontynuuj
Po wykonaniu instrukcji continue bieżąca iteracja otaczającej pętli zostaje zakończona i rozpoczyna się następna iteracja.

//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
Instrukcja try/catch/finally jest mechanizmem JavaScript obsługującym wyjątki.

//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
}

Kilka następnych postów będzie częścią serii omawiającej podstawy i zaawansowane tematy dotyczące JavaScript.

Jeśli podobała Ci się ta historia, kliknij przycisk i udostępnij ją, aby inni też mogli ją znaleźć! Zachęcamy również do pozostawienia komentarza poniżej.

Groww Engineering publikuje anegdoty techniczne, najnowsze technologie i lepsze sposoby rozwiązywania typowych problemów programistycznych. Możesz subskrybować tutaj , aby otrzymywać najnowsze aktualizacje.

Zatrudniamy. Zobacz oferty pracy tutaj .