Workshop Chat Room: avi.codes/chat
Live Presentation: slides.com/avipatel91/deck-2/live
Slides: slides.com/avipatel91/deck-2
> 1 + 1;
2
> 6 / 2;
3
> 1 + 4 * ( 2 + 2 );
17
> "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"
> 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
> 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.
/*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
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 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.
===
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
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.
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.
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.
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
}
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.
var car = {
make: 'Tesla',
model: 'S',
year: 2015,
miles: 45,
battery: 100,
charge: function(){
this.battery = 100;
},
drive: function(){
this.battery -= 20;
}
};
Literal Notation
var Person = {
name: "Bob",
age: 45
};
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.
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";
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'
This keyword is used to indicate that the property or method belongs to the object that the function creates.
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 |
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"
<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script type="text/javascript" src="myScript.js"></script>
</head>
<body>
<h1>Greetings!</h1>
</body>
</html>
HTML
JS
Parser
Displayed webpage
Note: This is a very high level overview. A lot more goes on behind the scenes.
source: JavaScript and jQuery - John Duckett
HTML and its DOM tree representation
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')
/*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');
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.
var elements = document.getElementsByClassName('cool');
/*Selecting an element from a node list */
if(elements.length >=1 ){
var firstItem = elements[0];
}
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.
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.
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');
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.
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';