SlideShare a Scribd company logo
FEWD - WEEK 6
WILL MYERS
Freelance Front End Developer
SLIDES
http://www.slideshare.net/wilkom/fewd-week6-slides
YOUR WEEKLY FEWD GITHUB
REPOSITORY
Use the '+' button in the top-left of GitHub Desktop
(Create tab)
Create a new repository called 'FEWD_Week6'
Choose the [home]/FEWD folder for the local path
Open this repo folder in your editor
Commit the changes and publish the FEWD_Week6
repository to github.com
YOUR WEEKLY WORKING FILES
FROM ME
To get the week6_working_files you should just be able to
select the ga-fewd-files repository in GitHub Desktop and
press 'Sync'. This should pull in this weeks folder from
github.com.
If you any difficulties you should just re-clone the ga-fewd-
files repository.
Copy the whole week6_working_files into your FEWD_Week6
repository and commit and publish to github.com
REVIEW OF LAST WEEK'S
ASSIGNMENT
AGENDA
Collection Of Data
Manipulating Collections
ARRAYS COLLECTIONS
ARRAYS
What if we had a collection of images that we wanted to
display to the screen one at a time?
How could we store all the images?
ARRAYS
An array is a list object with built in methods for things like:
adding to the list
removing from the list
traversal of the list.
DECLARING ARRAYS
var myArr = new Array();
declaring an empty array using the Array constructor.
DECLARING ARRAYS
var myArr = [ ];
declaring an empty array using literal notation.
DECLARING ARRAYS
myArr = ['Hello', 54.3, true];
Arrays are filled with elements: i.e. myArr3 = [element,
anotherElement];
Elements can contain strings, numbers, booleans, and
more.
DECLARING ARRAYS
If you leave a blank spot in an array it creates a blank shelf
space (undefined) placeholder.
ARRAYS INDEXING
ARRAYS INDEXING
Array elements can be fetched by their index number (starts
from 0).
myArr = ['Hello', , 54.3, true];
console.log(myArr[0]); //prints Hello
console.log(myArr[1]); //prints undefined
console.log(myArr[2]); //prints 54.3
console.log(myArr[3]); //prints true
ARRAYS INDEXING
We can insert new values into any space in the array using
the positions index.
myArr[1] = 'Stuff';
ARRAYS INDEXING
We can overwrite all the elements of an array simply by
giving the array new values or by setting an array equal to a
different array.
var fruits = ['Apples', 'Oranges', 'Pears', 'Bananas'];
var myArr=[1,2,3];
myArr = fruits;
console.log(myArr); //prints Apples, Oranges, Pears, Bananas
ARRAY LENGTH
What if I would like to know how long my array is (how many
elements)?
console.log(myArr.length); //prints 4
ARRAY METHODS
The Array object has many built in methods for doing stuff
with arrays. Here are two common methods:
Array.push()adds an item to the end of an array
var myArr = [1,2,3];
myArr.push(4); //myArr === [1,2,3,4]
Array.pop()removes an item from the end of an array
var myArr = [1,2,3,4];
var popped = myArr.pop(); //myArr === [1,2,3]; popped = 4;
ARRAYS EXERCISE
Open week5_working_files/arrays_exercise
ITERATE OVER ARRAY
Computers can repeatedly execute lines of code very
quickly (in milliseconds and nanoseconds)
Combined with conditions (if) computers can process
large quantities of data quickly and make "intelligent"
decisions based on this data.
Sequentially processing a list of data and doing
something with the data is one of the most common
activities in programming.
ITERATE OVER ARRAY - REPEAT LOOPS
forloop:
for (var i = 0; i < 5; i++) {
//i runs from 0 to 4 in this loop.
};
whileloop:
var n = 10;
while(n--){
console.log('n is', n); //n runs from 9 to 0
};
ITERATE OVER ARRAY
The Array.forEachmethod also allows you to run code
using each element from the array as a value
You pass an anonymous function with pre-defined
arguments
var fruits=["Banana","Apple","Pear"]
fruits.forEach(function(element,index){
console.log(element, "is at position", index);
});
elementis the item from the array
indexis the item's position in the array
MORE ON ARRAYS
For many more Array methods see:​
https://developer.mozilla.org/en-
US/docs/JavaScript/Reference/Global_Objects/Array
CAROUSEL
Open week5_working_files/carousel_animals
WEATHER APPLICATION
Can you build a weather application that works in the same
way as your CitiPix assignment?
The user inputs a temperature in Celsius
This temperature gets converted to Fahrenheit and
displayed on the page
Change the display of an image on the page if the
temperature is cold or hot (< 20 degrees Celsius or >= 20
degrees Celsius)
ROCK PAPER SCISSORS
Open week6_working_files/rock_paper_scissors
AGENDA
Refactor
This Keyword
Debugging Techniques
REFACTOR
Making code more efficient without changing
functionality.
REFACTOR
The process of rewriting code without changing
functionality
To reduce or eliminate redundancy
Make code easier to read
Make code more maintainable
CSS REFACTOR
Remove inline styling
Replace repeated styles with classes
Rename classes/ids for readability
Organize CSS
Group by section
Order by precedence (tag selectors at top, id selectors at
bottom)
Create classes for large CSS changes in JS
Remove unnecessary css
JS REFACTOR
Use functions
Use variables
Use arrays
Combine jQuery selectors
Combine jQuery property changes into objects
.css,.attr,etc
Chain jQuery function calls
REFACTOR
Open week6_working_files/refactor
SWITCH BLOCKS
When you end up writing a lot if ... elsesyntax in your
code (for example in the Rock Paper Scissors game) you can
use a different syntax (as follows) to make your code a bit
cleaner and clearer:
switch(someValue){
case "value1":
doThis();
break;
case "value2":
doThat();
break;
default:
doSomethingElse();
}
It is important have the break;keyword at the end of each
casestatement, so as to exit the switchblock correctly.
SWITCH BLOCKS
Let's refactor Rock Paper Scissors with a switchblock
KEYWORD: "THIS"
In JavaScript thisis the keyword for a context object. It is
used inside a function block.
You can think of the context as the owner of a function.
If you write a function in the global context, then thiswill
refer to the global windowobject.
//written in the global window context of your JavaScript file
function doSomething(){
return this; //this refers to the global window object
}
console.log (doSomething() === window);// returns true
KEYWORD: "THIS"
When you attach a function as an event handler to an HTML
element, then the element becomes the owner of the
function and so thiswill refer to the element.
element.onclick = doSomething;
See this link for more info on when thisrefers to an HTML
element: http://www.quirksmode.org/js/this.html
KEYWORD: "THIS" IN JQUERY
jQuery uses thiswrapped in a jQuery selection, so that it
can call jQuery methods directly on the selected element.
If you wrap thisin jQuery - $(this)- in your handler, it
will refer to the element you have selected using jQuery.
See this codepen: http://codepen.io/wilkom/pen/xZjeWz
KEYWORD: "THIS" IN JQUERY
This is useful when you are applying the same event handler
to a group elements and you want each element to work
independently.
$("p").on("click",function(e){
$(this).fadeOut(500);
});
Rule of thumb (ROT): If I don't know what thing will be acted
on, then I should consider using "this"
REFACTOR USING THIS
Open week6_working_files/color_scheme
DEBUGGING
Why isn't this working?
DEBUGGING
Always start be defining the problem.
"The image is not moving"
"None of my code works"
DEBUGGING
This will tell you where to start your hunt
Image not moving
find the code that makes the image move
None of my code works
Syntax error, check console
DEBUGGING: LEVEL 1
Check for errors (red text, aligned right) in console To access
debugging console
PC: CTRL+SHIFT+J
Mac: COMMAND+OPTION+J
Click the error
The location may not be correct but is a good place to start
Ex: Unbalanced brackets or parentheses
DEBUGGING: LEVEL 2
So no red errors but not getting the right answer? Try
console.log
Ex:
var stringOfNames="";
["Bob","Joe"].forEach(function(element){
stringOfNames-=element+",";
console.log(stringOfNames);
});
DEBUGGING: LEVEL 3
Use the debugger in Chrome
Set a breakpoint
Run the code
Step through the code until you get to the error
Variable values display on the right
You can switch to the console to run code or check value
of variable
DEBUGGING: LEVEL 4
Get help!
1. Try "Your preferred search engine" search
2. Be ready to clearly articulate the problem (Write out what
your problem is)
3. If nothing, ask instructor
DEBUG
Open week6_working_files/debug

