What is Yoda Condition & what are the Advantages?

arp14 Programming Tags: , , 2

In many programming languages, in a conditional statement, we use double equal signs (==) together to compare two values. Traditionally, the constant part goes right and the variable part goes left to the double equal signs. The single equal sign is used to assign values to variables.

Now, what if we accidentally missed a equal sign among two, in a conditional statement?

As the value assignment goes from right to the left – the constant value will be assigned to the variable on the left, the statement will be executed, we won’t even get any error. See the code below:

var = 10;

if ( var == 10 ) {
  print "Ten";
}

But, if we swap the variable and the constant like the code below, the constant is to be assigned with the value of the variable. By doing this, we’ll get the error and we’ll know that the one of the two equal sign is missing – this is the main advantage.

var = 10;

if ( 10 == var ) { // use single equal sign to get the error
  print "Ten";
}

Having problem? Just comment below.

Thanks!

2 thoughts on “What is Yoda Condition & what are the Advantages?

Leave a Reply

Note: Your email address will not be published. Required fields are marked *