Dichiarazioni in JavaScript

Jan 24 2023
Le istruzioni JavaScript sono un blocco di codice che completa un'azione o un'attività. Per impostazione predefinita, l'interprete JavaScript esegue queste istruzioni una dopo l'altra nell'ordine in cui sono scritte.

Le istruzioni JavaScript sono un blocco di codice che completa un'azione o un'attività. Per impostazione predefinita, l'interprete JavaScript esegue queste istruzioni una dopo l'altra nell'ordine in cui sono scritte.

Proviamo a capire i diversi tipi di istruzioni in JS di seguito

1. Dichiarazioni di espressione

Le espressioni che hanno effetti collaterali sono considerate istruzioni di espressione come le istruzioni di assegnazione, l'invocazione di funzioni, gli operatori di incremento e decremento, ++ e — relativi alle istruzioni di assegnazione e gli operatori di eliminazione.

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

Una singola istruzione può contenere più di una sottoistruzione che è considerata un'istruzione composta o un blocco di istruzioni in JS. Le righe seguenti fungono da singola istruzione

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

3. Dichiarazione condizionale

Dichiarazioni che fanno sì che l'interprete JS esegua o salti altre istruzioni a seconda del valore di un'espressione come le istruzioni if ​​e switch .

3.1 If Statement
l'istruzione di controllo fondamentale che consente a JS di prendere decisioni ed eseguire istruzioni condizionalmente.

//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 Istruzione switch
Quando il valore della stessa espressione può essere utilizzato per prendere una decisione tra più di 2 scelte per tali casi, JS fornisce un'istruzione 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. Dichiarazione dei cicli

Dichiarazioni che eseguono ripetutamente altre istruzioni, come while e for.

4.1 Ciclo while
L'interprete prima valuta l' espressione . Se il valore dell'espressione è falso, l'interprete salta l' istruzione che funge da corpo del ciclo e passa all'istruzione successiva nel programma. Se invece l' espressione è veritiera, l'interprete esegue l' enunciato e lo ripete.

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

Dichiarazioni che fanno saltare l'interprete a un'altra parte del programma, come break , return e throw .

5.1 Etichettato
Qualsiasi istruzione può essere etichettata facendola precedere da un identificatore e da due punti: Etichettando un'istruzione, le dai un nome che puoi usare per fare riferimento ad essa altrove nel tuo programma.

//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
Quando viene eseguita l'istruzione continue, l'iterazione corrente del ciclo di inclusione viene terminata e inizia l'iterazione successiva.

//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
L'istruzione try/catch/finally è il meccanismo di gestione delle eccezioni di 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
}

Questi prossimi post faranno parte di una serie che discute le nozioni di base e gli argomenti avanzati su JavaScript.

Se questa storia ti è piaciuta, fai clic sul pulsante e condividila, in modo che anche gli altri possano trovarla! Inoltre, sentiti libero di lasciare un commento qui sotto.

Groww Engineering pubblica aneddoti tecnici, le ultime tecnologie e modi migliori per affrontare problemi di programmazione comuni. Puoi iscriverti qui per ricevere gli ultimi aggiornamenti.

Stiamo assumendo. Visualizza le offerte di lavoro qui .