IF – JavaScript

IF statements are ideal for when you want to control how your code flows. IF statements only evaluate either True or False and they look like this:

if ( condition_to_test ) 
{ 
     what to be done if the "condition" is true.
}

An if statement consists of the word ‘if’ in lowercase letters, followed by the condition to test inside a pair of round brackets. That condition gets evaluated to see if it is true. If it is, then the code that is in between the curly brackets will be executed. If the condition evaluates false, then that code is ignored.

Note that if you have only a single line to be executed, you can execute if conditions without curly brackets also. Still, it is recommended that you always use curly brackets to put the execution part of the if statement. That way, you will prevent a lot of mistakes and errors inshaAllah.

Try this.

let first_name = "Mohamed"; 
if ( first_name == "Mohamed" ) 
{
     document.write("First Name is " + first_name ); 
}

In the first line of the code, we are assigning the name “Mohamed” to a variable called “first_name”. So, the variable first_name now holds the name “Mohamed”.

Then we are using an IF statement to check if the variable first_name is equal to “Mohamed”. If the condition test becomes true, then the code in between curly brackets will be executed. Hence, it will display “First Name is Mohamed” in the browser.

Try this:

Add the code below to a text editor. Save and open the HTML file in a web browser.

<!doctype HTML> 
<html> 
<head> 
</head> 
<body> 
  <script> 
    var first_name = "Mohamed"; 
    if (first_name = "Mohamed"); 
    { 
      document.write("First Name is " + first_name); 
    }
  </script> 
</body> 
</html>

As you can see, we are using a plus (+) symbol to concatenate the text “First Name is ” and the variable firs_name. Like that you can concatenate any number of texts or variables.

Now try to add last name to the same code. And use “Ahmed” as the last name. So, the result should be you should have “First Name is Mohamed Ahmed” on your browser.

All the best.