SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Introduction to JavaScript
www.bbsydptraining.blogspot.com
JavaScript is the programming language of the Web.
All modern HTML pages are using JavaScript.
JavaScript is easy to learn.
Why Study JavaScript?
JavaScript is one of 3 languages all web
developers MUST learn:
HTML to define the content of web pages
CSS to specify the layout of web pages
JavaScript to program the behavior of web page
JavaScript is the most popular programming
language in the world.
It is the language for HTML, for the Web, for
computers, servers, laptops, tablets, smart
phones, and more.
This page contains some examples of what
JavaScript can do in HTML.
<html>
<body>
<h1>My First JavaScript</h1>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo">This is a demonstration.</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello
JavaScript!";}
</script>
</body>
</html>
JavaScript Can Change HTML Elements
The HTML DOM (the Document Object Model) is
the official W3C standard for accessing HTML
elements.
JavaScript can manipulate the DOM (change
HTML contents).
The following example changes the content
(innerHTML) of an HTML element identified with
id="demo":
Why talk about JavaScript?
Very widely used, and growing
Web pages, AJAX, Web 2.0
Increasing number of web-related applications
Some interesting and unusual features
First-class functions - interesting
Objects without classes - slightly unusual
Powerful modification capabilities - very unusual
Add new method to object, redefine prototype, access caller 

Many security, correctness issues
Not statically typed – type of variable may change 

Difficult to predict program properties in advance
JavaScript History
Developed by Brendan Eich at Netscape
Scripting language for Navigator 2
Later standardized for browser compatibility
ECMAScript Edition 3 (aka JavaScript 1.5)
Related to Java in name only
Name was part of a marketing deal
Various implementations available
Spidermonkey interactive shell interface
Rhino: http://www.mozilla.org/rhino/
Motivation for JavaScript
Netscape, 1995
Netscape > 90% browser market share
Opportunity to do “HTML scripting language”
Brendan Eich
I hacked the JS prototype in ~1 week in May
And it showed! Mistakes were frozen early
Rest of year spent embedding in browser
Common uses of JavaScript include:
Form validation
Page embellishments and special effects
Dynamic content manipulation
Emerging Web 2.0: client functionality implemented at client
- ICFP talk, 2006
Example 1: simple calculation
<html>


<p> 
 </p>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>


</html>
Example 2: browser events
<script type="text/JavaScript">
function whichButton(event) {
if (event.button==1) {
alert("You clicked the left mouse button!") }
else {
alert("You clicked the right mouse button!")
}}
</script>


<body onmousedown="whichButton(event)">


