Syntax:
if(condition){
//statements;
}
If the condition is true, the statement inside the block will be executed. Note that when comparing, two equal sign (==) is not the strict that it converts the other data type if needed before comparing but three equal sign (===) is the strict mode when comparing. In strict mode, a false is not equal to zero.
================
let x=5;
function incrementingX(){
if(x){
return x++;
}
return ++x;
}
================
HTML
document.write(incrementingX())
Result:
5
Note: Inside the condition of if, x was converted to true. So, it performs the x++. It returns 5 though since it will return the value of x first before performing x = x + 1. But if you change the initialization of x = 5 to x = 0, then inside the condition of if, x will convert 0 to false. It will then skip the block of if and would proceed immediately to return ++x. So, the value will become 6 right away before returning it.
Besides zero, empty space, null, undefined and NaN are also false if you won't used a strict mode comparison (===).
Syntax: if else
if(condition){
//block 1 statements;
}else {
//block 2 statements;
}
If the condition is true, the block 1 statements will be executed but if false, block 2 statements will be executed.
=================
let x=0;
function incrementingX(){
if(x === null){
return x++;
}else {
return ++x;
}
}
================
HTML
document.write(incrementingX())
Result:
1
Note: null is null here and was not converted to zero. Since it is false, ++x was returned.
Nesting if else is also possible just like in java.
if(condition 1){ //block 1 statements;
}else if(condition 2){ //block 2 statements;
}else { //block 3 statements;
}
Conditional Operator (?)
Syntax:
let variableName = (condition) ? value1 : value2;
Conditional operator works the same way as the if else statement. The condition before the question mark operator will be evaluated. If true, variableName is equal to value1 if false variableName is equal to value2.
Also, since you can used nested in if-else statement, in conditional operator you can use the chaining method. Instead of a value, you put another conditional code to perform.
===============
let x = 0;
function incrementingX(){
x = (x === null) ? x++ : (x == 0) ? ++x : --x;
return x;
}
===============
HTML
document.write(incrementingX())
Result:
1
Note: It check first in strict mode if x is null, the condition is false. The value2 is another conditional code, it check if x is equal to 0, the condition is true. So, ++x is performed.
YOU ARE READING
Javascript Programming
RandomI am just documenting things what i learned online in here. I do express things in my own words. And I create my own program samples which serves as my practice. I do this so that when someday I would need some notes to review, I can just visit in h...