More Related Content

What's hot (20)

KEY
SproutCore is Awesome - HTML5 Summer DevFest
tomdale
 
PDF
Putting the Cat in the Catalogue: A Feline-Inspired OPAC Theme For Koha
Galen Charlton
 
PDF
Everything You (N)ever Wanted to Know about Testing View Controllers
Brian Gesiak
 
PDF
Design for succcess with react and storybook.js
Chris Saylor
 
PDF
Violet Peña - Storybook: A React Tool For Your Whole Team
Anton Caceres
 
PDF
Ember and containers
Matthew Beale
 
PPT
jQuery 1.7 Events
dmethvin
 
PDF
Testing view controllers with Quick and Nimble
Marcio Klepacz
 
PDF
Integrating React.js with PHP projects
Ignacio Martín
 
PDF
Crossing platforms with JavaScript & React
Robert DeLuca
 
PDF
Hidden Treasures in Project Wonder
WO Community
 
PDF
Quick: Better Tests via Incremental Setup
Brian Gesiak
 
PDF
jQuery in 15 minutes
Simon Willison
 
PDF
Complex Architectures in Ember
Matthew Beale
 
PDF
Advanced redux
Boris Dinkevich
 
PPTX
Owl: The New Odoo UI Framework
Odoo
 
PDF
Ruby - Design patterns tdc2011
Rafael Felix da Silva
 