</body>
Mouse event causes
page-defined function
to be called
Other events: onLoad, onMouseMove, onKeyPress, onUnLoad
Example 3: page manipulation
Some possibilities
createElement(elementName)
createTextNode(text)
appendChild(newChild)
removeChild(node)
Example: Add a new list item:
var list = document.getElementById(‘list1')
var newitem = document.createElement('li')
var newtext = document.createTextNode(text)
list.appendChild(newitem)
newitem.appendChild(newtext)
This example uses the browser Document Object Model (DOM). For now,
we will focus on JavaScript as a language, not its use in the browser.
Design goals
Brendan Eich’s 2006 ICFP talk
Make it easy to copy/paste snippets of code
Tolerate “minor” errors (missing semicolons)
Simplified onclick, onmousedown, etc., event
handling, inspired by HyperCard
Pick a few hard-working, powerful primitives
First class functions for procedural abstraction
Objects everywhere, prototype-based
Leave all else out!
Language basics
JavaScript is case sensitive
HTML is not case sensitive; onClick, ONCLICK, 
 are
HTML
Statements terminated by returns or semi-colons (;)
x = x+1; same as x = x+1
Semi-colons can be a good idea, to reduce errors
“Blocks”
Group statements using { 
 }
Not a separate scope, unlike other languages (see later
slide)
Variables
Define a variable using the var statement
Define implicitly by its first use, which must be an
assignment
Implicit definition has global scope, even if it occurs in nested
Useful implementation
Spidermonkey command-line interpreter
Read-eval-print loop
Enter declaration or statement
Interpreter executes
Displays value
Returns to input state
Example
class web page has link to this implementation
JavaScript blocks
Use { } for grouping; not a separate scope
js> var x=3;
js> x
3
js> {var x=4; x}
4
js> x
4
Not blocks in the sense of other languages
Only function calls and the with statement cause a
change of scope
JavaScript primitive datatypes
Boolean
Two values: true and false
Number
64-bit floating point, similar to Java double and Double
No integer type
Special values NaN (not a number) and Infinity
String
Sequence of zero or more Unicode characters
No separate character type (just strings of length 1)
Literal strings using ' or " characters (must match)
Special values
null and undefined
typeof(null) = object; typeof(undefined)=undefined
Objects
An object is a collection of named properties
Simple view: hash table or associative array
Can define by set of name:value pairs
objBob = {name: “Bob", grade: 'A', level: 3};
New members can be added at any time
objBob.fullname = 'Robert';
Can have methods, can refer to this
Arrays, functions regarded as objects
A property of an object may be a function (=method)
A function defines an object with method called “( )”
function max(x,y) { if (x>y) return x; else return y;};
max.description = “return the maximum of two arguments”;
More about functions
Declarations can appear in function body
Local variables, “inner” functions
Parameter passing
Basic types passed by value, objects by reference
Call can supply any number of arguments
functionname.length : # of arguments in definition
functionname.arguments.length : # args in call
“Anonymous” functions (expressions for functions)
(function (x,y) {return x+y}) (2,3);
Closures and Curried functions
function CurAdd(x){ return function(y){return x+y} };
More explanation on next slide
Function Examples
Anonymous functions make great callbacks
setTimeout(function() { alert("done"); }, 10000)
Curried function
function CurriedAdd(x){ return function(y){ return x+y} };
g = CurriedAdd(2);
g(3)
Variable number of arguments
function sumAll() {
var total=0;
for (var i=0; i< sumAll.arguments.length; i++)
total+=sumAll.arguments[i];
return(total); }
sumAll(3,5,3,5,3,2,6)
Use of anonymous functions
Anonymous functions very useful for callbacks
setTimeout(function() { alert("done"); }, 10000)
// putting alert("done") in function delays evaluation until call
Simulate blocks by function definition and call
var u = { a:1, b:2 }
var v = { a:3, b:4 }
(function (x,y) {
var tempA = x.a; var tempB =x.b; //local variables
x.a=y.a; x.b=y.b;
y.a=tempA; y.b=tempB
}) (u,v)
// This works because objects are passed by reference
Detour: lambda calculus
Expressions
x + y x + 2*y + z
Functions
ïŹx. (x+y) ïŹz. (x + 2*y + z)
Application
(ïŹx. (x+y)) (3) = 3 + y
(ïŹz. (x + 2*y + z))(5) = x + 2*y + 5
Higher-Order Functions
Given function f, return function f  f
ïŹf. ïŹx. f (f x)
How does this work?
(ïŹf. ïŹx. f (f x)) (ïŹy. y+1)
= ïŹx. (ïŹy. y+1) ((ïŹy. y+1) x)
= ïŹx. (ïŹy. y+1) (x+1)
= ïŹx. (x+1)+1
In pure lambda calculus, ame result if step 2 is altered.
Same procedure, Lisp syntax
Given function f, return function f  f
(lambda (f) (lambda (x) (f (f x))))
How does this work?
((lambda (f) (lambda (x) (f (f x)))) (lambda (y) (+ y 1))
= (lambda (x) ((lambda (y) (+ y 1))
((lambda (y) (+ y 1)) x))))
= (lambda (x) ((lambda (y) (+ y 1)) (+ x 1))))
= (lambda (x) (+ (+ x 1) 1))
Same procedure, JavaScript syntax
Given function f, return function f  f
function (f) { return function (x) { return f(f(x)); }; }
How does this work?
(function (f) { return function (x) { return f(f(x)); }; )
(function (y) { return y +1; })
function (x) { return (function (y) { return y +1; })
((function (y) { return y + 1; }) (x)); }
function (x) { return (function (y) { return y +1; }) (x + 1); }
function (x) { return ((x + 1) + 1); }
Basic object features
Use a function to construct an object
function car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Objects have prototypes, can be changed
var c = new car(“Ford”,”Taurus”,1988);
car.prototype.print = function () {
return this.year + “ “ + this.make + “ “ + this.model;}
c.print();
JavaScript functions and this
var x = 5; var y = 5;
function f() {return this.x + y;}
var o1 = {x : 10}
var o2 = {x : 20}
o1.g = f; o2.g = f;
o1.g()
15
o2.g()
25
Both o1.g and o2.g refer to the same function object
Why are the results for o1.g() and o2.g() different ?
More about this
Property of the activation object for fctn call
In most cases, this points to the object which has
the function as a property (or method).
Example :
var o = {x : 10, f : function(){return this.x}}
o.f();
10
this is resolved dynamically when the method is
executed
Special treatment for nested methods
var o = { x: 10
f : function() {
function g(){ return this.x } ;
return g();
}
};
o.f()
Function g gets the global object as its this property !
Language features in CS242
Stack memory management
Parameters, local variables in activation records
Garbage collection
Automatic reclamation of inaccessible memory
Closures
Function together with environment (global variables)
Exceptions
Jump to previously declared location, passing values
Object features
Dynamic lookup, Encapsulation, Subtyping, Inheritance
Concurrency
Do more than one task at a time (JavaScript is single-threaded)
Stack memory management
Local variables in activation record of function
function f(x) {
var y = 3;
function g(z) { return y+z;};
return g(x);
}
var x= 1; var y =2;
f(x) + y;
Garbage collection
Automatic reclamation of unused memory
Navigator 2: per page memory management
Reclaim memory when browser changes page
Navigator 3: reference counting
Each memory region has associated count
Count modified when pointers are changed
Reclaim memory when count reaches zero
Navigator 4: mark-and-sweep, or equivalent
Garbage collector marks reachable memory
Sweep and reclaim unreachable memory
Reference http://www.unix.org.ua/orelly/web/jscript/ch11_07.html
Discuss garbage collection in connection with Lisp
Closures
Return a function from function call
function f(x) {
var y = x;
return function (z){y += z; return y;}
}
var h = f(5);
h(3);
Can use this idea to define objects with “private” fields
Description of technique
http://www.crockford.com/JavaScript/private.html
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Workin
g_with_Closures
But there are subtleties (look for __parent__)
Exceptions
Throw an expression of any type
throw "Error2";
throw 42;
throw {toString: function() { return "I'm an object!"; } };
Catch
try {
} catch (e if e == “FirstException") { // do something
} catch (e if e == “SecondException") { // do something else
} catch (e){ // executed if no match above
}
Reference: http://developer.mozilla.org/en/docs/
Core_JavaScript_1.5_Guide :Exception_Handling_Statements
Object features
Dynamic lookup
Method depends on run-time value of object
Encapsulation
Object contains private data, public operations
Subtyping
Object of one type can be used in place of another
Inheritance
Use implementation of one kind of object to implement
another kind of object
Concurrency
JavaScript itself is single-threaded
How can we tell if a language provides concurrency?
AJAX provides a form of concurrency
Create XMLHttpRequest object, set callback function
Call request method, which continues asynchronously
Reply from remote site executes callback function
Event waits in event queue

Closures important for proper execution of callbacks
Another form of concurrency
use SetTimeout to do cooperative multi-tasking
Maybe we will explore this in homework 

JavaScript eval
Evaluate string as code
The eval function evaluates a string of JavaScript code, in
scope of the calling code
Examples
var code = "var a = 1";
eval(code); // a is now '1‘
var obj = new Object();
obj.eval(code); // obj.a is now 1
Most common use
Efficiently deserialize a large, complicated JavaScript data
structures received over network via XMLHttpRequest
What does it cost to have eval in the language?
Can you do this in C? What would it take to implement?
Unusual features of JavaScript
Some built-in functions
Eval, Run-time type checking functions, 

Regular expressions
Useful support of pattern matching
Add, delete methods of an object dynamically
Seen examples adding methods. Do you like this? Disadvantages?
myobj.a = 5; myobj.b = 12; delete myobj.a;
Redefine native functions and objects (incl undefined)
Iterate over methods of an object
for (variable in object) { statements }
With statement (“considered harmful” – why??)
with (object) { statements }
Intro to Javascript

Weitere Àhnliche Inhalte

Was ist angesagt?

PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP FormsM.Zalmai Rahmani
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScriptBala Narayanan
 
3. Java Script
3. Java Script3. Java Script
3. Java ScriptJalpesh Vasa
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
Javascript
JavascriptJavascript
Javascriptmussawir20
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
 
Php string function
Php string function Php string function
Php string function Ravi Bhadauria
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
cascading style sheet ppt
cascading style sheet pptcascading style sheet ppt
cascading style sheet pptabhilashagupta
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHPMaruf Abdullah (Rion)
 
Java Script ppt
Java Script pptJava Script ppt
Java Script pptPriya Goyal
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handlerJesus Obenita Jr.
 

Was ist angesagt? (20)

PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Javascript
JavascriptJavascript
Javascript
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Java awt
Java awtJava awt
Java awt
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
 
Php string function
Php string function Php string function
Php string function
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
cascading style sheet ppt
cascading style sheet pptcascading style sheet ppt
cascading style sheet ppt
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Java loops
Java loopsJava loops
Java loops
 
jQuery
jQueryjQuery
jQuery
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 

Andere mochten auch

NodeJs Intro - JavaScript Zagreb Meetup #1
NodeJs Intro - JavaScript Zagreb Meetup #1NodeJs Intro - JavaScript Zagreb Meetup #1
NodeJs Intro - JavaScript Zagreb Meetup #1Tomislav Capan
 
Javascript intro for MAH
Javascript intro for MAHJavascript intro for MAH
Javascript intro for MAHAleksander Fabijan
 
JavaScript Intro
JavaScript IntroJavaScript Intro
JavaScript IntroEric Brown
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptKevin Ball
 
JavaScript - Intro
JavaScript - IntroJavaScript - Intro
JavaScript - IntroAnton Tibblin
 
Intro to Javascript and jQuery
Intro to Javascript and jQueryIntro to Javascript and jQuery
Intro to Javascript and jQueryShawn Calvert
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 

Andere mochten auch (10)

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
NodeJs Intro - JavaScript Zagreb Meetup #1
NodeJs Intro - JavaScript Zagreb Meetup #1NodeJs Intro - JavaScript Zagreb Meetup #1
NodeJs Intro - JavaScript Zagreb Meetup #1
 
Intro to javascript (4 week)
Intro to javascript (4 week)Intro to javascript (4 week)
Intro to javascript (4 week)
 
Javascript intro for MAH
Javascript intro for MAHJavascript intro for MAH
Javascript intro for MAH
 
JavaScript Intro
JavaScript IntroJavaScript Intro
JavaScript Intro
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript - Intro
JavaScript - IntroJavaScript - Intro
JavaScript - Intro
 
Intro to Javascript and jQuery
Intro to Javascript and jQueryIntro to Javascript and jQuery
Intro to Javascript and jQuery
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 

Ähnlich wie Intro to Javascript

Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5team11vgnt
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsZohar Arad
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real menIvano Malavolta
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptxMuqaddarNiazi1
 
Javascript
JavascriptJavascript
JavascriptorestJump
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScriptIvano Malavolta
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java ScriptMichael Girouard
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Alberto Naranjo
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript BasicsMats Bryntse
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webpjcozzi
 

Ähnlich wie Intro to Javascript (20)

Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
JavaScript
JavaScriptJavaScript
JavaScript
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Javascript
JavascriptJavascript
Javascript
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 

Mehr von Anjan Banda

Seo tutorial
Seo tutorialSeo tutorial
Seo tutorialAnjan Banda
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to phpAnjan Banda
 
Website Networking
Website Networking Website Networking
Website Networking Anjan Banda
 
crisis-in-textile-industry
crisis-in-textile-industrycrisis-in-textile-industry
crisis-in-textile-industryAnjan Banda
 
Genetic engineering
Genetic engineeringGenetic engineering
Genetic engineeringAnjan Banda
 
Android os
Android osAndroid os
Android osAnjan Banda
 
Body area-networks
Body area-networksBody area-networks
Body area-networksAnjan Banda
 
Woods Of Pakistan
Woods Of PakistanWoods Of Pakistan
Woods Of PakistanAnjan Banda
 

Mehr von Anjan Banda (9)

Seo tutorial
Seo tutorialSeo tutorial
Seo tutorial
 
Css3
Css3Css3
Css3
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Website Networking
Website Networking Website Networking
Website Networking
 
crisis-in-textile-industry
crisis-in-textile-industrycrisis-in-textile-industry
crisis-in-textile-industry
 
Genetic engineering
Genetic engineeringGenetic engineering
Genetic engineering
 
Android os
Android osAndroid os
Android os
 
Body area-networks
Body area-networksBody area-networks
Body area-networks
 
Woods Of Pakistan
Woods Of PakistanWoods Of Pakistan
Woods Of Pakistan
 

KĂŒrzlich hochgeladen

An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 

KĂŒrzlich hochgeladen (20)

An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 

Intro to Javascript

  • 2. JavaScript is the programming language of the Web. All modern HTML pages are using JavaScript. JavaScript is easy to learn. Why Study JavaScript? JavaScript is one of 3 languages all web developers MUST learn: HTML to define the content of web pages CSS to specify the layout of web pages JavaScript to program the behavior of web page
  • 3. JavaScript is the most popular programming language in the world. It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more. This page contains some examples of what JavaScript can do in HTML.
  • 4. <html> <body> <h1>My First JavaScript</h1> <p>JavaScript can change the content of an HTML element:</p> <button type="button" onclick="myFunction()">Click Me!</button> <p id="demo">This is a demonstration.</p> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello JavaScript!";} </script> </body> </html>
  • 5. JavaScript Can Change HTML Elements The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements. JavaScript can manipulate the DOM (change HTML contents). The following example changes the content (innerHTML) of an HTML element identified with id="demo":
  • 6. Why talk about JavaScript? Very widely used, and growing Web pages, AJAX, Web 2.0 Increasing number of web-related applications Some interesting and unusual features First-class functions - interesting Objects without classes - slightly unusual Powerful modification capabilities - very unusual Add new method to object, redefine prototype, access caller 
 Many security, correctness issues Not statically typed – type of variable may change 
 Difficult to predict program properties in advance
  • 7. JavaScript History Developed by Brendan Eich at Netscape Scripting language for Navigator 2 Later standardized for browser compatibility ECMAScript Edition 3 (aka JavaScript 1.5) Related to Java in name only Name was part of a marketing deal Various implementations available Spidermonkey interactive shell interface Rhino: http://www.mozilla.org/rhino/
  • 8. Motivation for JavaScript Netscape, 1995 Netscape > 90% browser market share Opportunity to do “HTML scripting language” Brendan Eich I hacked the JS prototype in ~1 week in May And it showed! Mistakes were frozen early Rest of year spent embedding in browser Common uses of JavaScript include: Form validation Page embellishments and special effects Dynamic content manipulation Emerging Web 2.0: client functionality implemented at client - ICFP talk, 2006
  • 9. Example 1: simple calculation <html> 
 <p> 
 </p> <script> var num1, num2, sum num1 = prompt("Enter first number") num2 = prompt("Enter second number") sum = parseInt(num1) + parseInt(num2) alert("Sum = " + sum) </script> 
 </html>
  • 10. Example 2: browser events <script type="text/JavaScript"> function whichButton(event) { if (event.button==1) { alert("You clicked the left mouse button!") } else { alert("You clicked the right mouse button!") }} </script> 
 <body onmousedown="whichButton(event)"> 
 </body> Mouse event causes page-defined function to be called Other events: onLoad, onMouseMove, onKeyPress, onUnLoad
  • 11. Example 3: page manipulation Some possibilities createElement(elementName) createTextNode(text) appendChild(newChild) removeChild(node) Example: Add a new list item: var list = document.getElementById(‘list1') var newitem = document.createElement('li') var newtext = document.createTextNode(text) list.appendChild(newitem) newitem.appendChild(newtext) This example uses the browser Document Object Model (DOM). For now, we will focus on JavaScript as a language, not its use in the browser.
  • 12. Design goals Brendan Eich’s 2006 ICFP talk Make it easy to copy/paste snippets of code Tolerate “minor” errors (missing semicolons) Simplified onclick, onmousedown, etc., event handling, inspired by HyperCard Pick a few hard-working, powerful primitives First class functions for procedural abstraction Objects everywhere, prototype-based Leave all else out!
  • 13. Language basics JavaScript is case sensitive HTML is not case sensitive; onClick, ONCLICK, 
 are HTML Statements terminated by returns or semi-colons (;) x = x+1; same as x = x+1 Semi-colons can be a good idea, to reduce errors “Blocks” Group statements using { 
 } Not a separate scope, unlike other languages (see later slide) Variables Define a variable using the var statement Define implicitly by its first use, which must be an assignment Implicit definition has global scope, even if it occurs in nested
  • 14. Useful implementation Spidermonkey command-line interpreter Read-eval-print loop Enter declaration or statement Interpreter executes Displays value Returns to input state Example class web page has link to this implementation
  • 15. JavaScript blocks Use { } for grouping; not a separate scope js> var x=3; js> x 3 js> {var x=4; x} 4 js> x 4 Not blocks in the sense of other languages Only function calls and the with statement cause a change of scope
  • 16. JavaScript primitive datatypes Boolean Two values: true and false Number 64-bit floating point, similar to Java double and Double No integer type Special values NaN (not a number) and Infinity String Sequence of zero or more Unicode characters No separate character type (just strings of length 1) Literal strings using ' or " characters (must match) Special values null and undefined typeof(null) = object; typeof(undefined)=undefined
  • 17. Objects An object is a collection of named properties Simple view: hash table or associative array Can define by set of name:value pairs objBob = {name: “Bob", grade: 'A', level: 3}; New members can be added at any time objBob.fullname = 'Robert'; Can have methods, can refer to this Arrays, functions regarded as objects A property of an object may be a function (=method) A function defines an object with method called “( )” function max(x,y) { if (x>y) return x; else return y;}; max.description = “return the maximum of two arguments”;
  • 18. More about functions Declarations can appear in function body Local variables, “inner” functions Parameter passing Basic types passed by value, objects by reference Call can supply any number of arguments functionname.length : # of arguments in definition functionname.arguments.length : # args in call “Anonymous” functions (expressions for functions) (function (x,y) {return x+y}) (2,3); Closures and Curried functions function CurAdd(x){ return function(y){return x+y} }; More explanation on next slide
  • 19. Function Examples Anonymous functions make great callbacks setTimeout(function() { alert("done"); }, 10000) Curried function function CurriedAdd(x){ return function(y){ return x+y} }; g = CurriedAdd(2); g(3) Variable number of arguments function sumAll() { var total=0; for (var i=0; i< sumAll.arguments.length; i++) total+=sumAll.arguments[i]; return(total); } sumAll(3,5,3,5,3,2,6)
  • 20. Use of anonymous functions Anonymous functions very useful for callbacks setTimeout(function() { alert("done"); }, 10000) // putting alert("done") in function delays evaluation until call Simulate blocks by function definition and call var u = { a:1, b:2 } var v = { a:3, b:4 } (function (x,y) { var tempA = x.a; var tempB =x.b; //local variables x.a=y.a; x.b=y.b; y.a=tempA; y.b=tempB }) (u,v) // This works because objects are passed by reference
  • 21. Detour: lambda calculus Expressions x + y x + 2*y + z Functions ïŹx. (x+y) ïŹz. (x + 2*y + z) Application (ïŹx. (x+y)) (3) = 3 + y (ïŹz. (x + 2*y + z))(5) = x + 2*y + 5
  • 22. Higher-Order Functions Given function f, return function f  f ïŹf. ïŹx. f (f x) How does this work? (ïŹf. ïŹx. f (f x)) (ïŹy. y+1) = ïŹx. (ïŹy. y+1) ((ïŹy. y+1) x) = ïŹx. (ïŹy. y+1) (x+1) = ïŹx. (x+1)+1 In pure lambda calculus, ame result if step 2 is altered.
  • 23. Same procedure, Lisp syntax Given function f, return function f  f (lambda (f) (lambda (x) (f (f x)))) How does this work? ((lambda (f) (lambda (x) (f (f x)))) (lambda (y) (+ y 1)) = (lambda (x) ((lambda (y) (+ y 1)) ((lambda (y) (+ y 1)) x)))) = (lambda (x) ((lambda (y) (+ y 1)) (+ x 1)))) = (lambda (x) (+ (+ x 1) 1))
  • 24. Same procedure, JavaScript syntax Given function f, return function f  f function (f) { return function (x) { return f(f(x)); }; } How does this work? (function (f) { return function (x) { return f(f(x)); }; ) (function (y) { return y +1; }) function (x) { return (function (y) { return y +1; }) ((function (y) { return y + 1; }) (x)); } function (x) { return (function (y) { return y +1; }) (x + 1); } function (x) { return ((x + 1) + 1); }
  • 25. Basic object features Use a function to construct an object function car(make, model, year) { this.make = make; this.model = model; this.year = year; } Objects have prototypes, can be changed var c = new car(“Ford”,”Taurus”,1988); car.prototype.print = function () { return this.year + “ “ + this.make + “ “ + this.model;} c.print();
  • 26. JavaScript functions and this var x = 5; var y = 5; function f() {return this.x + y;} var o1 = {x : 10} var o2 = {x : 20} o1.g = f; o2.g = f; o1.g() 15 o2.g() 25 Both o1.g and o2.g refer to the same function object Why are the results for o1.g() and o2.g() different ?
  • 27. More about this Property of the activation object for fctn call In most cases, this points to the object which has the function as a property (or method). Example : var o = {x : 10, f : function(){return this.x}} o.f(); 10 this is resolved dynamically when the method is executed
  • 28. Special treatment for nested methods var o = { x: 10 f : function() { function g(){ return this.x } ; return g(); } }; o.f() Function g gets the global object as its this property !
  • 29. Language features in CS242 Stack memory management Parameters, local variables in activation records Garbage collection Automatic reclamation of inaccessible memory Closures Function together with environment (global variables) Exceptions Jump to previously declared location, passing values Object features Dynamic lookup, Encapsulation, Subtyping, Inheritance Concurrency Do more than one task at a time (JavaScript is single-threaded)
  • 30. Stack memory management Local variables in activation record of function function f(x) { var y = 3; function g(z) { return y+z;}; return g(x); } var x= 1; var y =2; f(x) + y;
  • 31. Garbage collection Automatic reclamation of unused memory Navigator 2: per page memory management Reclaim memory when browser changes page Navigator 3: reference counting Each memory region has associated count Count modified when pointers are changed Reclaim memory when count reaches zero Navigator 4: mark-and-sweep, or equivalent Garbage collector marks reachable memory Sweep and reclaim unreachable memory Reference http://www.unix.org.ua/orelly/web/jscript/ch11_07.html Discuss garbage collection in connection with Lisp
  • 32. Closures Return a function from function call function f(x) { var y = x; return function (z){y += z; return y;} } var h = f(5); h(3); Can use this idea to define objects with “private” fields Description of technique http://www.crockford.com/JavaScript/private.html http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Workin g_with_Closures But there are subtleties (look for __parent__)
  • 33. Exceptions Throw an expression of any type throw "Error2"; throw 42; throw {toString: function() { return "I'm an object!"; } }; Catch try { } catch (e if e == “FirstException") { // do something } catch (e if e == “SecondException") { // do something else } catch (e){ // executed if no match above } Reference: http://developer.mozilla.org/en/docs/ Core_JavaScript_1.5_Guide :Exception_Handling_Statements
  • 34. Object features Dynamic lookup Method depends on run-time value of object Encapsulation Object contains private data, public operations Subtyping Object of one type can be used in place of another Inheritance Use implementation of one kind of object to implement another kind of object
  • 35. Concurrency JavaScript itself is single-threaded How can we tell if a language provides concurrency? AJAX provides a form of concurrency Create XMLHttpRequest object, set callback function Call request method, which continues asynchronously Reply from remote site executes callback function Event waits in event queue
 Closures important for proper execution of callbacks Another form of concurrency use SetTimeout to do cooperative multi-tasking Maybe we will explore this in homework 

  • 36. JavaScript eval Evaluate string as code The eval function evaluates a string of JavaScript code, in scope of the calling code Examples var code = "var a = 1"; eval(code); // a is now '1‘ var obj = new Object(); obj.eval(code); // obj.a is now 1 Most common use Efficiently deserialize a large, complicated JavaScript data structures received over network via XMLHttpRequest What does it cost to have eval in the language? Can you do this in C? What would it take to implement?
  • 37. Unusual features of JavaScript Some built-in functions Eval, Run-time type checking functions, 
 Regular expressions Useful support of pattern matching Add, delete methods of an object dynamically Seen examples adding methods. Do you like this? Disadvantages? myobj.a = 5; myobj.b = 12; delete myobj.a; Redefine native functions and objects (incl undefined) Iterate over methods of an object for (variable in object) { statements } With statement (“considered harmful” – why??) with (object) { statements }