IF structure in Javascript

We see how to work with the IF control structure in Javascript.

In .com now. In this article we are going to dedicate ourselves to showing how the if statement works, which is the most common structure used to make decisions in computer programs.

IF is a control structure used to make decisions. It is a conditional that is used to perform one or the other operations based on an expression. It works in the following way, first an expression is evaluated, if it gives a positive result, the actions related to the positive case are carried out.

The syntax of the IF structure is as follows.

Note: All control structures are lowercase in Javascript. Although sometimes to highlight the name of the structure we can write it in the text of the manual with uppercase letters, in the code of our scripts we always have to put it in lowercase. Otherwise we will receive an error message.

if (expression) { //actions to perform if positive //… }

Optionally, actions to be carried out can be indicated in the event that the evaluation of the sentence returns negative results.

if (expression) { //actions to perform if positive //… } else { //actions to perform if negative //… }

Let’s look at several things. To begin with, we see how with some keys they encompass the actions that we want to carry out in case the expressions are fulfilled or not. These braces must always be placed, except in the case that there is only one instruction such as actions to perform, which are optional.

Note: Although the braces to encompass the statements to be executed in both the positive and negative cases are optional when we want to execute a single statement, the recommendation is to always place them, because we will thus obtain a clearer source code. For example: if (it rains) alert(“Water falls”); It would be exactly the same as this code: if (it’s raining){ alert(“Water falls”); } Or even, the same as this other one: if (it rains) alert(“Water falls”);

However, when we use braces, the code is much clearer, because you can see at a quick glance which statements are depending on the positive case of the if. This is a detail that may not be very important now, but that will be appreciated when the program is more complex or when several programmers are in charge of touching the same code.

Another detail that is obvious is the indentation (margin) that we have placed in each of the blocks of instructions to be executed in the positive and negative cases. This indentation is totally optional, we have only done it this way so that the IF structure is understood in a more visual way. The line breaks are not necessary either and they have also been placed to make the structure better visible. We could perfectly fit the entire IF statement on the same line of code, but that won’t help make things clear.

See also  CSS Frameworks

Note: We, as well as any person with some experience in the programming area, advise that the necessary indentations and line breaks be used so that the instructions can be better understood. Perhaps the day you create a code you will be clear about what you have done and why it is so, but in a month, when you have to reread that code, you may remember less of what you did in your scripts and you will appreciate that they have a user-friendly format. that can be easily read by people. If you work as a team, these recommendations will be even more important, since it is even more difficult to read source code that other people have made.

Let’s look at some examples of IF conditionals.

if (day == “monday”) document.write (“Have a happy start to the week”)

If it is Monday, he will wish us a happy week. It won’t do anything otherwise. As in this example we only indicate an instruction for the positive case, it will not be necessary to use the braces (although it would be advisable to have them). Also look at the conditional operator that consists of two equal signs.

Now let’s see another example, a little longer.

if (credit >= price) { document.write(“you have bought the item ” + newItem) //show cart += newItem //insert the item in the shopping cart credit -= price //decrease the credit according to the price of the item } else { document.write(“you have run out of credit”) //I inform you that you are short of money window.location = “carritodelacompra.html” //I go to the cart page }

This example is a bit more complex, and also a bit fictional. What I do is check if I have credit to make a supposed purchase. To do this, I check if the credit is greater than or equal to the price of the item, if so, I report the purchase, I put the item in the cart and subtract the price from the accumulated credit. If the price of the item is higher than the money available, I will report the situation and send the browser to the page where your shopping cart is displayed.

conditional expressions

The expression to be evaluated is always placed between parentheses and is made up of variables that are combined with each other by means of conditional operators. We remember that the conditional operators related two variables and always returned a Boolean result. For example, a conditional operator is the operator “is equal” (==), which returns true if the two operands are equal or false if they are different.

See also  Compare dates in Javascript

if (age > 18) document.write(“you can view this page for adults”)

In this example we use the conditional operator “is greater” (>). In this case, it returns true if the age variable is greater than 18, which would execute the next line informing us that adult content is viewable.

Conditional expressions can be combined with logical expressions to create more complex expressions. Remember that logical expressions are those that have Booleans as operands and that return another Boolean value. They are the logical negation, logical AND, and logical OR operators.

if (battery < 0.5 && mains == 0) document.write("your laptop will turn off in seconds")

What we do is check if the battery of our supposed computer is less than 0.5 (it is almost finished) and we also check if the computer has no electrical network (it is unplugged). Then the logical operator maps them to an AND, so if it’s almost out of battery AND out of mains, I report that the computer is going to shut down.

The if structure is one of the most used in programming languages, to make decisions based on the evaluation of a statement. In the previous article and now we are going to see some slightly more advanced uses.

Nested IF statements

To make more complex conditional structures we can nest IF statements, that is, place IF structures inside other IF structures. With a single IF we can evaluate and carry out one action or another according to two possibilities, but if we have more possibilities to evaluate we must nest IFs to create the necessary code flow to decide correctly.

For example, if I want to check if one number is greater than or equal to another, I have to evaluate three different possibilities. First I can check if the two numbers are equal, if they are I have solved the problem, but if they are not equal I will still have to see which one is greater. Let’s look at this example in Javascript code.

var number1=23 var number2=63 if (number1 == number2){ document.write(“The two numbers are equal”) }else{ if (number1 > number2) { document.write(“The first number is greater than the first second”) }else{ document.write(“The first number is less than the second”) } }

The flow of the program is as we mentioned before, first it is evaluated if the two numbers are equal. If so, a message is displayed informing about it. Otherwise we already know that they are different, but we still have to find out which of the two is greater. For that, another comparison is made to know if the first is greater than the second. If this comparison gives positive results, we show a message saying that the first is greater than the second, otherwise we will indicate that the first is less than the second.

See also  HTML 5 Canvas Manual

We remark that the keys are optional in this case, since only one sentence is executed for each case. In addition, line breaks and indentations are also optional in any case and serve only to see the code in a more orderly manner. Keeping the code well structured and written in an understandable way is very important, as it will make our lives more pleasant when programming and later when we have to review the programs.

Note: In this manual I will use a notation like the one you have seen in the previous lines. I will also maintain that notation at all times. This will undoubtedly make the code with examples more quickly understandable, otherwise it would be a real pain to read. This same recipe is applicable to the codes that you have to create and the main beneficiary will be yourself and the colleagues who come to read your code.

IF operator

There is an operator that we haven’t seen yet, and it’s a more schematic way of doing some simple IFs. It comes from the C language, where very few lines of code are written and where the less we write, the more elegant we will be. This operator is a clear example of saving lines and characters when writing scripts. We’ll see it quickly, because the only reason I’m including it is so you know it exists and if you ever find it out there, you know how to identify it and how it works.

An example of using the IF operator can be seen below.

Variable = (condition) ? value1 : value2

This example not only performs a comparison of values, it also assigns a value to a variable. What it does is evaluate the condition (placed between parentheses) and if it is positive it assigns the value1 to the variable and otherwise it assigns the value2. Let’s see an example:

moment = (current_time < 12) ? "Before noon" : "After noon"

This example looks to see if the current time is less than 12. If so, it is now before noon, so it assigns “Before noon” to the variable time. If the hour is greater than or equal to 12, it is already after noon, which assigns the text “After noon” to the moment variable.

For further information, we recommend that you also see the , in the .

Loading Facebook Comments ...
Loading Disqus Comments ...