If/else Statements in JavaScript
In JavaScript, if/else statements are implemented using if
and else
keywords. The if
keyword is followed by an expression, which must be enclosed in round brackets ()
. The body of the if
statement is denoted using curly braces{}
. This is also known as the scope
of the if statement. The body of the if
statement contains one or several statements which need to be evaluated under the specified condition.
In general, we have the syntax as,
SNIPPET
1if (expression){
2 statement
3}
For the odd-even number example above, if-else statements in JavaScript will be written as,
xxxxxxxxxx
var x = 5
if (x % 2 == 0){
console.log("x is even")
}
else{
console.log("x is odd")
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment