All Products
Search
Document Center

Statement

Last Updated: Apr 08, 2021

if statement

In .js files, you can use if statements in the following formats:

  • if (expression) statement: when expression is truthy, execute statement.
  • if (expression) statement1 else statement2: when expression is truthy, execute statement1. Otherwise, execute statement2.
  • if ... else if ... else statementN With this format of if statement, a statement among statement1 ~ statementN can be selected to execute.

Syntax example:

  1. // if ...
  2. if (expression) statement;
  3. if (expression)
  4. statement;
  5. if (expression) {
  6. code block;
  7. }
  8. // if ... else
  9. if (expression) statement;
  10. else statement;
  11. if (expression)
  12. statement;
  13. else
  14. statement;
  15. if (expression) {
  16. code block;
  17. } else {
  18. code block;
  19. }
  20. // if ... else if ... else ...
  21. if (expression) {
  22. code block;
  23. } else if (expression) {
  24. code block;
  25. } else if (expression) {
  26. code block;
  27. } else {
  28. code block;
  29. }

switch statement

  • The default branch can be omitted.
  • Only variable, number, and string can follow the case keyword.

Syntax example:

  1. switch (expression) {
  2. case variable:
  3. statement;
  4. case number:
  5. statement;
  6. break;
  7. case string:
  8. statement;
  9. default:
  10. statement;
  11. }

Code sample:

  1. var exp = 10;
  2. switch ( exp ) {
  3. case "10":
  4. console.log("string 10");
  5. break;
  6. case 10:
  7. console.log("number 10");
  8. break;
  9. case exp:
  10. console.log("var exp");
  11. break;
  12. default:
  13. console.log("default");
  14. }

Output:

  1. number 10

for statement

Supports the use of break and continue keywords.

Syntax example:

  1. for (statement; statement; statement)
  2. statement;
  3. for (statement; statement; statement) {
  4. code block;
  5. }

Code sample:

  1. for (var i = 0; i < 3; ++i) {
  2. console.log(i);
  3. if( i >= 1) break;
  4. }

Output:

  1. 0
  2. 1

while statement

  • When expression is true, loop through the statement or code block.
  • Supports the use of break and continue keywords.

Syntax example:

  1. while (expression)
  2. statement;
  3. while (expression){
  4. code block;
  5. }
  6. do {
  7. code block;
  8. } while (expression)