9/25/2018

Exercise 12

Assignment 2

Record Class

When the exercise gets difficult or frustrating:

  • DON'T stress, just relax
  • DO read the instructions carefully, check for typos, check for bad syntax
  • I am going to give less guidance on syntax. Figuring it out on your own will cement it in your memory.

Complex Variables

  • Arrays
  • Objects

Arrays

Arrays are used to store a collection of variables.


    var list = ["A", "B", "C", "D"];
    var list2 = [1, 10, 0, 3];
    var list3 = [1, 'ten', '0', 3];

Accessing Values in Array

You can access individual items in an array by referencing its index or position. Accessing an invalid index will return undefined.

Arrays operate off of a "zero" based index. The first position has an index of 0.


    var list = ["A", "B", "C", "D"];
    console.log(list[1]); // Outputs "B"
    console.log(list[0]); // Outputs "A"
    console.log(list[20]); // Outputs undefined

Array Methods

There are several different methods to modify an array. We're going to focus primarily on one.

  • push - Adds item to the end of an array

Array Properties

  • length - gives the count of items in the array

Array Pushing


    var x = ["a", "b", "c"];
    x.push('d');
    x.push('e');
    console.log(x);     //["a", "b", "c", "d", "e"];

JavaScript Objects

Just about everything in JavaScript is an object. Primitive variables are the only things that are not actual objects.

Objects are variables that contain many variables.


    var person = {
        firstName: "Jon",
        lastName: "Middaugh",
        age: 28,
        city: 'Johnson',
        fullName: function(){
            // return this.firstName + " " + this.lastName;
		var me = this;
		return me.firstName + " " + me.lastName;
        }
    };
    console.log(person.age) //Outputs 28;
    console.log(person.height); //Outputs undefined
    person.height = '5\' 6"';
    console.log(person.height); //Outputs 5' 6"

this

The most confusing thing in JavaScript


    var person = {
        firstName: "Jon",
        lastName "Middaugh",
        age: 28,
        city: 'Cave Springs',
        fullName: function(){
            return this.firstName + " " + this.lastName;
        };
    };



Incrementing and Decrementing

There is a very easy way to increment or decrementing a variable. You can use the ++ or -- to increment or decrement your variable by 1.


    var x = 0;
    x++  // equivalent to x = x + 1;
    console.log(x); //outputs 1
    x++
    console.log(x); //outputs 2
    x--
    console.log(x); //outputs 1

JavaScript Loops

Loops in JavaScript are used to execute the same statement multiple times.

There are two types of Loops

  • For Loops
  • While Loops

The For Loop

The for loop is most often used when dealing with collections.

Syntax

for ( statement 1; statement 2; statement 3; ){

//Code Block

}

Code Samples


    var x = [1, 2, 3, 4];
    for(var i = 0; i < x.length; i++){
        console.log(x[i]);
    }
                    

    var x = [1, 2, 3, 4];
    var i = 0;
    for(; i < x.length; i++){
        console.log(x[i]);
    }
                    

More Examples


    var names = ['Jon', 'Benjamin', 'Kristin'];
    var htmlString = "<ul>"
    for( var i = 0; i < names.length; i++){
        htmlString = htmlString + '<li>' + names[i] + '</li>'
    }
    htmlString = htmlString + '</ul>';

                        
Example of injecting html

More Examples


var names = [
    { firstname: 'John', lastname: 'Doe'},
    { firstname: 'Jane', lastname: 'Doe'}
    ];
var html = "<ul>"
for( var i = 0; i < names.length; i++){
    html = html + '<li>' + names[i].firstname + ' ' + names[i].lastname  + '</li>'
}
html = html + '</ul>';
                        

Reverse Loops


    var array = [1,2,3,4,5]
    for(var i = array.length; i>0; i--){
	
    }
    

Do and While Loops

Do and While loops are easier to read, but require more care to code properly.

A While Loop

May not execute depending on the condition.


    var i = 0;
    while(i < 25){
        console.log('i is equal to ' + i);
        i++
    }

