SlideShare a Scribd company logo
adapted from slides by Alan Smith and Paweł Dorofiejczyk.
Web Information Systems - 2015
Client Side Programming 1
Javascript Introduction
Just an overview
1
Javascript Introduction
Javascript is
◦ A prototype-based scripting
language
◦ Dynamic
◦ Loosely typed
◦ Multi-Paradigm
▫ Object-Oriented
▫ Functional
▫ Imperative
Javascript Introduction
What’s it Good For?
◦ Web Apps (Client Side)
▫ Provides programmatic access to
certain browser features, your
page's elements, their properties,
and their styles
◦ Server Side
▫ node.js
◦ Databases
▫ MongoDB, CouchDB
Javascript Introduction
Anything Else?
◦ Scripting
▫ OpenOffice
▫ Adobe CS
 Photoshop
 Illustrator
 Dreamweaver
◦ Cross-Platform
▫ Enyo
▫ WinJS
Javascript Basics
How to use it
2
Javascript Basics
Local Variables
Introduce Variables with “var”
◦ var myString = “Hi”;
◦ var myNumber = 1;
◦ var myOtherNumber = 1.1;
◦ var myBoolean = true;
Don’t Create a
Variable Without
var!
This is a Global Variable Declaration.
Don’t do this!
Javascript Basics
Variable Types
typeof
◦ typeof “hi”; // string
Gotchas
◦ typeof []; // object
◦ typeof null; // object
◦ typeof NaN;// number
Javascript Basics
Functions
◦ Are objects
◦ Can be anonymous with reference
stored in a variable
▫ no name necessary
◦ Can create other functions
▫ try not to do this
◦ Are closures
▫ have there own scope
◦ Prototypes
▫ more on this later
Javascript Basics
Function Syntax
function foo() {
console.log(“hello world”);
}
is equivalent to the anonymous
var foo = function() {
console.log(“hello world”);
}
Javascript Basics
Function Args
Primitives
◦ always passed by value
Objects
◦ passed by reference
Javascript Basics
Function Args
var test = function(a, b, obj) {
obj.modified = true;
console.log(arguments);
}
var obj = {};
console.log(obj.modified); // undefined
test(1, 'a', obj);
// { '0': 1, '1': 'a', '2': { modified: true } }
console.log(obj.modified); // true
Javascript Basics
Function Scope
◦ Static (lexical)
◦ Created only by function
◦ Function arguments becomes part of
scope
◦ Child scope have reference to
parent scope (scope chain)
◦ this is not scope (!!!)
Javascript Basics
Function Scope
var accumulator = function(x) {
this.sum = (this.sum || 0) + x;
return this.sum;
}
console.log(accumulator(1)); //1
console.log(accumulator(1)); //2
console.log(accumulator.sum); //undefined
console.log(sum); // 2 !!!
Javascript Basics
Notes on “this”
}
var bar = function(x) {
this.x = x;
return this.x;
}
} ← this refers to the global scope by default
In the browser, “this” refers to window
Javascript Basics
Objects
◦ Dynamic
◦ non-ordered
◦ key-value pairs
◦ Array access or object access
◦ Iterable
◦ Created in runtime
◦ Object literal {}
◦ No privacy control at object level
◦ Prototypal inheritance
◦ Constructor functions
Javascript Basics
A Simple Object
◦ var obj = {};
A Little More
◦ var obj = {
name: “Simple Object”
}
Access via
◦ obj.name
◦ obj[“name”]
Javascript Basics
Special Operators
◦ “+” will also concat two strings
▫ 1 + 2 = 3 (as expected)
▫ “foo”+”bar” = “foobar”
◦ Unary “+” will change type
▫ +”1” = 1
◦ “===” and “!==” should be used
instead of “==” and “!=” as the former
will not attempt type conversion.
Javascript Basics
More Special Operators
◦ “&&” and “||” can be used outside of
conditionals for smaller, though less
readable code.
▫ “&&” will guard against null refs
 return obj && obj.name;
▫ “||” will let you assign values only if
they exist.
 var x = name || obj.name;
