Review

  • Numbers and Strings
  • Variables
  • Methods and Functions

Numbers

  • Numbers are a type of data
  • You can apply math operations to numbers.  ( * / + - %)
  • Modulus (%) returns the remainder.
  • All statements in JS end with a semicolon. 
> 1 + 1;
2

> 6 / 2;
3

> 1 + 4 * ( 2 + 2 );
17

Strings

  • Strings are a type of data
  • Strings are characters enclosed in quotes. 
  • NUMBERS ARE NOT STRINGS. 
    • e.g. 123 is not equal to "123"
  • You can add (concat) strings together by using the plus sign. 
> "Hello World!"
"Hello World!"

> 123 === "123"   //The === operation check whether the left side is equal to the right side. 
false

//notice that i added a string with an empty space between the two strings. 
> "One does not simply" + " " + "walk into Mordor";    
"One does not simply walk into Mordor"

Variables

  • Variables are a placeholder for data and functions. 
  • You can reassign a variable with a different type of value.
  • Variable names are in camel case. 
> var foo = 2;  //variable called foo is assigned the value 2
> foo = 3;      // the new value of foo is now 3
> foo + 2;      // This will take the value of foo, add 2 and return a new number. 
5
> foo+=2;       //this will take the value of foo, add 2 and then put the new value back into foo. 
> var b = foo;  //assigning the value of foo to b.
> b;
5

Methods

  • Methods are used to manipulate a data type. 
  • JS comes with methods for data types such as strings and numbers. 
  • For some methods, you can pass in values/data into a method when calling it.
  • Methods for one data type does not work for another data type. 
> 1.337.toFixed()  //rounds to the nearest whole number.
"1"                //this method returns a string instead of a number. 
>1.337.toFixed(3)  //Rounds to two decimal places. 
"1.34"

>"Pow".repeat(3);  //returns this string repeated 3 times.
"PowPowPow" 
>"Do you even ".concat("code?");
"Do you even code?"

123.concat("456"); //this is not possible. 

Functions

  • Functions perform an action when called.
  • Unlike methods, functions are not called on a data type.
  • Like methods, functions can take in arguments. 
  • You can define your own functions using the function keyword. 
  • You can assign a function to a variable and call it. 
/*This creates a function and assigns it to a variable. It takes in two 
arguments and returns the sum of the two arguments. */ 

> var sum = function(num1, num2){ return num1 + num2; }


//You can then call the function and pass in arguments. 
>sum(2, 3);
5

Onward to new horizons! 

Making Decisions

  • When a program runs, there are often several places in the program (code) where decisions are made that determine which lines of code should be run next.

  • These decisions are made based on whether conditions are met.

  • In order to determine whether a condition is met, we use comparison operators.

Comparison Operators

Comparison operators return a Boolean value (true or false).

===

is equal to

>

greater than

<

less than

Checks if two values are equal

Checks if the value on the left hand side is greater than the value on the right hand side.

Checks if the value on the left hand side is less than the value on the right hand side.

Comparison Operators Example

===

is equal to

>

greater than

<

less than

>> 5 < 3
false

>> 4 < 6
true
>> 6 > 7
false

>> 'Michael Jordan' > 'LeBron James'
true
>> 'Lebron James' === 'Michael Jordan'
false

>> 6 === 6
true

If...else statement

 One way to control the flow of a script is to use an if...else statement.

An if...else statement evaluates a condition and makes a decision on control flow depending on whether that condition is true or false.

Remember, a condition is where you compare two values using a comparison operator.

If...else statement continued

var score = 74;








if (score > 60){
  alert("You passed!");
} else{
  alert("Please try again!");
}

condition

}

}

Every line of code between the first set of brackets gets executed if the condition is true....

...Else every line of code within the second set of brackets gets executed.

The if...else statement checks a condition. If the condition is true, the first code block gets executed. If it is false, then the second code block gets executed.

Let's take a step backwards

var score = 35;





if (score > 60){
  alert("You passed!");
} 

This will evaluate to false.

}

None of the code in this block will get executed since the condition is false.

  • You can use the if statement by itself without the else.
  • What happens if you only use if?
    • If the condition is true, the following block of code gets executed. If it is false, then the JS engine skips the block and continues executing the rest of the script.

If...else Practice

