JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes. JavaScript also supports functional programming — functions are objects, giving functions the capacity to hold executable code and be passed around like any other object.
In Javascript, a control structure, as the term implies, refers to the flow of execution of the program. There are two possible control structures: linear and nonlinear. The linear execution (also called sequential execution) refers to the execution of the statements in the order they are listed. In comparison, the non-linear execution refers to the execution of statements regardless of the order they are listed.
Conditional Execution
In the simple case, we would like some code to be executed if a certain condition is hold but also we would like to have some code that handles the other case or cases.
If-Else
In JavaScript, basic conditional execution is created with ‘if’ and ‘else’ keywords. The ‘if’ keyword executes or skips a statement depending on the value of a Boolean expression. You can use the ‘else’ keyword, together with if, to create two separate, alternative execution paths.
var num = 5; if (num < 10) { console.log("Small"); } else { console.log("Large"); } //> "Small" var num = 150; if (num < 10) { console.log("Small"); } else { console.log("Large"); } //> "Large"
Switch-Case
There is a structure called switch which aims to express a chained if-else statement more directly in a more efficient way.
var user ="admin"; switch (user) { case "admin": console.log("Hello Admin!"); break; case "user": console.log("Hello User!"); break; default: console.log("Hello Guest!"); break; } //> "Hello Admin!"