Front End Web Development

Spark Boulder, Summer 2017

Session 11: Reboot

Javascript 102: variables, loops, and functions

Some post-election humor

Project 3: Coin Flipping App

For your third project, I'd like you to create an app that flips a coin and records the results!

I'd like for you to create a page with two buttons: "Flip coin" and "Reset". Every time you click the "Flip coin" button, your page writes either a "Heads" or "Tails" to the page. Every time you click the "Flip coin" button, the old results stick around, so eventually you'll have a big long list of "Heads" and "Tails".

If you click the "Reset" button, it should clear out all the previous results, and allow you to click the "Flip coin" button for more results.

I should also mention, there should be a 50/50 chance for heads/tails :)

A couple things:

More Dumb Fun Web Stuff

Cookie Clicker!

Clickers are fun (maybe?) little (sometimes) games that are written entirely in HTML, CSS, and JavaScript. No 3D graphics here - just a little manipulation of <div>s and a lot of calculation of how many insert-currency-token-here's you've got.

These get a little more complicated too! Check out these pure HTML/CSS/JavaScript clickers:

And, here's an Extra Credits episode on Skinner Boxes.

Time for some more JavaScript!

Let's bust out those text editors!

Comments

Want to "comment" something out, just like in HTML?

Use // at the beginning of a line.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

// this is a really important bit of code, right here.
console.log("This will be logged to the console! Hooray!");
// console.log("This won't be logged to the console! Oh no!");

If you're writing code that someone else is going to look at in the future, it might be beneficial to leave comments in your code, to explain what you're doing.

You can also comment out JavaScript instructions. Commented instructions won't be executed!

Variables

A variable is like a box - you can put stuff in it, you can take stuff out of it, and you can read what’s in it.

Declaring, assigning, and using variables

Let's declare a variable, and assign a value to it. Then, we'll log that variable out to the console.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

var myVariable = "Hello, World!";
console.log(myVariable);

Notice a couple things:

  1. You'll need to put the word var before your variable to tell the browser "hey, this is a variable".
  2. It might make more sense if you think about putting the thing on the right-hand side into the thing on the left-hand side. (Putting the value "Hello, World!" into myVariable)
  3. For this example, our value needs to be wrapped in quotation marks.
  4. Don't forget to end with a semicolon!

What happens if we don't declare our variable? (e.g., if we forgot to include the first line, and just tried to log myVariable?)

Overwriting/assigning new values to variables

Variables can only hold one thing at a time - if you want to put something else in the variable, it overwrites whatever's already in there.

Let's declare another variable, assign a value to it, log it to the console, assign another value to it, and try logging it to the console again.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

var myVariable = "Hello, World!";
console.log(myVariable);
var myVariable = "Goodbye, World!";
console.log(myVariable);

What happens if you set the value of a variable to another variable?

What can we put in variables?

Lots of things!

For the time being, we'll just have you put Strings and Numbers in variables.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

var myString = "Ken";
var myNumber = 28;

Numbers don't need quotation marks!

In the next session, we'll learn about assigning Arrays and Objects to variables.

Conditional statements

Conditional statments tell the browser to do something (or to not do something) based on if a condition is true or not.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

var person = "Ken";
var age = 28;

console.log("Hello, " + person + "! You are " + age + " years old.");

if (age < 28) {
    console.log("What a young, spry, and good-looking individual!");
} else {
    console.log("Wow. You are old. Your life is basically over.");
}

Notice here that we're "adding" three strings together to create a new string!

What other "operators" are there? What happens if we use <=, >, or == in our if statement?

What if we forgot to include the else statement, and just had that console.log("...") instead? What would be logged to the console?

There's some other statements that you can use, like else if and switch, but I'll let you discover those on your own.

Conditional Statements!

Comparison Operators!

Loops

Loops tell the browser, "do this thing n times in a row".

A basic while loop

The most basic loop is called a while loop. It uses a conditional, and executes all of the code within the curly brackets while the conditional is true.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

