SlideShare una empresa de Scribd logo
1 de 42
LESSON THREE
Javascript and the DOM
Fast Review
Data Types in Javascript


•   (1) Numbers

•   (2) Strings

•   (3) Booleans

•   (4) Functions

•   (5) Objects

•   (6) Undefined
FUNCTIONS


The ultimate DRY

Encapsulate common functionality
function name( arg_1, ... arg_n ) {

    [ FUNCTION BODY ]

}
CONTROL FLOW

if
     •   Execute some code if a certain condition pertains

for
     •   Execute some code a “definite” number of times

while
     •   Execute some code an “indefinite” number of times
CONTROL FLOW: if

if ( condition_1) {
    [ DO SOME STUFF ]
} else if ( condition_2 ) {
    [ DO SOME OTHER STUFF ]
} else {
    [ DO DEFAULT STUFF ]
}
CONTROL FLOW: for



for ( var i = 0; i < 10; i++ ) {
    [ DO SOME STUFF ]
}
// That stuff will happen 10 times
CONTROL FLOW: while


while ( [SOME CONDITION OBTAINS] ) {
    [ KEEP DOING STUFF ]
}
// That stuff will keep happening until
// the condition is false
Where do we code
  our javascript?
1. Webkit Console
2. JS Fiddle
3. In-line javascript
4. Include a .js file
5. In Node.js Terminal
JAVASCRIPT
[more on functions]
FUNCTIONS AS ARGUMENTS
In Javascript, functions can be passed as
arguments to other functions
  •   Relatedly, they can be returned by functions and stored as
      variables

  •   This is a very special and valuable feature of the language

  •   One says that functions are “first class objects”

  •   Javascript, in this way, treats functions like data


var say_hi =         function() {console.log(“hi”);};
say_hi(); // Prints “hi”
BUZZZZWORD




    “First class objects”
•    These are the “objects” in an “object-oriented” language (we will define
     “object oriented” later) that can be (1) saved in variables, (2) passed as
     arguments to functions, and (3) returned as values from functions
ANONYMOUS FUNCTIONS


Javascript conveniently allows you to define
functions “inline” without specifying a name
var kill_timeout = set_timeout(
 function() {
     console.log(“You are now 5 seconds older”);
 }, 5000); // Javascript tells time in milliseconds
RECURSIVE FUNCTIONS
In Javascript, functions can call themselves
 •   This is called “recursion”

 •   It must “bottom out” at the “base case” or it will never end (and
     you will run out of memory!)


function factorial(n) {
  if ( n == 0 ) {
     return 1; // Factorial of zero is one by definition
  } else {
     return n * factorial( n - 1 ); // Recursive step
  }
}
JAVASCRIPT
[data structures]
ARRAYS




   Javascript
  [data structures]
ARRAYS
A data structure native to Javascript that
stores values in an ordered way
 •   Arrays contain an arbitrary number of “elements” which can be
     accessed individually by “indexing” into the array

 •   Defined by comma separating values between brackets

 •   Arrays are “indexed” from zero (not from one)


var team = [‘ben’,‘jeff’,‘kam’];
team[0] // => ‘ben’
team[2] // => ‘kam’
team[3] // => undefined
OBJECTS




    Javascript
   [data structures]
BUZZZZWORD



“Object Oriented”
•   A way of structuring programming languages invented in the early
    90s

•   Data and functions (“methods”) are grouped together in “objects”

•   The outside world can interact with these objects only through a
    rigidly defined interface

•   Javascript is centered on objects, but not object oriented in the
    traditional sense
OBJECTS


Objects are collections of “properties”
 •   Properties are key / value pairs

 •   Defined using braces

 •   Use “dot” notation to read and write

var person = {};

person.name = ‘will’; // Write

var name = person.name;                 // Read
OBJECTS


Can also use “javascript object notation” to
get and set properties
var person = {};

person[ ‘name’ ] = ‘will’; // Write

var name = person[ ‘name’ ];      // Read
OBJECTS


Everything in Javascript is an object
 •   Therefore everything can have properties

 •   Some values have “built in” properties

var name = ‘will’;

name.length; // => 4

var team = [‘ben’, ‘jeff’, ‘kam’];

team.length; // => 3
OBJECTS


Functions stored as properties are called
“methods”
var team = [‘ben’, ‘jeff’];

team.push( ‘kam’ ); // => team[2] == ‘kam’

// Push is an Array method that adds a value to the end of an array
“this”

“this” is used to refer to an object inside the
body of a method
var person = {};
person.name = ‘will’;
person.say_name = function() {
    console.log( this.name );
}
person.say_name(); // => ‘will’
THEORY VS. PRACTICE

There is a fair amount of theory underlying
object orientation
For our practical purposes, at the moment
you need only understand what properties
are, and how to set (write) and get (read)
them
var obj = {};
obj.prop = ‘some_val’; // Setting
var val = obj.prop; // Getting
Document Object Model (DOM)
   [ how javascript interacts with page content ]




                                             Introduction
