In programming if
and else
are conditional statements used to execute different blocks of code based on whether a certain condition is true or false.
if
is used to specify a block of code to be executed if a certain condition is true. If the condition is false, the block of code inside the if
statement is skipped and the program moves on to the next statement.
For example, if (x > 10)
means that the code inside the curly braces {}
will be executed only if the value of x
is greater than 10.
else
is used to specify a block of code to be executed if the if
condition is false. If the condition is true, the block of code inside the else
statement is skipped and the program moves on to the next statement.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
if (50 == 150) {
document.write("They are same");
} else {
alert("They are different");
}
</script>
</body>
</html>
The JavaScript code uses an if-else statement to compare if 50 is equal to 150. Since this condition is false, the code inside the else block is executed, which displays an alert message saying "They are different". The result will be an alert box with the message "They are different" when the HTML file is loaded in a web browser.
<!DOCTYPE html>
<html>
<head>
<!-- <script src="main.js"></script> -->
</head>
<body>
<script>
function same() {
document.write("Number equal to 1000");
}
function different() {
document.write("They are different");
}
var glob_var = 1000;
if (glob_var == 1000) {
same();
} else {
different();
}
</script>
</body>
</html>
This JavaScript code defines two functions named same
and different
. It then declares a global variable glob_var
and initializes it to 1000.
The code then checks if the value of glob_var
is equal to 1000 using an if
statement. If the condition is true, the same
function is called and it will print "Number equal to 1000". If the condition is false, the different
function is called and it will print "They are different".
In this case, since glob_var
is equal to 1000, the same
function will be called and it will print "Number equal to 1000".
Using functions to simplify source code is a good programming practice. It makes the code more modular and easier to read, understand, and maintain.
Functions allow you to break down your code into smaller, more manageable pieces, which can be reused in different parts of your program.
This helps to avoid repeating code and reduces the chances of errors or bugs in your code. In addition, functions can make it easier to test your code and make changes to it, since you can test and modify individual functions without affecting the rest of your program.