9/18/2018

Exercise 10



JavaScript

What is JavaScript

JavaScript is a client side programming language that is executed by the browser. It can be used to build interactive web pages that respond to user input.

Adding JavaScript to your page

You add JavaScript in a similar way that you add CSS to your page.

  • JavaScript can be placed anywhere in your HTML document
  • JavaScript is consumed and executed when the browser consumes it.

Inside a script tag


Including a reference to a external script file


    

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

Easy Outputs

You can use the following methods to easily output information onto the screen.


    <script>
        //Writes to just below the body tag.
        document.write('Hello World');
        //Displays a popup message
        alert('message');
        //Displays to your dev tool's console
        console.log('Hello World');
    </script>

Variables

JavaScript variables are used to store information for later use.

Naming Variables

  • Variable names should be unique.
  • Variable names are case sensitive.
  • The value of a variable

Declaring a Variable

You declared a variable by using the var keyword.


    var foo;
    var bar;

You can assign a value to a variable when it has been declared


    var foo  = "Hello World";

Variables can be used before they are declared. It makes the code harder to follow.

Using a variable in JavaScript



    var message  = "Hello World";

    console.log(message);


JavaScript variable types

We are going to cover the three main primitive types

Boolean

Numeric

String

Boolean

A boolean variable represents a true or false value


    var isBlack = true;
    var isBlue = false;

Booleans are incredibly simple, but we use them all over the place in code.

Numeric Values

Numeric values in JavaScript can be represented in integer or float values.


    var ten = 10;
    var pi = 3.14159265359;

String Variables

String variables are composed of text inside single or double quotes



    var myName = "jon middaugh" //Using Double Quotes;
    var yourName = 'John Doe';  //Using single quotes

    var foo = 'You'll be there tomorrow'; //Invalid
    var bar = 'You cannot do this";  //Invalid

What if I need to use an apostrophe or quote in my string?



    var phrase = "I said \"Hello!\"";

    var phrase2 = 'I\'m the best fit';


Operators

Operators allow you to take action with your variables.

Assignment Operators

  • Equals =

    var y;
    y = 1;
    console.log(y); //outputs 1
                           

More to come

Arithmetic Operators

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /

Arithmetic Examples


 var x = 1;
 var y = 2;
 var z = x + y;
 console.log(z); //Outputs 3
                           


 var a = 10 - 9;
 console.log(a); //Outputs 1


                           

 var b = 8;
 var c = 2;
 var d = b * c
 console.log(d); //Outputs 16
                           


 var e = 18 / 2;
 console.log(e);  //Outputs 9

                           

Additional Assignment Operators

  • +=
  • -=
  • *=
  • /=

Examples


 var x = 1;
 x += 2; //Equivalent of x = x + 2;
 console.log(x); //Outputs 3

 var y = 1;
 y += 2;
 y += 4;
 console.log(y); //Outputs j

                           


 var a = 10;
 a -= 9
 console.log(a); //Outputs 1


                           

 var x = 2;
 x *= 2;
 console.log(x); //Outputs 4

                           


 var e = 18 ;
 e /= 2
 console.log(e);  //Outputs 9

                           

Math Operators follow the Order of Operations

  • Parentheses
  • Exponents
  • Multiplication
  • Division
  • Addition
  • Subtraction

	var x = 3 * 4 + 15;
	console.log(x); // 27
                           

	var x = (3*4) + 15;
	console.log(x); //27
                           

	var x = 3 + 6 * (5 + 4) / 3 - 7;
	console.log(x); //14
                           

Arithmetic Operators with Strings

You can use the + to join variables together into strings


 var firstName = "jon";
 var lastName = "middaugh";
 var fullName = firstName + lastName;
 console.log(fullName); //Outputs jonmiddaugh
                           

 var firstName = "jon";
 var lastName = "middaugh";
 var fullName = firstName + " " + lastName + " " + 3;
 console.log(fullName); //Outputs jon middaugh 3
                           

More Examples


 var story = '';
 story += 'Greetings!';
 story += 'This is my story.';
 story += 'It is too long to put on one line.';
 console.log(story);
                           

More Examples


 var story = '';
 story += '

Greetings!

'; story += '

This is my story.

'; story += '

It is too long to put on one line.

'; document.write(story);

Performing Arithmetic on Strings