Document Object Model


•   HTML documents have hierarchy

•   every element has a parent

•   every parent thus has children
Document Object Model




The tree is made up of nodes and text
DOM Traversal: Node Links




             x.childNodes             x.parentNode
             x.firstChild             x.lastChild
             x.nextSibling            x.previousSibling




not enough for ya? https://github.com/spicyj/jquery-genealogy
Problem: Not Sustainable



document.firstChild.lastChild.previousSibling.firstChild.nextSibling.style.display = “none”


                                           VS.


               document.getElementById(“dummy”).style.display = “none”;
BUZZZZWORD




    SUSTAINABLE
•    Sustainable code retains its integrity and function over time.

•    It is invulnerable to external influence!
DOM Traversal: Attribute Selection




var my_box = document.getElementById(“my-unique-id”);



var my_links = document.getElementsByTagName(“A”);
Important Properties

x.innerHTML

   document.innerHTML(“<p> oh no! </p>”);
x.style

   document.body.style.marginTop(“30px”);
x.getAttribute(name)

   my_link.getAttribute(“href”); // => “http://www.hackyale.com”
x.setAttribute(name, value)

   my_link.setAttribute(“href”, “http://www.20b.org/”);
The ‘document’ Object



The document is a special object, with it’s
methods and properties.
PUTTING IT ALL TOGETHER



Let’s put cats on stuff
QUESTIONS?
contact will_and_bay@hackyale.com

Más contenido relacionado

La actualidad más candente

Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized军 沈
 
javascript
javascript javascript
javascript Kaya Ota
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLMohammad Shaker
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritancepedro.carvalho
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile applicationFabrizio Giudici
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript JourneyWanqiang Ji
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionMohammad Shaker
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptRangana Sampath
 

La actualidad más candente (20)

Prototype
PrototypePrototype
Prototype
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
javascript
javascript javascript
javascript
 
J query1
J query1J query1
J query1
 
J query
J queryJ query
J query
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance2012 oct-12 - java script inheritance
2012 oct-12 - java script inheritance
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
 
70 536
70 53670 536
70 536
 
Javascript Journey
Javascript JourneyJavascript Journey
Javascript Journey
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+Reflection
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java script
Java scriptJava script
Java script
 

Destacado (6)

week2
week2week2
week2
 
Week 1
Week 1Week 1
Week 1
 
Week 1
Week 1Week 1
Week 1
 
Week2
Week2Week2
Week2
 
Week 1 (v3)
Week 1 (v3)Week 1 (v3)
Week 1 (v3)
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Similar a Week3

AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfSreeVani74
 
JavaScript!
JavaScript!JavaScript!
JavaScript!RTigger
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMarlon Jamera
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Julie Meloni
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript WorkshopPamela Fox
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptCordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptBinu Paul
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuerycolinbdclark
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for DrupalSergey Semashko
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans Fabrizio Giudici
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptxMattMarino13
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptxMattMarino13
 

Similar a Week3 (20)

AJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdfAJS UNIT-1 2021-converted.pdf
AJS UNIT-1 2021-converted.pdf
 
JavaScript!
JavaScript!JavaScript!
JavaScript!
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)Learning About JavaScript (…and its little buddy, JQuery!)
Learning About JavaScript (…and its little buddy, JQuery!)
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Java script
Java scriptJava script
Java script
 
Cordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced JavascriptCordova training : Day 4 - Advanced Javascript
Cordova training : Day 4 - Advanced Javascript
 
User Interface Development with jQuery
User Interface Development with jQueryUser Interface Development with jQuery
User Interface Development with jQuery
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Tips for writing Javascript for Drupal
Tips for writing Javascript for DrupalTips for writing Javascript for Drupal
Tips for writing Javascript for Drupal
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 

