Giter Club home page Giter Club logo

control-flow's Introduction

Mastering Control Flow

Why is this important?

"Control flow" refers to the way our computers move through a program's code. Understanding control flow allows us to trace the flow of a program based on its code. This skill is essential for programming in every language and paradigm. In particular, conditionals and loops are fundamental to understanding modern programming languages.

What are the objectives?

After this workshop, developers will be able to:

  • Identify and discuss boolean operators and truthiness
  • Use nested if statements, ternary operators, and while loops
  • Use the break keyword and switch statements.

Where should we be now?

Before this workshop, developers should already be able to:

  • create basic if else conditionals
  • create basic for loops

Thruthiness vs Falsiness

In programming something that evaluates to True is said to be truthy.

Something that evaluates to False is said to be falsy.

Most things in JavaScript are truthy. In fact, only the following become false when converted to a Boolean

  • false
  • 0
  • "" (empty string)
  • NaN
  • null
  • undefined

Everything else in JavaScript is truthy !

You can tell if something is truthy or not by prepending it with !! and running it in the console. Why!?

Exercise

What do the following expressions evaluate to in the console?

!!1

!!"Hello"

!!NaN

!!undefined

!![]

!!{}

== vs ===

In JavaScript there are two operators used for comparison, == and ===. The distinction is simple. Triple-equals checks the type while double-equals does not. Therefor:

1 == '1' // returns true but...
1 === '1' // returns false.

Question: What should programmers usually use?

JavaScript Weirdness

Most of this is quite logical. These things work in an intuitive way, as they should. However, things in JavaScript aren't always so logical...

WAT?

Nested If Statements

if statements can be nested infinitely!

Example:

if(isRaining){
  if(!hasUmbrella){
    if(!hasRainCoat){
      callTaxi();
    };
  };
};

That doesn't mean you should nest so deep! More than two layers of if / else statement is probably a bad idea.

Exercise

Can I ride?

Jimmy loves roller coasters, but there are a bunch of rules (ugh!) for riding. For starters, it costs 5 tokens. Check the following additional Requirements: For starters, it costs 5 tokens. Here's how we might code that:

var tokens = 3; // Jimmy's tokens

// Can he ride?
if ( tokens >= 5 ) {
    console.log("Step right up!");
} else {
    console.log("Sorry, you can't ride")
}

Edit the code above to check the following additional Requirements:

  • Must be at least 4ft tall.
  • Must be at least 12 years old.
  • Replace the previous rule: now riders under 12 must be accompanied by an adult.
  • If the boss isn't looking, you can sneak in!
  • Riders with a park pass get in free. Solution

Ternary Operator

You can think about the ternary operator as a concise "if-else in one line":

isRaining ? callTaxi() : keepWalking();

while loops

Endless Doughnuts

While doughnut, eat doughnut!

In while loops, the initial setup happens before the loop. The continue condition goes inside the parentheses. The update expressions happen inside the loop.

var donuts = 100; // setup:  Here we start with 100 donuts.
while (donuts > 0) { // continue condition: as long as there are still donuts...
  console.log("mmmmm... donut...");
  donuts -= 1; // update: subtract 1 from total
}

The break keyword

The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

Example:

The following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.

function testBreak(x) {
  var i = 0;

  while (i < 6) {
    if (i == 3) {
      break;
    }
    i += 1;
  }

  return i * x;
}

-from MDN

switch statements

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.

Example:

In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

switch (expr) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
    console.log("Sorry, we are out of " + expr + ".");
}

console.log("Is there anything else you'd like?");

Exercise

Refactor the following conditional using a switch statement!

if(joke.isFunny === 'yes'){
  laugh();
} else if (joke.isFunny === 'sort of'){
  chortle();
} else if (joke.isFunny === 'no'){
  stareBlankly();
};

Solution

control-flow's People

Contributors

awhit012 avatar thaddak0 avatar

Watchers

James Cloos avatar Sherri Aminshahidy avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.