Do Loop

Will always execute at least once.


    var i = 0;
    do{
        console.log('i is equal to ' + i);
        i++
    }
    while (i < 25);

More Examples


    var condition = false;
    var i = 0;
    while(condition == false){
        if (i > 10){
           condition = true;
        }

        i++
    }

Dangers of Do and While Loops:

Infinite Loops

JavaScript Scope

Scope is the collection of variables, objects and functions you have the ability to access.

Local Scope

Local scope is a group of items that can only be accessed within the context it is declared.



    function testing(){
        var x = 0;

        console.log(x); //logs 0
    }

    testing();

    console.log(x);  // Causes an error



Global Scope

Global scope items can be accessed by all JavaScript on the page.



    var x = 0;
    function testing(){

        console.log(x); //logs 0
    }

    testing();

    console.log(x);  //logs 0;



JavaScript Dates

Dates are variable types that represent a date and time inside of JavaScript.

Epoch Time

Dates are stored as the number of milliseconds since January 1, 1970.

Example: 4/5/2017 is roughly - 1491415025702

Example : 1/1/1777 is roughly - -6090400800000

Date Declaration

//Creates a date variable that is set to now;
var now = new Date();         
// Wed Apr 05 2017 12:57:05 GMT-0500 (Central Daylight Time);
var newDate = new Date(1491415025702); 
//Tue Aug 17 2010 12:09:36 GMT-0500 (Central Daylight Time)
var newDate = new Date("2010/08/17 12:09:36"); 
//Fri Jan 01 2010 00:00:00 GMT-0600 (Central Standard Time)
var newDate2 = new Date("1/1/2010");

More Specific Examples


new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
    

Note: Month is zero based.


//Tue Feb 01 2010 00:00:00 GMT-0600 (Central Standard Time)
var d = new Date(2010, 1) 
    

//Thu Apr 15 2010 12:04:14 GMT-0500 (Central Daylight Time)
var d = new Date(2010, 3, 15, 12, 4, 14) 
    

How do we set a specific date that we already know?

Like September 9th, 2017


var d = new Date('9/9/2017')
    

or


var d = new Date(2017, 8, 9) 
    

Getting Values

Dates have very long outputs by default, but there are methods to retrieve parts of a date.


var d = new Date(2010, 0, 1);
console.log(d.getFullYear()); //2010;

console.log(d.getDate()); // 1
  • .getMonth()
  • .getHours()
  • .getMinutes()
  • etc.

Converting Dates to Strings


var d = new Date(1993,6, 28);
console.log(d.toString());     // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
console.log(d.toDateString()); // logs Wed Jul 28 1993
console.log(d.toTimeString()); // logs 14:39:07 GMT-0600 (PDT)

Changing Date Values

We use set methods change these values.


var d = new Date(2010, 0, 1);
d.setDate(7)  // 1-7-2010;
d.setMonth(1) // 2-7-2010;
d.setHours(40); // 2-8-2010 16:00
console.log(d);
        

Comparison


var d1 = new Date(1990, 1, 1);
var d2 = new Date(2000, 1, 1);
var isNewer = d2 > d1;  //True       
         

Adding values

Let's get the current date and add a week to it.


var d1 = new Date();
var curDate = d1.getDate(); //Get the number for the current Date
var newDate = curDate + 7; //Add value to it
d1.setDate(newDate);    // Set the new date
console.log(d1); 

//Shorter
var d1 = new Date();
var newDate = d1.getDate() + 7; 
d1.setDate(newDate);    
console.log(d1); 

//Even Shorter
var d1 = new Date();
d1.setDate(d1.getDate() + 7);    
console.log(d1); 

More adding

You don't have to stick to the traditional restrictions when adding values.

You have 90 days from today for a warranty.

You don't have to calculate the number of months. JS will automatically handle the overflow.


var d1 = new Date();

d1.setDate(d1.getDate() + 90);    

console.log(d1); 

Exercise 12

Assignment 2

>