9/20/2018

Exercise 10

Remember, don't declare the same variable repeatedly.

Record Class

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;
        

Methods

Methods are actions that can be taken on objects.

Properties

Properties are values associated with an object.

String Properties and Methods

  • length property - returns the number of characters in the string.
  • indexOf method - returns the position (index) of the first occurrence of text in a string.
More String properties

length


    var x = "name".length;
    console.log(x);  // x equals 4
    var y = "name"
    console.log(y.length);  //


    var username = "JonMiddaugh";
    var userNameLength = username.length; //11
    var isValid = (userNameLength > 20 || userNameLength < 10);  //Returns false

indexOf


    var x = "name".indexOf("n");  ///// x = 0;
    var y = "name name name".indexOf("a");  //y = 1;
    var z = "name".indexOf("z"); // z = -1;
    var z = "name".indexOf("ame"); // z = 1;


    var email = "jonathan.middaugh@gmail.com";
    var isValidEmail = (email.indexOf('@') > -1);
    console.log(isValidEmail); //true

indexOf returns -1 if the character is not found

Number Methods

These methods are considered global methods.

  • parseInt - Attempts to convert a string to an integer
  • parseFloat - Attempts to convert a string to a float

parseInt


    parseInt("10");         // returns 10
    parseInt("10.33");      // returns 10
    parseInt("ten");        // returns NaN


    parseInt("10 11 12");   // returns 10
    parseInt("10 tacos");   // returns 10
    parseInt("tacos 10");   // returns NaN

parseFloat


    parseFloat("10");         // returns 10
    parseFloat("10.33");      // returns 10.33
    parseFloat("ten");        // returns NaN


   parseFloat("10 11 12");   // returns 10
   parseFloat("10 tacos");   // returns 10
   parseFloat("tacos 10");   // returns NaN

Is it a number?

There is a built-in method for determining if a variable is a number.


    var x = "t"
    //This doesn't work
    var isNumber = (parseInt(x) === NaN);


    var x = "t"
    if (isNaN(x)){
        //it is NOT a number
    }else{
        //It is a number
    }

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
All you ever wanted to know about arrays

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 me = {
        firstName: "Jon",
        lastName: "Middaugh",
        age: 28,
        city: 'Johnson',
        fullName: function(){
            return this.firstName + " " + this.lastName;
        }
    };
    console.log(me.age) //Outputs 60;
    console.log(me.height); //Outputs undefined
    me.height = '5\' 6"';
    console.log(me.height); //Outputs 5' 6"

W3 Schools example

this

The most confusing thing in JavaScript


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

Undefined

Undefined is the value that is given to a variable before it has a value.


    var x;
    console.log(x); //undefined     
    x = 10;
    console.log(x); //10
    

Variable hoisting.


    console.log(x); //undefined     
    var x = 10;
    console.log(x); //10
    

Is actually


    var x;
    console.log(x); //undefined     
    x = 10;
    console.log(x); //10
    

null

null is a value given to objects that are not defined.


var x = null;
if (x !== null){
    //perform logic
}    
var d = document.getElementById('fdfdfdfdf');
console.log(d); //null;

Which one do I need to use?

It can get confusing which to use, but there is an easy solution for if statements.


var d = document.getElementById('yarg');
if (d){
    //executes if not null (not found)
}
var x;
if (x){
    //executes if not undefined
}
        

getElementsByClassName

Allows you to retrieve DOM elements by their class names.

There is one major difference between this and getElementById. This one returns an HTMLCollection which is like an array.

Syntax


document.getElementsByClassName('side-bar-item')
        

//targets elements with both user-input and invalid classes
document.getElementsByClassName('user-input invalid')
        

Accessing the object.

To modify the object's properties, we need to loop through them or reference a specific index.

We haven't covered loops yet so you can just reference by the index.


var elms = document.getElementsByClassName('user-input');
var elm = elms[0];
if (elm){
    elm.innerHTML = "Yay!";
}
        

New Array Methods

  • forEach()
  • map
  • filter
  • find

.forEach()

forEach loops through each item in an array and executes a function for each item.

Syntax


    [1,2,3].forEach(function(element, index, array){
        //Code
    });

  • element - the current iterated element.
  • index - the current zero based index
  • array - the full array of items
  • Does not return anything