1. Prompt the user for a number. If the number is less than 50, alert them that their number is less than 50. Don't worry if their number is equal to 50.

 

2. Let's build on top of problem 1. If the number is less than 50, it will still have the same alert. However, if it is greater than 50, then it will alert them that their number is greater than 50.

//Reference

var loginID = prompt('What is your login ID?');   //I will enter 'daRThVader' 


//The following condition will evaluate to true

if(loginID == 'daRThVader'){
  alert('You have successfully logged in.');     //this will end up running
}else{
  alert('Invalid Login ID');                    //this will be ignored
}

Objects

  • Objects group together variables and functions to create a model.
  • Variables are properties
  • Functions are known as methods.
  • Objects tend to represent real world objects/models.
var car = {
    make: 'Tesla',    
    model: 'S',
    year: 2015,
    miles: 45,
    battery: 100,
    charge: function(){
        this.battery = 100;
    },
    drive: function(){
        this.battery -= 20;
    }
};

properties

methods

I will go over this keyword in a later slide.

Objects Continued

  • Objects cannot have two keys with the same name.
  • The name of the property or method is called the key
    • e.g. keys: make, model, year,...,drive
  • The value is...well, the value of the key.
    • e.g. values: 'Tesla', 'S',...,function(){this.battery-=20;}
var car = {
    make: 'Tesla',    
    model: 'S',
    year: 2015,
    miles: 45,
    battery: 100,
    charge: function(){
        this.battery = 100;
    },
    drive: function(){
        this.battery -= 20;
    }
};

Creating Objects

  • There are two ways to create an object.
    • Literal Notation
    • Constructor Notation

Literal Notation

var Person = {
    name: "Bob",
    age: 45
};
  • Object is in curly braces
  • Object is stored in a variable.
  • Seperate key from value using colon.
  • Seperate each property and method using comma, but not after last value.

Accessing Object Properties and Methods

var worldLeaders = {
    russia: 'Putin',
    england: 'Cameron',
    china: 'JingPing',
    india: 'Modi',
    usa: 'Obama',
    world: 'Dr. Evil'
}

//Dot notation
var leader1 = worldLeaders.russia;   //leader1 will now equal 'Putin'

//Bracket notation
worldLeaders['usa'] = 'Morgan Freeman';  //the value of usa changed to 'Morgan Freeman'.    

delete worldLeaders.world;   //This will remove world: 'Dr. Evil' from the object.  
  • To update or retrieve the value of the property, use dot notation or square brackets.
  • You can only use dot notation to call or change a method in the object.
  • Use the delete keyword to delete a property.
  • You can add properties using dot notation.

Creating Objects Practice

Reference

var randomStuff = {
    microsoft: "Bill Gates",
    apple: "Steve Jobs",
    uberValuation: 51000000000    //yes, Uber is supposedly valued at 50+ billion. Not bad for a company that started in 2009.  
};

//Steve Jobs is replaced with Steve Wozniak (the real genius behind Apple).  
randomStuff.apple = "Steve Wozniak";    
  1. Create an object that represents a person. Give it an name, age, and gender.
  2. Create an object that represents employee. Give it a:
    • name
    • ID number
    • title
    • a method called "login" that returns the ID number concatenated to name. (Remember, you can add a string and number together to create a new string)
    1. After the object has been created, change the ID of the employee to another to another number.

Creating Objects Continued

Constructor Notation

function Car(make, model, year){
    this.make = make;                       //notice that semicolons are used.
    this.rooms = rooms;
    this.year = year;
}

var example = new Car('Ford', 'Model T', 1908);
var example2 = new Car('Toyota', 'Prius', 2016);

example.make; //this will return 'Ford'
example2.make; //this will return 'Toyota' 
  • Use the new keyword and object constructor function to create an object. 
  • Use constructor notation to create multiple objects that are similar.
  • The constructor function will be the blueprint. Whenever it is called using new, a copy is created.
  • The function can then set the values of the object.

This keyword is used to indicate that the property or method belongs to the object that the function creates.

Arrays

  • Arrays are a special type of object.
  • Like objects, they hold a key/value pairs, but the key is an index number.
var costs = {
    room1: 320,
    room2: 545,
    room3: 625,
    room4: 720,
};


var costs = [320,545,625,720];

Object

Array

Property Value
room1 320
room2 460
room3 625
room4 720
Index Number Value
0 320
1 460
2 625
3 720