The Document Object Model
Javascript in the browser
3
The DOM
In the DOM, everything is a node:
◦ The document itself is a document node
◦ All HTML elements are element nodes
◦ All HTML attributes are attribute nodes
◦ Text inside HTML elements are text nodes
◦ Comments are comment nodes
w3Schools
The DOM
Programmatically access page
elements
Create new elements by:
◦ var paragraph = document.createElement('p');
◦ paragraph.id = 'content';
◦ paragraph.appendChild(document.createText
Node('Hello, world'));
Don’t forget to add the element to the DOM
◦ document.body.appendChild(paragraph);
The DOM
Manipulate them by:
Setting properties
◦ var element =
document.getElementById('content');
element.style.color = 'blue';
Calling methods
◦ var firstNode = document.body.childNodes[0];
document.body.removeChild(firstNode);
The DOM
Understanding the DOM is important…
But it is verbose, tedious, may not
behave as expected across browsers.
This leads to implementation and
maintainability issues.
Javascript Libraries
Usable Javascript in the browser
4
Javascript Libraries
Popular Libraries
◦ jQuery
◦ Underscore
◦ Backbone
◦ Angular
Let’s take a look at the difference...
Javascript
var element =
document.getElementById('content');
element.style.color = 'blue';
var firstNode =
document.body.childNodes[0];
document.body.removeChild(firstNode);
Javascript Libraries
JQuery
var element =$(“#content”);
element.css(“color”, “blue”);
or element.css({color:”blue”})
$(‘body:first-child’).remove();
Javascript Libraries
$ is the global jQuery object
◦ It has its own properties and methods
$ is also a function you can call
◦ $.getJSON('student-list.php');
Relies heavily upon the familiar CSS selector
syntax and the Composite design pattern
◦ $('.urgent').css({ backgroundColor: 'red', color:
'white' });
Javascript Libraries
Many methods are both getters and setters,
depending on the parameter(s), or lack thereof
Many of its functions return a jQuery object as
well, which allows method chaining
◦ $("p.neat").addClass("ohmy").show("slow");
Javascript Libraries
More advanced topics next time...
CREDITS
Special thanks to:
◦ Alan Smith
◦ Paweł Dorofiejczyk
▫ http://www.slideshare.net/PaweD
orofiejczyk/lets-
javascript?qid=35826bbe-211d-
4f50-ad02-29143c7efff2

More Related Content

What's hot (20)

php
phpphp
php
ajeetjhajharia
 
introduction to NOSQL Database
introduction to NOSQL Databaseintroduction to NOSQL Database
introduction to NOSQL Database
nehabsairam
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
Amit Tyagi
 
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
AakankshaR
 
Xml
XmlXml
Xml
Dr. C.V. Suresh Babu
 
Requirement specification (SRS)
Requirement specification (SRS)Requirement specification (SRS)
Requirement specification (SRS)
kunj desai
 
Asp net
Asp netAsp net
Asp net
Dr. C.V. Suresh Babu
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
valuebound
 
Web server architecture
Web server architectureWeb server architecture
Web server architecture
Tewodros K
 
Json
JsonJson
Json
Steve Fort
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
XML Schema
XML SchemaXML Schema
XML Schema
yht4ever
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering concepts
Komal Singh
 
Database security
Database securityDatabase security
Database security
MaryamAsghar9
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
Vb.net ide
Vb.net ideVb.net ide
Vb.net ide
Faisal Aziz
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
Tejaswini Deshpande
 
database
databasedatabase
database
Shwetanshu Gupta
 
REQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGREQUIREMENT ENGINEERING
REQUIREMENT ENGINEERING
Saqib Raza
 
Data Modeling PPT
Data Modeling PPTData Modeling PPT
Data Modeling PPT
Trinath
 
introduction to NOSQL Database
introduction to NOSQL Databaseintroduction to NOSQL Database
introduction to NOSQL Database
nehabsairam
 
Introduction to CSS
Introduction to CSSIntroduction to CSS
Introduction to CSS
Amit Tyagi
 
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
AakankshaR
 
Requirement specification (SRS)
Requirement specification (SRS)Requirement specification (SRS)
Requirement specification (SRS)
kunj desai
 
An intro to GraphQL
An intro to GraphQLAn intro to GraphQL
An intro to GraphQL
valuebound
 
Web server architecture
Web server architectureWeb server architecture
Web server architecture
Tewodros K
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
XML Schema
XML SchemaXML Schema
XML Schema
yht4ever
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering concepts
Komal Singh
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
Patrick Savalle
 
REQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGREQUIREMENT ENGINEERING
REQUIREMENT ENGINEERING
Saqib Raza
 
Data Modeling PPT
Data Modeling PPTData Modeling PPT
Data Modeling PPT
Trinath
 

Similar to Lecture 5: Client Side Programming 1 (20)

JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Marlon Jamera
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
Mithun T. Dhar
 
Java script
Java scriptJava script
Java script
Ramesh Kumar
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
Núcleo de Electrónica e Informática da Universidade do Algarve
 
JS basics
JS basicsJS basics
JS basics
Mohd Saeed
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
DHTMLExtreme
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
Asanka Indrajith
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
JavaScript
JavaScriptJavaScript
JavaScript
Ivano Malavolta
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
webworkers
webworkerswebworkers
webworkers
Asanka Indrajith
 
Week3
Week3Week3
Week3
Will Gaybrick
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
Java script
Java scriptJava script
Java script
Adrian Caetano
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
Java script
Java scriptJava script
Java script
Jay Patel
 
Ad

Recently uploaded (20)

Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
Module 4 Presentation - Enhancing Competencies and Engagement Strategies in Y...
GeorgeDiamandis11
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
Ad

Lecture 5: Client Side Programming 1

  • 1. adapted from slides by Alan Smith and Paweł Dorofiejczyk. Web Information Systems - 2015 Client Side Programming 1
  • 3. Javascript Introduction Javascript is ◦ A prototype-based scripting language ◦ Dynamic ◦ Loosely typed ◦ Multi-Paradigm ▫ Object-Oriented ▫ Functional ▫ Imperative
  • 4. Javascript Introduction What’s it Good For? ◦ Web Apps (Client Side) ▫ Provides programmatic access to certain browser features, your page's elements, their properties, and their styles ◦ Server Side ▫ node.js ◦ Databases ▫ MongoDB, CouchDB
  • 5. Javascript Introduction Anything Else? ◦ Scripting ▫ OpenOffice ▫ Adobe CS  Photoshop  Illustrator  Dreamweaver ◦ Cross-Platform ▫ Enyo ▫ WinJS
  • 7. Javascript Basics Local Variables Introduce Variables with “var” ◦ var myString = “Hi”; ◦ var myNumber = 1; ◦ var myOtherNumber = 1.1; ◦ var myBoolean = true;
  • 8. Don’t Create a Variable Without var! This is a Global Variable Declaration. Don’t do this!
  • 9. Javascript Basics Variable Types typeof ◦ typeof “hi”; // string Gotchas ◦ typeof []; // object ◦ typeof null; // object ◦ typeof NaN;// number
  • 10. Javascript Basics Functions ◦ Are objects ◦ Can be anonymous with reference stored in a variable ▫ no name necessary ◦ Can create other functions ▫ try not to do this ◦ Are closures ▫ have there own scope ◦ Prototypes ▫ more on this later
  • 11. Javascript Basics Function Syntax function foo() { console.log(“hello world”); } is equivalent to the anonymous var foo = function() { console.log(“hello world”); }
  • 12. Javascript Basics Function Args Primitives ◦ always passed by value Objects ◦ passed by reference
  • 13. Javascript Basics Function Args var test = function(a, b, obj) { obj.modified = true; console.log(arguments); } var obj = {}; console.log(obj.modified); // undefined test(1, 'a', obj); // { '0': 1, '1': 'a', '2': { modified: true } } console.log(obj.modified); // true
  • 14. Javascript Basics Function Scope ◦ Static (lexical) ◦ Created only by function ◦ Function arguments becomes part of scope ◦ Child scope have reference to parent scope (scope chain) ◦ this is not scope (!!!)
  • 15. Javascript Basics Function Scope var accumulator = function(x) { this.sum = (this.sum || 0) + x; return this.sum; } console.log(accumulator(1)); //1 console.log(accumulator(1)); //2 console.log(accumulator.sum); //undefined console.log(sum); // 2 !!!
  • 16. Javascript Basics Notes on “this” } var bar = function(x) { this.x = x; return this.x; } } ← this refers to the global scope by default In the browser, “this” refers to window
  • 17. Javascript Basics Objects ◦ Dynamic ◦ non-ordered ◦ key-value pairs ◦ Array access or object access ◦ Iterable ◦ Created in runtime ◦ Object literal {} ◦ No privacy control at object level ◦ Prototypal inheritance ◦ Constructor functions
  • 18. Javascript Basics A Simple Object ◦ var obj = {}; A Little More ◦ var obj = { name: “Simple Object” } Access via ◦ obj.name ◦ obj[“name”]
  • 19. Javascript Basics Special Operators ◦ “+” will also concat two strings ▫ 1 + 2 = 3 (as expected) ▫ “foo”+”bar” = “foobar” ◦ Unary “+” will change type ▫ +”1” = 1 ◦ “===” and “!==” should be used instead of “==” and “!=” as the former will not attempt type conversion.
  • 20. Javascript Basics More Special Operators ◦ “&&” and “||” can be used outside of conditionals for smaller, though less readable code. ▫ “&&” will guard against null refs  return obj && obj.name; ▫ “||” will let you assign values only if they exist.  var x = name || obj.name;
  • 21. The Document Object Model Javascript in the browser 3
  • 22. The DOM In the DOM, everything is a node: ◦ The document itself is a document node ◦ All HTML elements are element nodes ◦ All HTML attributes are attribute nodes ◦ Text inside HTML elements are text nodes ◦ Comments are comment nodes w3Schools
  • 23. The DOM Programmatically access page elements Create new elements by: ◦ var paragraph = document.createElement('p'); ◦ paragraph.id = 'content'; ◦ paragraph.appendChild(document.createText Node('Hello, world')); Don’t forget to add the element to the DOM ◦ document.body.appendChild(paragraph);
  • 24. The DOM Manipulate them by: Setting properties ◦ var element = document.getElementById('content'); element.style.color = 'blue'; Calling methods ◦ var firstNode = document.body.childNodes[0]; document.body.removeChild(firstNode);
  • 25. The DOM Understanding the DOM is important… But it is verbose, tedious, may not behave as expected across browsers. This leads to implementation and maintainability issues.
  • 27. Javascript Libraries Popular Libraries ◦ jQuery ◦ Underscore ◦ Backbone ◦ Angular Let’s take a look at the difference...
  • 28. Javascript var element = document.getElementById('content'); element.style.color = 'blue'; var firstNode = document.body.childNodes[0]; document.body.removeChild(firstNode); Javascript Libraries JQuery var element =$(“#content”); element.css(“color”, “blue”); or element.css({color:”blue”}) $(‘body:first-child’).remove();
  • 29. Javascript Libraries $ is the global jQuery object ◦ It has its own properties and methods $ is also a function you can call ◦ $.getJSON('student-list.php'); Relies heavily upon the familiar CSS selector syntax and the Composite design pattern ◦ $('.urgent').css({ backgroundColor: 'red', color: 'white' });
  • 30. Javascript Libraries Many methods are both getters and setters, depending on the parameter(s), or lack thereof Many of its functions return a jQuery object as well, which allows method chaining ◦ $("p.neat").addClass("ohmy").show("slow");
  • 31. Javascript Libraries More advanced topics next time...
  • 32. CREDITS Special thanks to: ◦ Alan Smith ◦ Paweł Dorofiejczyk ▫ http://www.slideshare.net/PaweD orofiejczyk/lets- javascript?qid=35826bbe-211d- 4f50-ad02-29143c7efff2