CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Javascript if statement

If Statements let you control the flow of your code. For example:

function print( a ) { $('.print').append( a + '<br>' ); } var hit_points = 0; if( hit_points < 1 ) { print('Exit dungeon'); } else { print('Keep on fighting'); }

This says, if hit points are less than 1 then the player should exit the dungeon.

If the hit points are not less than 1, keep on fighting.

Copy and paste the code into the javascript editor and run it

Change hit_points to 5. Notice the difference?
DO IT
Did it work? Try to figure it out. If it still doesn't work just click DO IT and we'll fix the code for you.

There are several different types of conditional statements:

conditionaldefinition
<less than
<=less than or equal to
>greater than
>=greater than or equal to
==equal to
!=not equal to

Let's take a look at some more examples. When a player's hit points get too low, you have add hit points with a potion like so:

var hit_points = 3; var max_hp = 10; hit_points = 3 + 20; print( hit_points );

As you can see hit points have exceeded the maximum hit point count. How can we correct this? use the print function to check the value of hit_points both before and after the following statement:

if( hit_points > max_hp ) { hit_points = max_hp; }
DO IT

=== is similar to == but the triple = operator tests for type equality. Look at the following code:

var hit_points = 10; if( hit_points === 10 ) { print('hit points are 10'); } else { print('not equal'); }

Change 10 to "10". Hit run. Notice that 10 is not === "10", so print says not equal.

Now, change === to == and examine the difference.

In the next lesson, we will learn about Javascript comments

Get the Latest Tutorial Updates
<< >>
X