KEY
amsterdamjs - jQuery 1.5
mennovanslooten
 
PDF
Containers & Dependency in Ember.js
Matthew Beale
 
PDF
The effective use of Django ORM
Yaroslav Muravskyi
 
SproutCore is Awesome - HTML5 Summer DevFest
tomdale
 
Putting the Cat in the Catalogue: A Feline-Inspired OPAC Theme For Koha
Galen Charlton
 
Everything You (N)ever Wanted to Know about Testing View Controllers
Brian Gesiak
 
Design for succcess with react and storybook.js
Chris Saylor
 
Violet Peña - Storybook: A React Tool For Your Whole Team
Anton Caceres
 
Ember and containers
Matthew Beale
 
jQuery 1.7 Events
dmethvin
 
Testing view controllers with Quick and Nimble
Marcio Klepacz
 
Integrating React.js with PHP projects
Ignacio Martín
 
Crossing platforms with JavaScript & React
Robert DeLuca
 
Hidden Treasures in Project Wonder
WO Community
 
Quick: Better Tests via Incremental Setup
Brian Gesiak
 
jQuery in 15 minutes
Simon Willison
 
Complex Architectures in Ember
Matthew Beale
 
Advanced redux
Boris Dinkevich
 
Owl: The New Odoo UI Framework
Odoo
 
Ruby - Design patterns tdc2011
Rafael Felix da Silva
 
amsterdamjs - jQuery 1.5
mennovanslooten
 
Containers & Dependency in Ember.js
Matthew Beale
 
The effective use of Django ORM
Yaroslav Muravskyi
 

Viewers also liked (20)

PPTX
Cuadro Comparativo
Arleth Orellana
 
