Ok, I kept my promise. You made it to the next lesson so the cardigan came off. The topics are going to have to get harder before things get serious.
Let’s talk conditional statements. Programming usually comes down to making decisions based on some kind of input. If something happens, or something is true, then perform an action based on that condition.
Let’s do an example to show how if-statements work. But first we’ll put a comment about what this if statement will be doing. “How to get my number”.
Let’s talk about comments for a hot minute. Comments are prevalent in all programming languages. They allow users to make notes about the code they are writing. The comment is ignored by the program. For human consumption only. Comments in javascript come in two varieties. Double forward slashes comment out a single line. You can create a multi-line comment like this.
Back to getting my number. Let’s set up an if statement first. We’ll start with me being really picky. So if dude is equal to Ryan Gosling then dude gets my number and email. Because, well c’mon. (beat) The stuff inside the parentheses will evaluate to a boolean value. That just means it will be true or false. If it’s true, then the stuff in the curly braces happens. The double equals sign is a comparison operator testing whether the two things are equal. Always remember in javascript that you need two equal signs to test if two things are equal. The single equal sign sets a value to a variable.
Let’s set the variable dude equal to Ryan Gosling like this. (gesture)
Then we’ll run the script and my phone number and email will be logged to the console.
But what if the dude isn’t Ryan Gosling? Well, then we could add else to the if statement like this.
If you’re not Ryan Gosling, then I’ll have to think about it.
That’s pretty picky though. To give some more guys a chance we can add the ‘else if’ statement and change the dude variable to nice guy. Then we add a condition after else-if like this:
The 'exclamation point equals' is a comparison operator that stands for Not Equal. So if dude is NOT equal to douchebag, then you get my number. But we’ll still need an else statement for guys who aren’t Ryan Gosling and are douchebags. For those guys we’ll output “I’m kind of busy for the rest of my life.
There are a bunch of operators we can use for comparing two values. If we were comparing two numbers, we could use greater than and less than operators like this.
In the next lesson, we are going to talk about arrays. You probably want to stick around.
Questions or Comments?