Arrays Continued

  • An array stores a list of values.
  • You do not need to specify how many items you need in order to create it.
  • Values are inside a pair of square brackets, separated by commas.
  • The values do not need to be the same type. 
  • Arrays have a length property that returns the length of the array.
  • Indexing is off by one.
var randomMoviesAndNumbers = ["Space Jam", 3, "LOTR", "Straight Outta Compton", 
                   "Star Wars", "Godfather", "Matrix", "Toy Story", 
                   "Pulp Fiction", "Scarface", "Harry Potter", "Titanic", 2, 4];

randomMoviesAndNumbers[8];  //This will return "Pulp Fiction"

randomMoviesAndNumbers.length;  //This will return 13 (length of the list)

randomMoviesAndNumbers[0] = "The Martian";  //first item in list is replaced with "The Martian"

JS and HTML

  • We can use JavaScript to program the behavior of web pages.
    • For example, we can use JS to the text in an HTML element if we mouse over it.
  • With JavaScript we can create rich web applications using web apis.
    • There are objects built into JavaScript that represent a web page.
    • Playing around with these objects will let us manipulate the web page.

 

How to include JS into HTML

  • We use <script> tag to link a JS script into the HTML document.
  • The script tag can go anywhere on the page.
<!-- index.html -->
<html>
    <head>
        <title>My Page</title>
        <script type="text/javascript" src="myScript.js"></script>
    </head>
    <body>
        <h1>Greetings!</h1>
    </body>
</html>
  • Type specifcies that we are using a JavaScript. It should always have the value "text/javascript" if we are using JS.
  • Src specifies the path to the JS file relative to the HTML file. In the example above, myScript.js is in the same folder as index.html.

How does the browser load a webpage?

  1. Browser fetches the HTML page (e.g. index.html)
  2. Begins parsing the HTML.
  3. The browser encounters a <script> tag referencing an external script file.
  4. The browser then requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
  5. The script file is downloaded and the code within it starts getting executed line by line.
  6. Once that script is executed, the parser continues parsing the rest of the HTML document.

HTML

JS

Parser

Displayed webpage

Note: This is a very high level overview. A lot more goes on behind the scenes.

DOM

  • There are a set of built-in objects that come with the browser.
    • one of which is the Document Object Model (DOM)
  • The DOM models the current webpage using a objects linked together in a tree like structure. 
  • These objects represent HTML elements.
    • This means that the objects have properties such as attributes and text, which themselves are objects.
  • The topmost object in the tree is the document object.
  • All these objects are all called nodes.
  • Each node/object has methods and properties.
  • Any changes to the DOM tree (changes to the nodes), will be reflected in the browser.
  • The four types of nodes are Document, Element, Attribute, and Text.

Four Types of Nodes

  • Document Node
    • Document node represents the entire webpage.
    • To navigate to any node, one must first go through the document node.
  • Element Nodes
    • These nodes represent HTML elements. They have properties such as attribute and text, which themselves are a nodes.
  • Attribute Nodes
    • Attribute property in the element node is actually a list of attribute nodes representing the attributes of the element node.
  • Text Node
    • Once you access the element node, you can get the text within it. The text is stored in it's own text node.
    • This node is a child of its element node.

More on Nodes

  • The term element and node are used interchangeably.
  • Having four different types of nodes (aka objects) means that they all their own set of methods and properties.
  • In order to change a property value in a node, you must first retrieve the node.

source: JavaScript and jQuery - John Duckett

HTML and its DOM tree representation

  • Notice that the node element that represents the <em> element is a child of the <li> element. This is because the <em> element is within the <li> tags.
  • Same reasoning applies to text nodes. Notice that the text within the element tags is represented as the child node of that element.

 

Retrieving Elements

  • As mentioned in a previous slide, in order to get to the other nodes, you must first go through the document node.

  • You use the document node to retrieve other nodes.

  • The document node has methods that will search for your desired node and return it. These methods are called DOM queries since they query the DOM for element/s you want to retrieve.

  • getElementById('id')

  • querySelector('css selector')

These methods will return one node:

These methods will return a list of elements:

  • getElementsByClassName('class')

  • getElementsByTagName('tagName')

  • querySelectorAll('css selector')

