If, Else and Switch Conditionals in Javascript

00Comment iconComment iconComment iconComment icon

Let's continue understanding basic Javascript concepts, this time concepts that allow us to interact with the variables created

Writer image

Translated byEditorial

Writer image

Revised byEditorial

Edit Article

Conditional if and else

We use if/else Flow Controls to evaluate the conditions that are placed in the code structure. Conditions are sequences that must be evaluated as True or False.

We start by declaring that we are going to begin imposing a condition with the word IF. Then we place the condition, preferably between parentheses (). If the condition is satisfied, we will go to the result. The result must be between braces {}.

The condition is checked, using two equal signs for equality (==) and greater than (>) or less than (<) for comparisons.

Example:

| if ( condition ) {

| console.log("true");

| }

You can add else to catch all cases that are false:

| if (true) {

| console.log("true");

| } else {

| console.log("False");

| }

You can put conditionals inside one another:

| if (5>4) {

| if (3>2) {

| console.log("true");

| } else {

| console.log("true");

| }

| } else {

| console.log("False");

| }

You can put more than one if option one after another:

| var trafficLight = "yellow";

| var message;

| if (trafficLight == "green") {

| message = "You may go";

| } else if (trafficLight == "red") {

| message = "Stop";

| } else {

| message = "Attention";

| }

Union or intersection

It is also possible to have multiple comparisons using "&&" for intersection and "||" for union.

| var age = "16";

| var type;

| if (age >= 80 || age < 15) {

| type = "dependent";

| } else if (age < 18 && age >= 15) {

| type = "teenager";

| } else {

| type = "adult";

| }

Ternary if

You can make this code more compact. This is called a ternary if. It would be as follows:

| condition ? code1 : code2

See an example:

| var name;

| console.log( name ? 'Hello ' + name : 'Enter a name' );

This code has the same effect as this one:

| var name;

| if ( name ) {

| console.log("Hello " + name);

| } else {

| console.log("Enter a name");

| }

Switch

The Switch is a Javascript method that helps program various conditions. It can very well be replaced by ifs within one another, but it is clearer and nicer to use.

| authenticated = true;

| switch (authenticated) {

| case true:

| console.log("Logged-in user");

| break;

| case false:

| console.log("User not authenticated");

| }