SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
BEGINNING JAVASCRIPT
CLASS 2Javascript ~ Girl Develop It ~
WELCOME!
Girl Develop It is here to provide affordable and
accessible programs to learn software through
mentorship and hands-on instruction.
Some "rules"
We are here for you!
Every question is important
Help each other
Have fun
ARRAY
An array is a data-type that holds an ordered list
of values, of any type:
The length property reports the size of the array:
var arrayName = [element0, element1, ...];
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
var favoriteNumbers = [16, 27, 88];
var luckyThings = ['Rainbows', 7, 'Horseshoes'];
console.log(rainbowColors.length);
ARRAYS -- RETURNING
VALUES
You can access items with "bracket notation".
The number inside the brackets is called an
"index"
Arrays in JavaScript are "zero-indexed", which
means we start counting from zero.
var arrayItem = arrayName[indexNum];
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
var firstColor = rainbowColors[0];
var lastColor = rainbowColors[6];
ARRAYS -- UPDATING
VALUES
You can also use bracket notation to change the
item in an array:
Or to add to an array:
You can also use the push method
(recommended):
var awesomeAnimals = ['Corgis', 'Otters', 'Octopi'];
awesomeAnimals[0] = 'Bunnies';
awesomeAnimals[4] = 'Corgis';
awesomeAnimals.push('Ocelots');
LOOPS
Sometimes you want to go through a piece of
code multiple times
Why?
Showing a timer count down.
Display the results of a search.
Sort a list of values.
THE WHILE LOOP
The while loop tells JS to repeat statements while
a condition is true:
Review: '++' means increment by 1!
If we forget x++, the loop will never end!
while (expression) {
// statements to repeat
}
var x = 0;
while (x < 5) {
console.log(x);
x++;
}
THE FOR LOOP
The for loop is a safer way of looping
Less danger of an infinite loop. All conditions are
at the top!
for (initialize; condition; update) {
// statements to repeat
}
for (var i = 0; i < 5; i++) {
console.log(i);
}
LOOPS AND ARRAYS
Use a for loop to easily look at each item in an
array:
var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
for (var i = 0; i < rainbowColors.length; i++) {
console.log(rainbowColors[i]);
}
LET'S DEVELOP IT
Add a new button to the exercise from last
week.
Add an onclick to the button for a function
called favoriteThings().
Create a new function called favoriteThings() in
the JavaScript file.
In the function, create an array and loop
through the results.
Write the results to the document like: "My
favorite things are: XX, YY, ZZ"
Bonus -- add an 'and' in the sentence before
the last item
LET'S ANSWER IT<button type="button" onclick="favoriteThings()"> See my favorite things</button>
function favoriteThings(){
var favoriteThings = ['Rabbits', 'Orange', 'Yogurt', 'Brussel Sprouts', 'Otters'];
var result = 'My favorite things are: ';
for (var i = 0; i < favoriteThings.length; i++) {
result += favoriteThings[i] + ', ';
}
document.write(result);
}
LET'S ANSWER IT (BONUS)function favoriteThings(){
var favoriteThings = ['Rabbits', 'Orange', 'Yogurt', 'Brussel Sprouts', 'Otters'];
var result = 'My favorite things are: ';
for (var i = 0; i < favoriteThings.length; i++) {
if (i < favoriteThings.length - 1) {
result += favoriteThings[i] + ', ';
}
else {
result += "and " + favoriteThings[i] + '.';
}
}
document.write(result);
}
OBJECTS
Objects are a data type that let us store a
collection of properties and methods.
var objectName = {
propertyName: propertyValue,
propertyName: propertyValue,
...
};
var charlie = {
age: 8,
name: "Charlie Brown",
likes: ["baseball", "The little red-haired girl"],
pet: "Snoopy"
};
OBJECTS -- RETURNING
VALUES
Access values of "properties" using "dot
notation":
var charlie = {
age: 8,
name: "Charlie Brown",
likes: ["baseball", "The little red-haired girl"],
pet: "Snoopy"
};
var pet = charlie.pet;
OBJECTS -- RETURNING
VALUES
Or using "bracket notation" (like arrays):
Non-existent properties will return undefined:
var name = charlie['name'];
var gender = charlie.gender
OBJECTS -- CHANGING
VALUES
Use dot or bracket notation with the assignment
operator to change objects.
Change existing properties:
Or add new properties:
You can also delete properties:
charlie.name = "Chuck";
charlie.gender = "male";
delete charlie.gender;
ARRAYS OF OBJECTS
Arrays can hold objects too!
That means we can use a for loop!
var peanuts = [
{name: "Charlie Brown",
pet: "Snoopy"},
{name: "Linus van Pelt",
pet: "Blue Blanket"}
];
for (var i = 0; i < peanuts.length; i++) {
var peanut = peanuts[i];
console.log(peanut.name + ' has a pet named ' + peanut.pet + '.');
}
OBJECTS IN FUNCTIONS
You can pass an object into a function as a
parameter
var peanut ={
name: "Charlie Brown",
pet: "Snoopy"
};
function describeCharacter(character){
console.log(character.name + ' has a pet named ' + character.pet + '.');
}
describeCharacter(peanut);
METHODS
Methods are functions that are associated with
an object
The affect or return a value for a specific object
Used with dot notation
Previously seen example:
document.write("Hello, world!");
METHODS
Methods can be added to objects in two ways.
Declared with the object.
Attached using dot notation.
var charlie = {
name: "Charlie",
sayHello: function () {
document.write("My name is Charlie.");
}
};
charlie.sayHello();
var charlie = { name: "Charlie"};
function sayName() {
document.write("My name is Charlie.");
}
charlie.sayHello = sayName;
charlie.sayHello();
THIS
Inside methods, properties are accessed using
the this keyword.
this refers to the "owner" of the property.
var charlie = {
name: "Charlie",
sayHello: function () {
document.write("My name is " + this.name + ".");
}
};
var lucy = {
name: "Lucy van Pelt",
sayHello: function () {
document.write("My name is " + this.name + ".");
}
};
charlie.sayHello(); //My name is Charlie.
lucy.sayHello(); //My name is Lucy van Pelt.
LET'S DEVELOP IT
Add another button that calls the function
myFriends() on click.
Add a new function called myFriends to the
JavaScript.
In the function, create an array of friends
objects, with their names and hair colors.
Use a for loop to go through each friend and
describe them.
Write the results to the document.
Bonus -- make a separate functions that
describe the friends
LET'S ANSWER IT<button href = "#" onclick="myFriends()">My friends</button>
function myFriends(){
var friends = [
{name: 'Santa Claus',
hair: 'red'},
{name: 'Easter Bunny',
hair: 'brown'},
{name: 'Tooth Fairy',
hair: 'blue'}
];
var results = "My friends: "
for(var i = 0; i < friends.length; i++){
document.write("My friend " + friend[i].name + " has " + friend[i].hair + " hair. ");
}
}
LET'S ANSWER IT (BONUS)function myFriends(){
var friends = [
{name: 'Santa Claus',
hair: 'red'},
{name: 'Easter Bunny',
hair: 'brown'},
{name: 'Tooth Fairy',
hair: 'blue'}
];
var results = "My friends: "
for(var i = 0; i < friends.length; i++){
results += describeFriend(friends[i]);
}
document.write(results)
}
function describeFriend(friend){
return "My friend " + friend.name + " has " + friend.hair + " hair. ";
}
QUESTIONS?
?
GDI Seattle - Intro to JavaScript Class 2

