Tap for Menu

If/Else Statements

If and Else functions are very powerful in JS. This is a good time to talk about the difference between arithmetic operators and comparison operators. Arithmetic Operators let you peform math opeartions. You can see them all listed below.

Comparison operators allow you to compare to things in a funciton or an if/else statement. They are all listed below.

Now that we have learned some comparison operators, let's start with our first if/else statment! Open a new HTML document and work inside the script tag. Create a new variable called "num" and prompt the user for a number.

Every If/Else statment starts with the if statment. (Proper syntax can be seen above). In the first "if" statment we compare the number the user entered to another number. All if/else statments end with "else". Any other comparisons inbetween are listed as "else if". Make sure each statement has the proper syntax. After the comparision make sure all of the JS statements that will happen are listed inside "{" "}". If/else statements can also be used inside functions!

Arrays

Arrays allow you to list any variable values quickly. So say I want to create a new var called "name" that has several values; I can do that. Start out by declaring it as a different variable.

We use the "[]" straight brackets to define variables. Every item should be in qoutes ("") and end with a comma. You shouldn't use a comma for the last item.

I made the above example a little more complex than it needed to be! To access a value in a array call the variable followed by the number of the item. For example in this list "Jake" would be [0]. The first item of an array is zero! The example below would return "Lydia".

If we go back to my first example you see we define the same array, but then also prompt the user for a number. We then use this number to access the array! This is a good example of using vars in arrays. Note that it will only return something if "0, 1 or 2" is entered.