官术网_书友最值得收藏!

Operators and flows

JavaScript supports similar control structures to other languages in the C family. Conditional statements are written with if and else, and you can chain together the statements using else-if ladders.

var a = "some value"; 
if(a === "other value") { 
  //do something 
} else if (a === "another value") { 
  //do something 
} else { 
  //do something 
} 

Control statements can be written using while, do-while, for, and switch statements. One important thing to consider while writing conditions in JavaScript is to understand what equates to true and/or false. Any value greater or less than zero, not null, and not undefined equates to true. Strings such as 0, null, undefined, or empty strings equate to false.

Some sample examples using while, do-while, for, and switch statements are as follows:

// for loop example 
 
var myVar = 0; 
for(let i = 0; i < 100; i += 1) {  
  myVar = i; 
  console.log(myVar); // => 0 1 ... 99 
} 
 
// do while example 
var x = 0; 
do { 
  x += 1; 
  console.log(x); // => 1 2 ... 100 
} while (x < 100); 
 
// while example 
while (x > 90) { 
  x -= 1; 
  console.log(x); // => 99 98 ... 90 
} 
//switch example 
 
var x = 0; 
switch(x) { 
  case 1 :  
console.log(""one""); 
break; 
  case 2 :  
console.log("two""); 
break; 
  default: 
console.log("none"); 
 
} // => "none" 

Another important thing will be to understand the basic difference between
the comparisons using == and ===. The == comparisons should be used where
the type of variable is not your concern; and if the data type of the variables also should be compared, then you should opt for a === comparison symbol as given in the following code:

const a = '5'; 
const b = 5; 
if(a == b) { 
  //do something 
} 
if(a === b) { 
  //do something 
} 

Here in the code snippet, the first condition evaluates to true while the second doesn't. So while you code, it's always safer to depend on strict (===) equality checks as a best practice.

It's always advised to run your code through code quality tools such as JSHint before you approve them for your application. You can automate the code quality checks via task runners such as Grunt so that each time we make a change in our code, the code quality tool runs and presents if there are any potential issues with the code that has been written.
主站蜘蛛池模板: 元朗区| 汕尾市| 伊金霍洛旗| 崇礼县| 临泉县| 宜阳县| 垣曲县| 泾川县| 托克逊县| 晋城| 澜沧| 房山区| 灵丘县| 巴林右旗| 潞城市| 巴东县| 新蔡县| 黄梅县| 安福县| 东丽区| 且末县| 临朐县| 凉城县| 桂林市| 鄯善县| 诏安县| 彝良县| 郸城县| 通江县| 如东县| 林周县| 东乡族自治县| 剑川县| 中江县| 锦屏县| 平湖市| 张家界市| 望奎县| 高阳县| 平谷区| 西盟|