Más contenido relacionado

La actualidad más candente

Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 

La actualidad más candente (18)

Scripting3
Scripting3Scripting3
Scripting3
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
Php array
Php arrayPhp array
Php array
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
MySQLConf2009: Taking ActiveRecord to the Next Level
MySQLConf2009: Taking ActiveRecord to the Next LevelMySQLConf2009: Taking ActiveRecord to the Next Level
MySQLConf2009: Taking ActiveRecord to the Next Level
 
Perl
PerlPerl
Perl
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Lodash js
Lodash jsLodash js
Lodash js
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
Python - Lecture 3
Python - Lecture 3Python - Lecture 3
Python - Lecture 3
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 

Destacado (8)

New cervical screening guidelines. 1
New cervical screening guidelines. 1New cervical screening guidelines. 1
New cervical screening guidelines. 1
 
Kuala Lumpur Hotels
Kuala Lumpur HotelsKuala Lumpur Hotels
Kuala Lumpur Hotels
 
GDI Seattle - Intermediate HTML and CSS Class 3 Slides
GDI Seattle - Intermediate HTML and CSS Class 3 SlidesGDI Seattle - Intermediate HTML and CSS Class 3 Slides
GDI Seattle - Intermediate HTML and CSS Class 3 Slides
 
GDI Seattle - Intro to JavaScript Class 1
GDI Seattle - Intro to JavaScript Class 1GDI Seattle - Intro to JavaScript Class 1
GDI Seattle - Intro to JavaScript Class 1
 
Pic pas demo
Pic pas demoPic pas demo
Pic pas demo
 
Nelson mandela
Nelson mandelaNelson mandela
Nelson mandela
 
GDI Seattle - Web Accessibility Class 1
GDI Seattle - Web Accessibility Class 1GDI Seattle - Web Accessibility Class 1
GDI Seattle - Web Accessibility Class 1
 
Prova origami
Prova origamiProva origami
Prova origami
 