You can try to run additional arithmetic on string, but it will not yield useful results.


 var firstName = "jon";
 var twoFirstName = firstName * 2;
 console.log(twoFirstName);  //Outputs NaN which stands for Not A Number
                           

Comparison

JavaScript operators are used to test if a condition is true or false.

Comparison Operators

  • == and === equals
  • != and !== not equals
  • > and >= greater than and greater than or equal to
  • < and <= less than and less than or equal to

Here's the guide

Greater and Less than usage


 var x = 10;
 var y = x > 9; //true
 var z = x > 100 //false;
 var a = x >= 10 //true


                           

 var x = 10;
 var y = x < 9; //false
 var z = x < 100 //true;
 var a = x <= 10 //true
                            

Equality vs. Strict Equality

== vs. ===

!= vs. !==

== and != check value

=== and !== check value and type

Equals confusion

= is not the same as == or ===

Examples


    1 == '1';            //true
    1 === '1';           //false
    1 === 1;             //true
                           

    1 != '1';            //false
    1 !== '1';           //true
    1 !== 1;             //false


                           

    true == 'true';      //true
    true === 'true';     //false
                           

    false == 0;          //true
    false === 0;         //false
    false == ' ';        //true
    false === ' ' ;      //false

                           

Logical Operators

We can joining together multiple conditional statements by using logical operators

  • && - Stands for And
  • || - Stands for Or

Example


    var x = 10;
    var y = 20;
    var z = (x > 9 && y < 10);  //Evaluates to false
                                // x IS greater than 9, BUT y is not less than 10
    var a = (x === 10 && y===20)  //true
    var b = (x > 20 || y > 10) // True because y IS greater than 20
                                  

Questions?

Condition Statements

Conditional statements allow us to write code that is capable of performing different actions

The if statement


var x = true;
if (x === true){
//This code will be executed
}
		

var x = true;
if (x === false){ 
//This code will NOT be executed
}
		

if (x > 10 && x < 25){
//Executes if greater than 10 AND 
//less than 25
}
         

if (x === true || y > 10){
//This code will execute if x is true
//OR  y is greater than 10 
}
		

The else statement

The else statement acts as a catch all.


    var x  = true;
    if (x === false){
        //This code will NOT be executed
    } else {
        //This code will be executed
    }
         

The else if statement

else ifs are used after the if block and before the else


    var x  = 2;
    if (x === 1){
        //This code will NOT be executed
    }else if (x === 2){
        //This code will be executed
    } else {
        //This code  will not be reached
    }
         

You can have an infinite number of else if blocks.

The else if statement


    var colour  = getColor();
    if (colour === "yellow"){

    }else if (colour === "red"){

    } else {
		
    }
         

More Equals Problems


	if (x = 1){
		alert(true);   //This will always execute
	}

	

x = 1 doesn't fail so JS treats it like a true value

Questions?

Functions

Functions are blocks of code designed to execute a particular task. They help prevent code duplication.

Simple Function


    //Declaring a function
    function sayHello(){
        console.log('hello');
    }

    //Executing function
    sayHello();
        

Functions with Parameters


    //Declaring a function
    function sayHello(message){
        console.log(message);
    }

    //Executing function
    sayHello('hello');
        

    //Declaring a function
    function sayHello(message1, message2){
        console.log(message1);
        console.log(message2);
    }

    //Executing function
    sayHello('hello', 'world');
        

Functions with Return Values


    function getArea(height, width){
        return height * width;
    }
    var x = getArea(10, 10);
    console.log(x); // outputs 100;
        

Another way to Declare


    //Declaring a function
    function sayHello(message){
        console.log(message);
    }
    var sayHi = function(message){
        console.log(message);
    }

    //Executing function
    sayHello('hello');
    sayHi('Hi');
        

Questions?

New Output Method

We are going to select an element out of our HTML and update what is inside its tags.

Select the element

document . getElementById ('myID')

This searches our document object model (D.O.M.) and finds the first element that matches the id.


<script> var elm = document.getElementById('myID'); //Retrieves the proper element var elm2 = document.getElementById('myElement'); //return null </script>

We now have accessed an element. How do we modify it?

We are going to use a property inside of the object called innerHTML



     
My Text
<script> var elm = document.getElementById('myID'); console.log(elm.innerHTML); //Outputs 'My Text' elm.innerHTML = "Hello World"; //Update's the element console.log(elm.innerHTML); //Outputs 'Hello World' </script>

Exercise 10

>