PDF
Designing for Online Collaborative Sensemaking
Nitesh Goyal
 
PPTX
Mapa de riesgo
Paola Carolina Bracho Romero
 
PDF
Machine learning
Alex Vermeulen
 
DOCX
Week van de Mobiliteit 2015
Ans Huisman
 
PDF
Boletín Semestral INPPARES Informa (Semestre 1/ Ene - Jun 2015 )
INPPARES / Perú
 
PPTX
The Percheron horses:
DrMuhammadAshiq
 
PPTX
Milvia pinedaa5
Milvia Pineda
 
PDF
Gastronomía 2.0 en la red
Javier Camacho
 
PPTX
Chem 2 - Acid-Base Equilibria IV: Calculating the pH of Strong Acids versus W...
Lumen Learning
 
PDF
Turismo en entornos competitivos
Javier Camacho
 
PPTX
Higiene y Seguridad Industrial
'Crlooz Márqez
 
PDF
La Educación Sexual Integral en la Prevención de la Violencia.
INPPARES / Perú
 
PDF
Abordaje preventivo del duelo complicado en unidades de hospitalización
Centro de Humanización de la Salud
 
PPTX
1.9 temperatura y ley cero de la termodinamica
Tersy Comi Gonzalez
 
PDF
Introducción a la ingeniería
Universidad Libre
 
PPTX
e paper seminar
Vyshnav Radhakrishnan
 
PDF
Marca Sevilla by Sevilla Tourism Week
Javier Camacho
 
PPT
Trabajo sobre el sida
septimogrado
 
PPTX
Sexualidad y discapacidad
Fundación Dios es Amor
 
Cuadro Comparativo
Arleth Orellana
 
Designing for Online Collaborative Sensemaking
Nitesh Goyal
 
Machine learning
Alex Vermeulen
 
Week van de Mobiliteit 2015
Ans Huisman
 
Boletín Semestral INPPARES Informa (Semestre 1/ Ene - Jun 2015 )
INPPARES / Perú
 
The Percheron horses:
DrMuhammadAshiq
 
Milvia pinedaa5
Milvia Pineda
 
Gastronomía 2.0 en la red
Javier Camacho
 
Chem 2 - Acid-Base Equilibria IV: Calculating the pH of Strong Acids versus W...
Lumen Learning
 
Turismo en entornos competitivos
Javier Camacho
 
Higiene y Seguridad Industrial
'Crlooz Márqez
 
La Educación Sexual Integral en la Prevención de la Violencia.
INPPARES / Perú
 
Abordaje preventivo del duelo complicado en unidades de hospitalización
Centro de Humanización de la Salud
 
1.9 temperatura y ley cero de la termodinamica
Tersy Comi Gonzalez
 
Introducción a la ingeniería
Universidad Libre
 
e paper seminar
Vyshnav Radhakrishnan
 
Marca Sevilla by Sevilla Tourism Week
Javier Camacho
 
Trabajo sobre el sida
septimogrado
 
Sexualidad y discapacidad
Fundación Dios es Amor
 
Ad

Similar to Fewd week6 slides (20)

PDF
Fewd week5 slides
William Myers
 
PDF
Lesson 10
Gene Babon
 
PDF
Lesson 10
Gene Babon
 
PPTX
Week 6 java script loops
brianjihoonlee
 
PDF
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
PDF
GDI Seattle - Intro to JavaScript Class 2
Heather Rock
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
PPTX
Coding 101: A hands-on introduction
Bohyun Kim
 
PDF
Maintainable JavaScript 2011
Nicholas Zakas
 
PDF
JavaScript 101
ygv2000
 
KEY
Week3
Will Gaybrick
 
PPTX
A Skeptics guide to functional style javascript
jonathanfmills
 
ZIP
Javascript Everywhere
Pascal Rettig
 
PPTX
Week 7 html css js
brianjihoonlee
 
PDF
J query fundamentals
Attaporn Ninsuwan
 
