Tap Forms JavaScript Scripting 101
by T. L. Ford

Section 7: Snippet If Condition

If condition

If I take out the trash, the trashcan will be empty.

Else, the trash will stink up the house.

An if statement (a statement is just another word for instruction or command) syntax looks like this:

if ( ) { }

or:

if ( ) { } else { }

The computer expects a condition inside the ( )'s and a code block (set of instructions) inside the { }'s.

You will see this written in documentation as:

if (condition) { ... } else { ... }

Trivia: Other programming languages might refer to this construct as if-then-else/elseif/elsif and may have a terminating keyword like endif/fi/end if. Different programming languages have some form of this construct and once you know what it does, you simply have to look up what that language's syntax is to know a bit about how to speak that language. (Betcha didn't guess you could learn other programming languages accidentally while doing this tutorial.)

Even more trivia: JavaScript also has a switch keyword to make a whole bunch of similar if statements less obnoxious. If you are feeling up to it, have a peek at https://www.w3schools.com/js/js_switch.asp, but you don't need to know this right now.

This is the snippet you are given:

This is an example of how you can modify it.

Writing an if statement is fairly easy and straightforward. See https://www.w3schools.com/js/js_if_else.asp.

Writing the condition for the if statement can be more challenging. The condition is something that evaluates to true or false, that is, an expression that the computer calculates to see if it is true or false.

https://www.w3schools.com/js/js_comparisons.asp

The most common error a beginner programmer makes (with conditions) is:

if (variableName = 3 ) { /* always true */ }

This stores the value of 3 in the variable variableName and then translates to if ( 3 ) { /* always true */ }. The = is for assigning a variable a value.

The correct way:

if (variableName == 3 ) { /* variableName equals 3 */ }

== is for comparing. If you are feeling particularly courageous, search the internet and learn the difference between JavaScript's comparison operators == and ===. Operators is a general term for +, -, *, /, &, |, &&, ||, +=, -=, ++, --, etc.

NEXT - Section 8: Snippet Basic Loop (and Arrays)