SlideShare a Scribd company logo
Week3
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

More Related Content

PDF
JavaScript - Chapter 8 - Objects
PPTX
Lecture 5: Client Side Programming 1
PPTX
Lecture 6: Client Side Programming 2
PDF
JavaScript Objects
PPTX
Functions and Objects in JavaScript
PPTX
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
PPT
Synapseindia object oriented programming in php
PPTX
JavsScript OOP
JavaScript - Chapter 8 - Objects
Lecture 5: Client Side Programming 1
Lecture 6: Client Side Programming 2
JavaScript Objects
Functions and Objects in JavaScript
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Synapseindia object oriented programming in php
JavsScript OOP

What's hot (20)

PDF
Prototype
PPTX
Javascript Prototype Visualized
PPTX
javascript
PPTX
J query1
PPT
J query
PPT
A Deeper look into Javascript Basics
PDF
C# Advanced L03-XML+LINQ to XML
KEY
2012 oct-12 - java script inheritance
PDF
Designing a JavaFX Mobile application
PDF
Javascript Journey
PPT
JavaScript Basics
PPTX
Javascript 101
PDF
javascript objects
PPT
jQuery Objects
PDF
jQuery -Chapter 2 - Selectors and Events
PDF
JavaScript - Chapter 12 - Document Object Model
PDF
CSharp Advanced L05-Attributes+Reflection
PPTX
Introduction to JavaScript
PPTX
Java script
Prototype
Javascript Prototype Visualized
javascript
J query1
J query
A Deeper look into Javascript Basics
C# Advanced L03-XML+LINQ to XML
2012 oct-12 - java script inheritance
Designing a JavaFX Mobile application
Javascript Journey
JavaScript Basics
Javascript 101
javascript objects
jQuery Objects
jQuery -Chapter 2 - Selectors and Events
JavaScript - Chapter 12 - Document Object Model
CSharp Advanced L05-Attributes+Reflection
Introduction to JavaScript
Java script
Ad

Viewers also liked (6)

KEY
KEY
KEY
KEY
KEY
Week 1 (v3)
PDF
Hype vs. Reality: The AI Explainer
Week 1 (v3)
Hype vs. Reality: The AI Explainer
Ad

Similar to Week3 (20)

KEY
JavaScript Neednt Hurt - JavaBin talk
PPTX
Awesomeness of JavaScript…almost
PPT
JavaScript Workshop
PPT
lecture 6 javascript event and event handling.ppt
PPT
JavaScript Needn't Hurt!
PPTX
All of Javascript
PPTX
Cordova training : Day 4 - Advanced Javascript
PDF
Handout - Introduction to Programming
PPT
JavaScript Tutorial
PDF
Fewd week5 slides
PPTX
Learning About JavaScript (…and its little buddy, JQuery!)
PPT
JavaScript - An Introduction
PPTX
All of javascript
PPTX
Front end fundamentals session 1: javascript core
PPTX
JavaScript Fundamentals & JQuery
PPTX
The JavaScript Programming Language
PPT
Javascript.ppt
PPTX
Java script
PPT
JavaScript Neednt Hurt - JavaBin talk
Awesomeness of JavaScript…almost
JavaScript Workshop
lecture 6 javascript event and event handling.ppt
JavaScript Needn't Hurt!
All of Javascript
Cordova training : Day 4 - Advanced Javascript
Handout - Introduction to Programming
JavaScript Tutorial
Fewd week5 slides
Learning About JavaScript (…and its little buddy, JQuery!)
JavaScript - An Introduction
All of javascript
Front end fundamentals session 1: javascript core
JavaScript Fundamentals & JQuery
The JavaScript Programming Language
Javascript.ppt
Java script

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Business Ethics Teaching Materials for college
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
Final Presentation General Medicine 03-08-2024.pptx
human mycosis Human fungal infections are called human mycosis..pptx
O7-L3 Supply Chain Operations - ICLT Program
Renaissance Architecture: A Journey from Faith to Humanism
Business Ethics Teaching Materials for college
STATICS OF THE RIGID BODIES Hibbelers.pdf
Institutional Correction lecture only . . .
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPH.pptx obstetrics and gynecology in nursing
Basic Mud Logging Guide for educational purpose
Week 4 Term 3 Study Techniques revisited.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
Pre independence Education in Inndia.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Module 4: Burden of Disease Tutorial Slides S2 2025
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf

Week3

  • 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

Editor's Notes