PPTX
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
PPTX
Class[3][5th jun] [three js]
Saajid Akram
 
PPS
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
ZIP
Back To The Future.Key 2
gueste8cc560
 
PDF
Handout - Introduction to Programming
Cindy Royal
 
Fewd week5 slides
William Myers
 
Lesson 10
Gene Babon
 
Lesson 10
Gene Babon
 
Week 6 java script loops
brianjihoonlee
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
GDI Seattle - Intro to JavaScript Class 2
Heather Rock
 
Maintainable JavaScript 2012
Nicholas Zakas
 
Coding 101: A hands-on introduction
Bohyun Kim
 
Maintainable JavaScript 2011
Nicholas Zakas
 
JavaScript 101
ygv2000
 
A Skeptics guide to functional style javascript
jonathanfmills
 
Javascript Everywhere
Pascal Rettig
 
Week 7 html css js
brianjihoonlee
 
J query fundamentals
Attaporn Ninsuwan
 
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Class[3][5th jun] [three js]
Saajid Akram
 
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
Back To The Future.Key 2
gueste8cc560
 
Handout - Introduction to Programming
Cindy Royal
 
Ad

More from William Myers (7)

PDF
Fewd week8 slides
William Myers
 
PDF
Fewd week7 slides
William Myers
 
PDF
Fewd week4 slides
William Myers
 
PDF
Fewd week3 slides
William Myers
 
PDF
Fewd week2 slides
William Myers
 
PDF
Fewd week1 slides
William Myers
 
PDF
Pfnp slides
William Myers
 
Fewd week8 slides
William Myers
 
Fewd week7 slides
William Myers
 
Fewd week4 slides
William Myers
 
Fewd week3 slides
William Myers
 
Fewd week2 slides
William Myers
 
Fewd week1 slides
William Myers
 
Pfnp slides
William Myers
 

Recently uploaded (20)

PPTX
Random Presentation By Fuhran Khalil uio
maniieiish
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
PDF
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPTX
一比一原版(LaTech毕业证)路易斯安那理工大学毕业证如何办理
Taqyea
 
PDF
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
PDF
Digital Security in 2025 with Adut Angelina
The ClarityDesk
 
PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PDF
DevOps Design for different deployment options
henrymails
 
PPTX
Cost_of_Quality_Presentation_Software_Engineering.pptx
farispalayi
 
PDF
Technical Guide to Build a Successful Shopify Marketplace from Scratch.pdf
CartCoders
 
PPTX
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
PPTX
Template Timeplan & Roadmap Product.pptx
ImeldaYulistya
 
PPTX
本科硕士学历佛罗里达大学毕业证(UF毕业证书)24小时在线办理
Taqyea
 
PPTX
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
PDF
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 
Random Presentation By Fuhran Khalil uio
maniieiish
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
introductio to computers by arthur janry
RamananMuthukrishnan
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
一比一原版(LaTech毕业证)路易斯安那理工大学毕业证如何办理
Taqyea
 
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
Digital Security in 2025 with Adut Angelina
The ClarityDesk
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
DevOps Design for different deployment options
henrymails
 
Cost_of_Quality_Presentation_Software_Engineering.pptx
farispalayi
 
Technical Guide to Build a Successful Shopify Marketplace from Scratch.pdf
CartCoders
 
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
Template Timeplan & Roadmap Product.pptx
ImeldaYulistya
 
本科硕士学历佛罗里达大学毕业证(UF毕业证书)24小时在线办理
Taqyea
 
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 