Example - Simple

See the Pen Array - forEach() by Jon (@Middaugh) on CodePen.

Example - More Complex

See the Pen Array - forEach() by Jon (@Middaugh) on CodePen.

.map()

map acts similar to forEach but it returns a whole new array.

Syntax


[1,2,3].map(function(element, index, array){ 
    return '';
});

  • element - the current iterated element.
  • index - the current zero based index
  • array - the full array of items
  • Returned item gets added to new array.
  • Returns new array

Example

See the Pen Array - map() by Jon (@Middaugh) on CodePen.

.filter()

Filter iterates through an array and adds the element to the new array if it returns true.

Syntax


[1,2,3].filter(function(element, index, array){
    return true | false;
});

  • element - the current iterated element.
  • index - the current zero based index
  • array - the full array of items
  • Returns new array

Example Simple

See the Pen Array - filter by Jon (@Middaugh) on CodePen.

Example Advanced

See the Pen Array - Filter Advanced by Jon (@Middaugh) on CodePen.

.find()

Acts like filter, but only returns the first one found that matches the parameters

Syntax


[1,2,3].find(function(element, index, array){
    return true | false;
});

  • element - the current iterated element.
  • index - the current zero based index
  • array - the full array of items
  • Returns first item matching parameters

Example

See the Pen Array - Filter Advanced by Jon (@Middaugh) on CodePen.

Sort

Sorting an array happens in place, it doesn't return a new array.

Code


    var food = ['taco', 'burger', 'hotdog'];
    food.sort();
    console.log(food); //['burger', 'hotdog', 'taco'];

    var nums = [20, 3, 10, 1, 2]
    nums.sort();
    console.log(nums); //[1, 10, 2, 20, 3];

Uhhh?

.sort sorts by unicode character. Everything gets converted to a string before sorting.

So how do we sort numbers?

It gets a little complicated

This is what we are going to use for now


    var nums = [20, 3, 10, 1, 2]
    nums.sort(function(a,b){
        return a - b;
    });
    console.log(nums); //[1, 2, 3, 10, 20];

Regular Expressions/RegExp

RegExp are patterns that are used to match specific characters.

We'll use them for text searching and text replacement.

RegExps are not unique to JavaScript.

Basic Patterns

Syntax: /pattern/modifiers


var pattern = /lorem/i    
      
  • lorem - looks for 'lorem'
  • i - indicates it is case-insensitive

Text Replace with RegExp


    var str = "hello world. Hello class. hello things";
    var pattern = /hello/i;
    var newStr = str.replace(pattern, 'Goodbye'); 

Result: 'Goodbye world. Hello class. hello things'

Global Flag

We can add g to our pattern to globally replace.


    var str = "hello world. Hello class. hello things";
    var pattern = /hello/ig;
    var newStr = str.replace(pattern, 'Goodbye'); 

Result: 'Goodbye world. Goodbye class. Goodbye things'

Regex Test

Regex Test is a method that allows us to see if a block of text contains a pattern. This leverages the RegExp object.


    var str = "Lorem ipsum dolor";
    var patt = new RegExp(/lorem/i);
    var res = patt.test(str);        
    

The i flag allows 'Lorem' to match.

Useful Patterns

Constructing RegExp patterns can be really hard. I always keep a few handy.

  • /[a-z]/gi - Letters only
  • /[0-9]/gi - Numbers only
  • /^[a-z0-9_-]{3,16}$/ - User Name min 3 max 16
  • /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/ - Email
  • /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ - URL

Create more here

Links Page

Functions follow-up

Arays follow-up

Objects follow-up

Exercise 11

  • Clone this repo
  • Create a repo on GitHub called Exercises.
  • Clone it and get it all setup.
  • Copy the folder from Exercise11 from the course info into your new repo.
  • Perform the exercise in your new repo and push to GitHub when finished.
  • Send me a link when done.

Super Challenge

Research the difference between x++ and ++x and use ++x properly in a for loop that returns an array populated with the unique values of this array:
var fruits = ["Orange", "Orange", "Apple", "Apple"];
(so result is ["Orange", "Apple"])

Exercise 27

>