Último

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Último (20)

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Week3

  • 1.
  • 4. Data Types in Javascript • (1) Numbers • (2) Strings • (3) Booleans • (4) Functions • (5) Objects • (6) Undefined
  • 5. FUNCTIONS The ultimate DRY Encapsulate common functionality function name( arg_1, ... arg_n ) { [ FUNCTION BODY ] }
  • 6. CONTROL FLOW if • Execute some code if a certain condition pertains for • Execute some code a “definite” number of times while • Execute some code an “indefinite” number of times
  • 7. CONTROL FLOW: if if ( condition_1) { [ DO SOME STUFF ] } else if ( condition_2 ) { [ DO SOME OTHER STUFF ] } else { [ DO DEFAULT STUFF ] }
  • 8. CONTROL FLOW: for for ( var i = 0; i < 10; i++ ) { [ DO SOME STUFF ] } // That stuff will happen 10 times
  • 9. CONTROL FLOW: while while ( [SOME CONDITION OBTAINS] ) { [ KEEP DOING STUFF ] } // That stuff will keep happening until // the condition is false
  • 10. Where do we code our javascript?
  • 14. 4. Include a .js file
  • 15. 5. In Node.js Terminal
  • 17. FUNCTIONS AS ARGUMENTS In Javascript, functions can be passed as arguments to other functions • Relatedly, they can be returned by functions and stored as variables • This is a very special and valuable feature of the language • One says that functions are “first class objects” • Javascript, in this way, treats functions like data var say_hi = function() {console.log(“hi”);}; say_hi(); // Prints “hi”
  • 18. BUZZZZWORD “First class objects” • These are the “objects” in an “object-oriented” language (we will define “object oriented” later) that can be (1) saved in variables, (2) passed as arguments to functions, and (3) returned as values from functions
  • 19. ANONYMOUS FUNCTIONS Javascript conveniently allows you to define functions “inline” without specifying a name var kill_timeout = set_timeout( function() { console.log(“You are now 5 seconds older”); }, 5000); // Javascript tells time in milliseconds
  • 20. RECURSIVE FUNCTIONS In Javascript, functions can call themselves • This is called “recursion” • It must “bottom out” at the “base case” or it will never end (and you will run out of memory!) function factorial(n) { if ( n == 0 ) { return 1; // Factorial of zero is one by definition } else { return n * factorial( n - 1 ); // Recursive step } }
  • 22. ARRAYS Javascript [data structures]
  • 23. ARRAYS A data structure native to Javascript that stores values in an ordered way • Arrays contain an arbitrary number of “elements” which can be accessed individually by “indexing” into the array • Defined by comma separating values between brackets • Arrays are “indexed” from zero (not from one) var team = [‘ben’,‘jeff’,‘kam’]; team[0] // => ‘ben’ team[2] // => ‘kam’ team[3] // => undefined
  • 24. OBJECTS Javascript [data structures]
  • 25. BUZZZZWORD “Object Oriented” • A way of structuring programming languages invented in the early 90s • Data and functions (“methods”) are grouped together in “objects” • The outside world can interact with these objects only through a rigidly defined interface • Javascript is centered on objects, but not object oriented in the traditional sense
  • 26. OBJECTS Objects are collections of “properties” • Properties are key / value pairs • Defined using braces • Use “dot” notation to read and write var person = {}; person.name = ‘will’; // Write var name = person.name; // Read
  • 27. OBJECTS Can also use “javascript object notation” to get and set properties var person = {}; person[ ‘name’ ] = ‘will’; // Write var name = person[ ‘name’ ]; // Read
  • 28. OBJECTS Everything in Javascript is an object • Therefore everything can have properties • Some values have “built in” properties var name = ‘will’; name.length; // => 4 var team = [‘ben’, ‘jeff’, ‘kam’]; team.length; // => 3
  • 29. OBJECTS Functions stored as properties are called “methods” var team = [‘ben’, ‘jeff’]; team.push( ‘kam’ ); // => team[2] == ‘kam’ // Push is an Array method that adds a value to the end of an array
  • 30. “this” “this” is used to refer to an object inside the body of a method var person = {}; person.name = ‘will’; person.say_name = function() { console.log( this.name ); } person.say_name(); // => ‘will’
  • 31. THEORY VS. PRACTICE There is a fair amount of theory underlying object orientation For our practical purposes, at the moment you need only understand what properties are, and how to set (write) and get (read) them var obj = {}; obj.prop = ‘some_val’; // Setting var val = obj.prop; // Getting
  • 32. Document Object Model (DOM) [ how javascript interacts with page content ] Introduction
  • 33. Document Object Model • HTML documents have hierarchy • every element has a parent • every parent thus has children
  • 34. Document Object Model The tree is made up of nodes and text
  • 35. DOM Traversal: Node Links x.childNodes x.parentNode x.firstChild x.lastChild x.nextSibling x.previousSibling not enough for ya? https://github.com/spicyj/jquery-genealogy
  • 36. Problem: Not Sustainable document.firstChild.lastChild.previousSibling.firstChild.nextSibling.style.display = “none” VS. document.getElementById(“dummy”).style.display = “none”;
  • 37. BUZZZZWORD SUSTAINABLE • Sustainable code retains its integrity and function over time. • It is invulnerable to external influence!
  • 38. DOM Traversal: Attribute Selection var my_box = document.getElementById(“my-unique-id”); var my_links = document.getElementsByTagName(“A”);
  • 39. Important Properties x.innerHTML document.innerHTML(“<p> oh no! </p>”); x.style document.body.style.marginTop(“30px”); x.getAttribute(name) my_link.getAttribute(“href”); // => “http://www.hackyale.com” x.setAttribute(name, value) my_link.setAttribute(“href”, “http://www.20b.org/”);
  • 40. The ‘document’ Object The document is a special object, with it’s methods and properties.
  • 41. PUTTING IT ALL TOGETHER Let’s put cats on stuff

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n