JavaScript I – Day 3

Geekwise Academy

 

 

Instructors:

Corey Shuman

Aaron Lurz

 

Slack Channel:

https://geekwise-js1.slack.com

Github:

https://github.com/coreyshuman/Geekwise-JavaScript-I

Lesson plans:

http://coreyshuman.github.io/Geekwise-JavaScript-I/html/

 

 


 

Today’s Topics

·         Review topics from day 2

·         Operators

·         Truthy, Falsy

·         Intrinsic Objects

·         String Functions

·         Control Flow

o   If, else if statements

o   Switches

o   Ternary Operators

 

 


Review Assignment

Create a new script called app.js and program it to do the following:

·         Ask for your first name

·         Ask for your last name

·         Log your first name to the console

·         Alert your last name

·         Confirm (anything) and alert the result of the confirm

Include your app.js file in a blank empty html page

Execute your script

Make sure that your script functions the way it's expected too

 

 

Code Syntax

·         Readability matters!

o   camelCasing

o   CaSe SeNsItIvItY

o   Whitespace

o   Comments

 

Operators

We talked a bit about number data types in the last class, but not much about what we can do with them.

Operators allow us to take action and do something with the variables we've created.

Some operators you will see often include:

·         Mathematical

o   = (equals, assignment)

o   + (addition)

o   - (subtraction)

o   * (multiplication)

o   / (division)

o   % (modulus)

·         Shorthand Operators

o   +=

o   -=

o   *=

o   /=

o   ++

o   --

·         Comparison

o   == (loose comparison, value only)

o   === (strict comparison, value and type)

o   != (loose not equal comparison)

o   !== (strict not equal comparison)

o   < (less than)

o   > (greater than)

o   <= (less than or equal to)

o   >= (greater than or equal to)

·         Logical

o   && (and)

o   || (or)

Remember operator precedence?

1.       Parentheses

2.       Multiplication / Division

3.       Addition / Subtraction

·         parseInt(number) can be used to convert floating point numbers to integers or convert a string into an integer

o   If you try to parse a value that can’t be turned into a number, you will get NaN (not a number)

var a = 1.6;

var b = parseInt(a); // number data type 1

 

var c = "5";

var d = parseInt(c); // number data type 5

 

var e = "foo";

var f = parseInt(e); //NaN

console.log( isNaN(f) ); //true

 

Let’s Try It!

                Create a script and accompanying html file that will:

·         Prompt for a number value (provide a default of 10)

·         Prompt for a second number value (provide a default of 10)

·         Convert the prompted values into integers

·         Add the numbers together and alert the user with the result

 


Control Flow

 

Control flow simply means controlling what code actually gets executed in your program.

It's very common that your application will want to behave differently based on available data. One common scenario is a login/authentication strategy. If you build an application where you want to require the user to log in, you'll want to show a login screen if they aren't logged in, or redirect them to their home page if they are.

The kinds of control flow we are going to look at today:

·        if

·        if else

·        if else if

·        if else if else

·        switch

·        ternary

In almost all cases, the control flow will evaluate some condition, and react accordingly. This enables us to run some code, while skipping other parts.

If Statement

The most basic form of control flow are if / else statements.

   

//simple if statement

if (true) {

 

    console.log("yup");

 

}

   

Try it: Create a program that prompts the user for their age. In an if statement check if the user is younger than 18. If so then alert the user "You're a young one!"

   

//if else, if the first condition is true, run the first

//block, else run the second block

if (false) {

 

    alert("it's true");

 

} else {

 

    alert("it's false");

 

}

   

Try it: Using the code from earlier, add an if else statement alerting all those older than 18 with anything you like.

 

   

//if else if statements, the last else is our "fallback"

if (condition1) {

 

 

} else if (condition2) {

 

 

} else {

 

 

}

   

Try it: Once more, alter the code and add an else if that checks if the user is between 18 and 50. In each section alert the user with something different.

 

With if statements, it's possible to evaluate multiple conditions, and we use logical operators to do so. This lets us say, "If this AND that are true, then run this code."

·        && the and operator

·        || the or operator

 

var a = true;

var b = false;

 

//if both a AND b are true...

if (a && b) {

    console.log("both a and b are true");

} else {

    console.log("one of a or b is false");

}

 

//if a OR b is true

if (a || b) {

    console.log("one of a or b is true");

}

               

Try it: Continuing on with our exercise, alter the code to now ask for both the users age and gender. Using the two inputs set up an if else if ladder that will alert something different for each combination of variables.


Switch Statement

Another common control flow element is the switch statement. Switch will evaluate the condition and then perform a given block of code based on that value. It looks like:

 

var condition = "foo";

 

switch (condition) {

case "foo":

    alert("foo");

    break;

case "bar":

    alert("bar");

    break;

default:

    alert("wasn't foo or bar");

}

Try it: Finally, using only the age variable, refactor your code to use a switch statement instead of an if statement. 

Challenge: Use both variables with the switch statement.

Careful with Switch statements however, they can lead to some unwanted results if you forget the break keyword called "fall-through" or "pass-through". What happens when you run the switch statement and omit the break in the "foo" case?

 

var condition = "foo";

 

switch (condition) {

case "foo":

    alert("foo");

case "bar":

    alert("bar");

    break;

default:

    alert("wasn't foo or bar");

}


Ternary Operator

Ternary operators are a short hand if else type of control flow.

They use the ? and the : as the syntax.

It looks like: condition ? trueValue : falseValue;

 

var loggedIn = true;

var needsLogin = loggedIn ? false : true;

 

var age = 31;

var logout = age < 13 ? true : false;

               

Ternary operators are great for simple situations where the conditional statement can be boiled down to a yes or no answer.

Avoid nested ternary

 

var dogs = false

var cats = false;

var fish = true;

var hasPets = dogs ? true : cats ? true : fish ? true : false; // uhhh...?

               

 

Just because you can do something, doesn't mean you should...

 

Assignment

 

·         Prompt the user for something that they would like to do.

·         Make sure that the user actually types something.

·         If the user has not typed anything, alert them that they need to type something and then terminate the program.

·         If they have input a to-do item, alert the user with the item and console log it.