Retrieving Elements Continued

  • The variable named document is already created behind the scenes and is set equal to the document node (aka a object).
  • Remember, you use dot notation to call a method. 
  • Once you have found the node you were looking for, you can then work with that node, its parent, or any children.
/*The following will call a method that belongs to the document node.
It takes in a string argument, specifically the id of the element 
you are looking for. Once the node is found, the method returns it. 
We then assign the returned node to a variable called foo. */

 
var foo = document.getElementById('one');  

Retrieving an Individual Element

var foo = document.getElementById('one');  

getElementById is the quickest and most efficient way to retrieve an element since no two elements have the same value for their id attribute.

document refers to the document object. You will always access individual elements via the document object.

This method will find and return an element node based on the value of the id attribute.

We store the returned object in a variable, so every time we need it later on in the script, we don't have to call it again.

Object

Method

The dot notation indicates that the method on the right of the dot is being applied to the node on the left of the dot.

The method needs to know the value of the id attribute on the element you want. You pass in the value as a string. If there are no matches, the method returns a null value.

Retrieving Multiple Elements

var elements = document.getElementsByClassName('cool');  

/*Selecting an element from a node list */
if(elements.length >=1 ){
    var firstItem = elements[0];
}
  • getElementsByClassName will return a node list of all nodes whose class value is equal to the argument passed in.
  • A node list will always be returned even it only finds one match.
  • A node list behaves like a JavaScript array, but with methods built-in to provide more functionality.

This method will find and return a list of nodes that have their class name equal to 'cool'.

We store the returned node list into a variable.
 We can then access any element in that list using an index.

Notice that we use class name since multiple elements can have the same value for their class, unlike with where you can only have one element.

Programmers tend to check that there is at least one item in the list before retrieving any items from it. This is done to prevent executing code on a list that has no elements for us to work with. Saves resources.

Indexing from a node list is the same as that of a JS array. Get nodes using square bracket notation. Indexing starts at 0 and ends at length - 1.

More Examples

document.querySelector('li.cool');

You can use a css selector syntax to find elements. querySelector will return the first matching element. In the example above, it will return the first element it finds that is a <li> and has class value equal to cool.

document.querySelectorAll('li.hot');

querySelectorAll will return a node list of all elements that match the css selector.

document.getElementsByTagName('li');

This will return a node list of all elements the page with the specified tag name.

Updating class of an element node

Once you retrieved the element node, you can update its classname using the className property.

var foo = document.getElementById('one');  

foo.className = 'cool';

You can also call setAttribute()

*But there is a caveat*

var foo = document.getElementById('one');  

foo.setAttribute('class', 'cool');

The caveat...

var foo = document.getElementById('one');  

foo.setAttribute('class', 'cool'); //foo has two class names "hot cool"

foo.className = 'cool'; //overwrites previous values. foo's class value is "cool"

setAttribute will append the name at the end of the element's class value/s. Whereas className will change the value of the element's class, including overwriting any previous class values for that element.

Updating CSS of an element node

Once you retrieved the element node, you can update its css using the style property followed by the property name, which is then equal to the new style you want.

var foo = document.getElementById('one');  

foo.style.color = 'red';

Find all JS versions of CSS properties here.

Updating multiple elements from a NodeList

In order to update multiple elements from a NodeList, we need to loop through that list using a for statement. Using the loop we can apply the same statements to each item.

//THIS IS PSEUDOCODE. It is NOT the real syntax. 

for (each element i in NodeList){
   NodeList[i].className = "cool"; //apply this to every element in the list
}

Pseudo Code

Loops

Loops are more flow control statements.

  • Loops check a condition and if it is true, a block of code is run.
  • After the block of code is ran, the condition is checked again, if it is true then the same block of code is ran.
  • This cycle continues until the condition is false.

There are 3 types of loops:

For

While

Do While

Loops continued

For loop

var numbers = [1,2,3,4]
var sum = 0;

//This will find the sum of the array. 
for (var i = 0; i < numbers.length; i++){
        sum += numbers[i];
}

console.log(sum); //should output 10 to the console/logging. 

1. create a variable once, assign it 0.

2. check a condition. In this case, we check if the variable i is less than numbers.length

4. We increment i after running the block of code.

3. Run the block of code.

5. Repeat steps 2-4 until the condition is false.

JS continued & jQuery

By avipatel91

JS continued & jQuery

  • 345