var age = 27;
var startingAge = 0;
while (startingAge < age) {
    console.log("Happy " + startingAge + "th Birthday!");
    startingAge = startingAge + 1;
}

A slightly more complicated for loop

There are a couple different ways to do loops, but I prefer this one:

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

for (var i = 0; i < 27; i++) {
    console.log("Happy " + i + "th Birthday!");
}

Inside the parentheses, there are three JavaScript expressions:

  1. What should be executed at the beginning of the loop
    • For this example, we declare and initialize our variable i to the number 0.
  2. A conditional statement that's evaluated at the beginning of each loop - if it evaluates to true, then run the iteration. If it evaluates to false, stop the loop.
    • For this example, we check to see if i is less than 10 every single iteration. If i is equal to or greater than 10, we stop the loop.
  3. What should be executed after every iteration of the loop.
    • For this example, we increment i by 1 every time we go through the loop.
    • i++ is a shorthand for saying i = i + 1.

Functions

A function is a set of instructions that you can tell the browser to run at any time.

We'd want to use a function anytime that we find ourselves repeating code. This is a little hard to tell initially, but you'll get much better at it as you write more code.

Splitting a big hairy spaghetti mess of code into a bunch of smaller functions improves readability, and makes it easier for us to debug and add new code. If you find yourself with some massive file that's too complex to understand, I'd recommend splitting it into functions!

There are three parts to a function - the function name, the function parameters, and the function's return statement.

Function names

Here's a function that logs Hello, World! to the console:

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

function sayHelloWorld() {
    console.log("Hello, World!");
}

We can then call our function using the function name:

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

function sayHelloWorld() {
    console.log("Hello, World!");
}

sayHelloWorld();

Function names can only contain letters and numbers - no spaces or dashes! Underscores are fine though.

Function parameters

Parameters are essentially variables that are passed into our functions! It's as if we declared a variable (named the same thing as our parameter) at the beginning of our function.

Here's a function that has a name, has one parameter, and logs out Hello, <someone>!:

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

function sayHello(someone) {
    console.log("Hello, " + someone + "!");
}

Then, we can call our function with an argument:

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

function sayHello(someone) {
    console.log("Hello, " + someone + "!");
}

sayHello("World");
sayHello("Ken");

What happens if we don't "pass in" anything to our function?

Function return statements

Sometimes we don't want the function to log anything out, and instead we want it to return a new, computed value to us. For that, we need a return statement.

This isn't so useful at the moment, but when you start re-using code, it'll become more valuable.

This function has a name, has one parameter, and returns the result.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

function createHelloString(someone) {
    return ("Hello, " + someone + "!");
}

We can then call the function, assign the result of the function to a variable, and log out the result.

<!-- index.html -->

<script src="myscript.js"></script>
// myscript.js

function createHelloString(someone) {
    return ("Hello, " + someone + "!");
}

var helloString = createHelloString("Ken");
console.log(helloString);

What happens if we just log createHelloString("Ken")?

Advanced: what happens if we just log createHelloString, no quotes or parentheses?

Advanced stuff

If you're a CS major, you might be interested in this stuff. Otherwise, you probably won't ever run into this.

Is JavaScript pass-by-value or pass-by-reference?

Both!

As a general rule of thumb, JavaScript uses pass-by-value when passing Numbers and Strings (primitive types) to a function. Otherwise, when passing Arrays and Objects to a function, it uses pass-by-reference.

More info: http://snook.ca/archives/javascript/javascript_pass

You now have all of the information you need to solve the #1 interview question for software developers, FizzBuzz!

I want you to loop through all numbers, 1 through 100.

If the number is divisible by 3, log Fizz to the console.

If the number is divisible by 5, log Buzz to the console.

If the number is divisible by both 3 and 5, log FizzBuzz to the console.

That's all I've got for today!

What questions are there?

How to be a Web Developer

  1. Look stuff up on the internet
  2. Make stuff
  3. Repeat

Excelsior! 🚀