Similar a GDI Seattle - Intro to JavaScript Class 2

Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
ARTDM 170, Week10: Arrays + Using Randomization
ARTDM 170, Week10: Arrays + Using RandomizationARTDM 170, Week10: Arrays + Using Randomization
ARTDM 170, Week10: Arrays + Using Randomization
Gilbert Guerrero
 
Artdm170 Week10 Arrays Math
Artdm170 Week10 Arrays MathArtdm170 Week10 Arrays Math
Artdm170 Week10 Arrays Math
Gilbert Guerrero
 

Similar a GDI Seattle - Intro to JavaScript Class 2 (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
JAVASCRIPT OBJECTS.pdf
JAVASCRIPT OBJECTS.pdfJAVASCRIPT OBJECTS.pdf
JAVASCRIPT OBJECTS.pdf
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)The Future of JavaScript (SXSW '07)
The Future of JavaScript (SXSW '07)
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Js types
Js typesJs types
Js types
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 
ARTDM 170, Week10: Arrays + Using Randomization
ARTDM 170, Week10: Arrays + Using RandomizationARTDM 170, Week10: Arrays + Using Randomization
ARTDM 170, Week10: Arrays + Using Randomization
 
Artdm170 Week10 Arrays Math
Artdm170 Week10 Arrays MathArtdm170 Week10 Arrays Math
Artdm170 Week10 Arrays Math
 
I, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 OverlordsI, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 Overlords
 

Más de Heather Rock (6)

GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
GDI Seattle Intro to HTML and CSS - Class 4
GDI Seattle Intro to HTML and CSS - Class 4GDI Seattle Intro to HTML and CSS - Class 4
GDI Seattle Intro to HTML and CSS - Class 4
 
GDI Seattle Intro to HTML and CSS - Class 3
GDI Seattle Intro to HTML and CSS - Class 3GDI Seattle Intro to HTML and CSS - Class 3
GDI Seattle Intro to HTML and CSS - Class 3
 
Intro to HTML and CSS - Class 2 Slides
Intro to HTML and CSS - Class 2 SlidesIntro to HTML and CSS - Class 2 Slides
Intro to HTML and CSS - Class 2 Slides
 
GDI Seattle Intermediate HTML and CSS Class 1
GDI Seattle Intermediate HTML and CSS Class 1GDI Seattle Intermediate HTML and CSS Class 1
GDI Seattle Intermediate HTML and CSS Class 1
 
GDI Seattle Intro to HTML and CSS - Class 1
GDI Seattle Intro to HTML and CSS - Class 1GDI Seattle Intro to HTML and CSS - Class 1
GDI Seattle Intro to HTML and CSS - Class 1
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

GDI Seattle - Intro to JavaScript Class 2

  • 2.
  • 3. WELCOME! Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction. Some "rules" We are here for you! Every question is important Help each other Have fun
  • 4. ARRAY An array is a data-type that holds an ordered list of values, of any type: The length property reports the size of the array: var arrayName = [element0, element1, ...]; var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']; var favoriteNumbers = [16, 27, 88]; var luckyThings = ['Rainbows', 7, 'Horseshoes']; console.log(rainbowColors.length);
  • 5. ARRAYS -- RETURNING VALUES You can access items with "bracket notation". The number inside the brackets is called an "index" Arrays in JavaScript are "zero-indexed", which means we start counting from zero. var arrayItem = arrayName[indexNum]; var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']; var firstColor = rainbowColors[0]; var lastColor = rainbowColors[6];
  • 6. ARRAYS -- UPDATING VALUES You can also use bracket notation to change the item in an array: Or to add to an array: You can also use the push method (recommended): var awesomeAnimals = ['Corgis', 'Otters', 'Octopi']; awesomeAnimals[0] = 'Bunnies'; awesomeAnimals[4] = 'Corgis'; awesomeAnimals.push('Ocelots');
  • 7. LOOPS Sometimes you want to go through a piece of code multiple times Why? Showing a timer count down. Display the results of a search. Sort a list of values.
  • 8. THE WHILE LOOP The while loop tells JS to repeat statements while a condition is true: Review: '++' means increment by 1! If we forget x++, the loop will never end! while (expression) { // statements to repeat } var x = 0; while (x < 5) { console.log(x); x++; }
  • 9. THE FOR LOOP The for loop is a safer way of looping Less danger of an infinite loop. All conditions are at the top! for (initialize; condition; update) { // statements to repeat } for (var i = 0; i < 5; i++) { console.log(i); }
  • 10. LOOPS AND ARRAYS Use a for loop to easily look at each item in an array: var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']; for (var i = 0; i < rainbowColors.length; i++) { console.log(rainbowColors[i]); }
  • 11. LET'S DEVELOP IT Add a new button to the exercise from last week. Add an onclick to the button for a function called favoriteThings(). Create a new function called favoriteThings() in the JavaScript file. In the function, create an array and loop through the results. Write the results to the document like: "My favorite things are: XX, YY, ZZ" Bonus -- add an 'and' in the sentence before the last item
  • 12. LET'S ANSWER IT<button type="button" onclick="favoriteThings()"> See my favorite things</button> function favoriteThings(){ var favoriteThings = ['Rabbits', 'Orange', 'Yogurt', 'Brussel Sprouts', 'Otters']; var result = 'My favorite things are: '; for (var i = 0; i < favoriteThings.length; i++) { result += favoriteThings[i] + ', '; } document.write(result); }
  • 13. LET'S ANSWER IT (BONUS)function favoriteThings(){ var favoriteThings = ['Rabbits', 'Orange', 'Yogurt', 'Brussel Sprouts', 'Otters']; var result = 'My favorite things are: '; for (var i = 0; i < favoriteThings.length; i++) { if (i < favoriteThings.length - 1) { result += favoriteThings[i] + ', '; } else { result += "and " + favoriteThings[i] + '.'; } } document.write(result); }
  • 14. OBJECTS Objects are a data type that let us store a collection of properties and methods. var objectName = { propertyName: propertyValue, propertyName: propertyValue, ... }; var charlie = { age: 8, name: "Charlie Brown", likes: ["baseball", "The little red-haired girl"], pet: "Snoopy" };
  • 15. OBJECTS -- RETURNING VALUES Access values of "properties" using "dot notation": var charlie = { age: 8, name: "Charlie Brown", likes: ["baseball", "The little red-haired girl"], pet: "Snoopy" }; var pet = charlie.pet;
  • 16. OBJECTS -- RETURNING VALUES Or using "bracket notation" (like arrays): Non-existent properties will return undefined: var name = charlie['name']; var gender = charlie.gender
  • 17. OBJECTS -- CHANGING VALUES Use dot or bracket notation with the assignment operator to change objects. Change existing properties: Or add new properties: You can also delete properties: charlie.name = "Chuck"; charlie.gender = "male"; delete charlie.gender;
  • 18. ARRAYS OF OBJECTS Arrays can hold objects too! That means we can use a for loop! var peanuts = [ {name: "Charlie Brown", pet: "Snoopy"}, {name: "Linus van Pelt", pet: "Blue Blanket"} ]; for (var i = 0; i < peanuts.length; i++) { var peanut = peanuts[i]; console.log(peanut.name + ' has a pet named ' + peanut.pet + '.'); }
  • 19. OBJECTS IN FUNCTIONS You can pass an object into a function as a parameter var peanut ={ name: "Charlie Brown", pet: "Snoopy" }; function describeCharacter(character){ console.log(character.name + ' has a pet named ' + character.pet + '.'); } describeCharacter(peanut);
  • 20. METHODS Methods are functions that are associated with an object The affect or return a value for a specific object Used with dot notation Previously seen example: document.write("Hello, world!");
  • 21. METHODS Methods can be added to objects in two ways. Declared with the object. Attached using dot notation. var charlie = { name: "Charlie", sayHello: function () { document.write("My name is Charlie."); } }; charlie.sayHello(); var charlie = { name: "Charlie"}; function sayName() { document.write("My name is Charlie."); } charlie.sayHello = sayName; charlie.sayHello();
  • 22. THIS Inside methods, properties are accessed using the this keyword. this refers to the "owner" of the property. var charlie = { name: "Charlie", sayHello: function () { document.write("My name is " + this.name + "."); } }; var lucy = { name: "Lucy van Pelt", sayHello: function () { document.write("My name is " + this.name + "."); } }; charlie.sayHello(); //My name is Charlie. lucy.sayHello(); //My name is Lucy van Pelt.
  • 23. LET'S DEVELOP IT Add another button that calls the function myFriends() on click. Add a new function called myFriends to the JavaScript. In the function, create an array of friends objects, with their names and hair colors. Use a for loop to go through each friend and describe them. Write the results to the document. Bonus -- make a separate functions that describe the friends
  • 24. LET'S ANSWER IT<button href = "#" onclick="myFriends()">My friends</button> function myFriends(){ var friends = [ {name: 'Santa Claus', hair: 'red'}, {name: 'Easter Bunny', hair: 'brown'}, {name: 'Tooth Fairy', hair: 'blue'} ]; var results = "My friends: " for(var i = 0; i < friends.length; i++){ document.write("My friend " + friend[i].name + " has " + friend[i].hair + " hair. "); } }
  • 25. LET'S ANSWER IT (BONUS)function myFriends(){ var friends = [ {name: 'Santa Claus', hair: 'red'}, {name: 'Easter Bunny', hair: 'brown'}, {name: 'Tooth Fairy', hair: 'blue'} ]; var results = "My friends: " for(var i = 0; i < friends.length; i++){ results += describeFriend(friends[i]); } document.write(results) } function describeFriend(friend){ return "My friend " + friend.name + " has " + friend.hair + " hair. "; }