Fewd week6 slides

  • 1. FEWD - WEEK 6 WILL MYERS Freelance Front End Developer SLIDES http://www.slideshare.net/wilkom/fewd-week6-slides
  • 2. YOUR WEEKLY FEWD GITHUB REPOSITORY Use the '+' button in the top-left of GitHub Desktop (Create tab) Create a new repository called 'FEWD_Week6' Choose the [home]/FEWD folder for the local path Open this repo folder in your editor Commit the changes and publish the FEWD_Week6 repository to github.com
  • 3. YOUR WEEKLY WORKING FILES FROM ME To get the week6_working_files you should just be able to select the ga-fewd-files repository in GitHub Desktop and press 'Sync'. This should pull in this weeks folder from github.com. If you any difficulties you should just re-clone the ga-fewd- files repository. Copy the whole week6_working_files into your FEWD_Week6 repository and commit and publish to github.com
  • 4. REVIEW OF LAST WEEK'S ASSIGNMENT
  • 7. ARRAYS What if we had a collection of images that we wanted to display to the screen one at a time? How could we store all the images?
  • 8. ARRAYS An array is a list object with built in methods for things like: adding to the list removing from the list traversal of the list.
  • 9. DECLARING ARRAYS var myArr = new Array(); declaring an empty array using the Array constructor.
  • 10. DECLARING ARRAYS var myArr = [ ]; declaring an empty array using literal notation.
  • 11. DECLARING ARRAYS myArr = ['Hello', 54.3, true]; Arrays are filled with elements: i.e. myArr3 = [element, anotherElement]; Elements can contain strings, numbers, booleans, and more.
  • 12. DECLARING ARRAYS If you leave a blank spot in an array it creates a blank shelf space (undefined) placeholder.
  • 14. ARRAYS INDEXING Array elements can be fetched by their index number (starts from 0). myArr = ['Hello', , 54.3, true]; console.log(myArr[0]); //prints Hello console.log(myArr[1]); //prints undefined console.log(myArr[2]); //prints 54.3 console.log(myArr[3]); //prints true
  • 15. ARRAYS INDEXING We can insert new values into any space in the array using the positions index. myArr[1] = 'Stuff';
  • 16. ARRAYS INDEXING We can overwrite all the elements of an array simply by giving the array new values or by setting an array equal to a different array. var fruits = ['Apples', 'Oranges', 'Pears', 'Bananas']; var myArr=[1,2,3]; myArr = fruits; console.log(myArr); //prints Apples, Oranges, Pears, Bananas
  • 17. ARRAY LENGTH What if I would like to know how long my array is (how many elements)? console.log(myArr.length); //prints 4
  • 18. ARRAY METHODS The Array object has many built in methods for doing stuff with arrays. Here are two common methods: Array.push()adds an item to the end of an array var myArr = [1,2,3]; myArr.push(4); //myArr === [1,2,3,4] Array.pop()removes an item from the end of an array var myArr = [1,2,3,4]; var popped = myArr.pop(); //myArr === [1,2,3]; popped = 4;
  • 20. ITERATE OVER ARRAY Computers can repeatedly execute lines of code very quickly (in milliseconds and nanoseconds) Combined with conditions (if) computers can process large quantities of data quickly and make "intelligent" decisions based on this data. Sequentially processing a list of data and doing something with the data is one of the most common activities in programming.
  • 21. ITERATE OVER ARRAY - REPEAT LOOPS forloop: for (var i = 0; i < 5; i++) { //i runs from 0 to 4 in this loop. }; whileloop: var n = 10; while(n--){ console.log('n is', n); //n runs from 9 to 0 };
  • 22. ITERATE OVER ARRAY The Array.forEachmethod also allows you to run code using each element from the array as a value You pass an anonymous function with pre-defined arguments var fruits=["Banana","Apple","Pear"] fruits.forEach(function(element,index){ console.log(element, "is at position", index); }); elementis the item from the array indexis the item's position in the array
  • 23. MORE ON ARRAYS For many more Array methods see:​ https://developer.mozilla.org/en- US/docs/JavaScript/Reference/Global_Objects/Array
  • 25. WEATHER APPLICATION Can you build a weather application that works in the same way as your CitiPix assignment? The user inputs a temperature in Celsius This temperature gets converted to Fahrenheit and displayed on the page Change the display of an image on the page if the temperature is cold or hot (< 20 degrees Celsius or >= 20 degrees Celsius)
  • 26. ROCK PAPER SCISSORS Open week6_working_files/rock_paper_scissors
  • 28. REFACTOR Making code more efficient without changing functionality.
  • 29. REFACTOR The process of rewriting code without changing functionality To reduce or eliminate redundancy Make code easier to read Make code more maintainable
  • 30. CSS REFACTOR Remove inline styling Replace repeated styles with classes Rename classes/ids for readability Organize CSS Group by section Order by precedence (tag selectors at top, id selectors at bottom) Create classes for large CSS changes in JS Remove unnecessary css
  • 31. JS REFACTOR Use functions Use variables Use arrays Combine jQuery selectors Combine jQuery property changes into objects .css,.attr,etc Chain jQuery function calls
  • 33. SWITCH BLOCKS When you end up writing a lot if ... elsesyntax in your code (for example in the Rock Paper Scissors game) you can use a different syntax (as follows) to make your code a bit cleaner and clearer: switch(someValue){ case "value1": doThis(); break; case "value2": doThat(); break; default: doSomethingElse(); } It is important have the break;keyword at the end of each casestatement, so as to exit the switchblock correctly.
  • 34. SWITCH BLOCKS Let's refactor Rock Paper Scissors with a switchblock
  • 35. KEYWORD: "THIS" In JavaScript thisis the keyword for a context object. It is used inside a function block. You can think of the context as the owner of a function. If you write a function in the global context, then thiswill refer to the global windowobject. //written in the global window context of your JavaScript file function doSomething(){ return this; //this refers to the global window object } console.log (doSomething() === window);// returns true
  • 36. KEYWORD: "THIS" When you attach a function as an event handler to an HTML element, then the element becomes the owner of the function and so thiswill refer to the element. element.onclick = doSomething; See this link for more info on when thisrefers to an HTML element: http://www.quirksmode.org/js/this.html
  • 37. KEYWORD: "THIS" IN JQUERY jQuery uses thiswrapped in a jQuery selection, so that it can call jQuery methods directly on the selected element. If you wrap thisin jQuery - $(this)- in your handler, it will refer to the element you have selected using jQuery. See this codepen: http://codepen.io/wilkom/pen/xZjeWz
  • 38. KEYWORD: "THIS" IN JQUERY This is useful when you are applying the same event handler to a group elements and you want each element to work independently. $("p").on("click",function(e){ $(this).fadeOut(500); }); Rule of thumb (ROT): If I don't know what thing will be acted on, then I should consider using "this"
  • 39. REFACTOR USING THIS Open week6_working_files/color_scheme
  • 41. DEBUGGING Always start be defining the problem. "The image is not moving" "None of my code works"
  • 42. DEBUGGING This will tell you where to start your hunt Image not moving find the code that makes the image move None of my code works Syntax error, check console
  • 43. DEBUGGING: LEVEL 1 Check for errors (red text, aligned right) in console To access debugging console PC: CTRL+SHIFT+J Mac: COMMAND+OPTION+J Click the error The location may not be correct but is a good place to start Ex: Unbalanced brackets or parentheses
  • 44. DEBUGGING: LEVEL 2 So no red errors but not getting the right answer? Try console.log Ex: var stringOfNames=""; ["Bob","Joe"].forEach(function(element){ stringOfNames-=element+","; console.log(stringOfNames); });
  • 45. DEBUGGING: LEVEL 3 Use the debugger in Chrome Set a breakpoint Run the code Step through the code until you get to the error Variable values display on the right You can switch to the console to run code or check value of variable
  • 46. DEBUGGING: LEVEL 4 Get help! 1. Try "Your preferred search engine" search 2. Be ready to clearly articulate the problem (Write out what your problem is) 3. If nothing, ask instructor