Conditional statements are used to perform different actions based on different conditions.
Conditional statements
Usually when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In JavaScript, we can use the following conditional statements:
•if statement - Use this statement to execute code only if the specified condition is true
•if...else statement - Execute code when the condition is true, and execute other code when the condition is false
•if...else if...else statement - Use this statement to select one of multiple code blocks to execute
•Switch statement - Use this statement to select one of multiple code blocks to execute
If statement
The statement executes code only when the specified condition is true.
grammar
The code copy is as follows:
if (condition)
{
Only code executed when the condition is true
}
Note: Please use lowercase if. Using capital letters (IF) generates JavaScript errors!
Example
When the time is less than 20:00, a "Good day" greeting is generated:
The code copy is as follows:
if (time<20)
{
x="Good day";
}
The result of x is:
Good day
Try it yourself
Note that in this syntax, there is no ..else.. You have told the browser to execute code only if the specified condition is true.
If...else statement
Please use the if...else statement to execute code when the condition is true and other code when the condition is false.
grammar
The code copy is as follows:
if (condition)
{
Code executed when the condition is true
}
else
{
Code executed when the condition is not true
}
Example
When the time is less than 20:00, you will get the greeting "Good day", otherwise you will get the greeting "Good evening".
The code copy is as follows:
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x is:
Good day
Try it yourself
If...else if...else statement
Use the if...else if...else statement to select one of multiple code blocks to execute.
grammar
The code copy is as follows:
if (condition 1)
{
Code executed when condition 1 is true
}
else if (condition 2)
{
Code executed when condition 2 is true
}
else
{
Code executed when neither condition 1 nor condition 2 is true
}
Example
If the time is less than 10:00, the greeting "Good morning" will be sent, otherwise if the time is less than 20:00, the greeting "Good day" will be sent, otherwise the greeting "Good evening" will be sent:
The code copy is as follows:
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x is:
Good morning
In javascript, which values can be used as conditions for if
1. Boolean variable true/false
2. Numbers are not 0, not NaN/ (0 or NaN)
See the example below, don’t think that negative numbers are false.
The code copy is as follows:
var i = -1;
if(i){
alert('here');
}else{
alert('test is ok!');
}
3. Objects are not null/(null or undefined)
4. String non-empty string ("")/empty string ("")
To sum up, for strings, you don’t need to write a lot of if(str!=null && str!=undefined && str !=''), just use one sentence
The code copy is as follows:
if(!str){
//do something
}
That's it.
For non-null judgments of numbers, you should consider using the isNaN() function. NaN is not equal to any type of data, including itself, and can only be judged by isNaN(). For numeric types, if(a) statement is 0, if(a) is false, if(a) is not 0, if(a) is true
The code copy is as follows:
var b;
var a = 0;
a = a + b;
if(a){
alert('1');
}else{
alert('2');
}
if(isNaN(a)){
alert('a is NaN');
}
JavaScript tutorial: About if statement optimization method if abbreviation
UglifyJS is a tool for compressing and beautifying javascript. In its documentation, I saw several ways to optimize if statements. Although I haven't used it to do some trial tests, we can see from here that it does beautify js. Some people may think that if statements are that simple, how much can they be optimized? But look at the following ways and you may change your mind.
1. Use common ternary operators
if (foo) bar(); else baz(); ==> foo?bar():baz();
if (!foo) bar(); else baz(); ==> foo?baz():bar();
if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
You are sure to be familiar with the above use of ternary operators to optimize if statements, and maybe you use it often.
Examples given by Wulin.com:
The code copy is as follows:
<script>
var i=9
var ii=(i>8)?100:9;
alert(ii);
</script>
Output result:
100
2. Use and(&&) and or(||) operators
if (foo) bar(); ==> foo&&bar();
if (!foo) bar(); ==> foo||bar();
To be honest, I have never written code like this. I have seen this writing method when I was studying "Bird Bird's Linux Private Vegetable", but I didn't expect to implement it in js.
3. Omit curly braces {}
if (foo) return bar(); else something(); ==> {if(foo)return bar(); something()}
I am familiar with this writing method, but I suggest doing this when optimizing the code, or leaving it to UglifyJS to help you solve it. After all, if you lack one brace, the code is not readable.
Having written this, I think of a method by the father of jQuery in "Mastering JavaScript" to obtain the attributes of HTML elements.
function getAttr(el, attrName){
var attr = {'for':'htmlFor', 'class':'className'}[attrName] || attrName;
};
If we don't write this way, we may need to use two if statements to process it, and the above code is not only concise and effective, but also highly readable.
If you think about it carefully, we can find effective ways to solve the problem in many cases, but the key is whether we are careful to find a better way.
【javascript skills】Abbreviation if(x==null)
if(x==null) or if (typeof (x) == 'undefined') can be abbreviated as if(!x), and is not verified.
On the contrary, if(x) means x is not empty
Determine whether the object exists
The code copy is as follows:
if(document.form1.softurl9){
//Judge whether softurl9 exists to prevent js errors
}
The code copy is as follows:
if(document.getElementById("softurl9")){
//Judge whether softurl9 exists to prevent js errors
}