SlideShare a Scribd company logo
JavaScript,
INTRODUCTIONTOJS.
DATA TYPESIN JS
VARIABLEDECLARATION
ARITHMATICOPERATORS
CONDITIONALSTATEMENTS
DATA TYPECONVERSIONS
Web Server Database ServerTime
Apache
PHP
MySql
Browser
JavaScri
pt
D
O
M Parse
Respons
e
ind.php P
D
O
Send
Request
http://www.wa4e.com/code/rrc/
About JavaScript
• IntroducedinNetscape in1995
• Developed by BrandonEich
• Named tomake use ofJava marketbuzz
• Standardizedtodayas ECMAScript
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>One Paragraph</p>
<script type="text/javascript">
document.write("<p>Hello World</p>")
</script>
<noscript>
Your browser doesn't support or has disabled JavaScript.
</noscript>
<p>Second Paragraph</p>
</body>
</html>
Low-Level Debugging
• When indoubt,youcan alwaysaddanalert() toyourJavaScript.
• The alert() functiontakes astringas a parameterandpauses theJavaScriptexecution
untilyoupress “OK”.
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>One Paragraph</p>
<script type="text/javascript">
alert("Here I am");
document.write("<p>Hello World</p>")
</script>
<noscript>
Your browser doesn't support or has disabled JavaScript.
</noscript>
<p>Second Paragraph</p>
</body>
</html>
IncludingJavaScript
Three Patterns:
• Inlinewithin thedocument
• As partofan event inanHTML tag
• Froma file
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>One Paragraph</p>
<p><a href="js-01.htm"
onclick="alert('Hi'); return false;">Click Me</a></p>
<p>Third Paragraph</p>
</body>
</html>
JavaScriptonatag
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>One Paragraph</p>
<script type="text/javascript" src="script.js">
</script>
<p>Third Paragraph</p>
</body>
</html>
script.js:
document.write("<p>Hello World</p>");
JavaScriptina separatefile
Syntax Errors
• As in anylanguage,wecan makesyntaxerrors
• Bydefault,browserssilently eat anykindofJavaScript error
• Butthe code stopsrunningin thatfileorscript section
<p>One Paragraph</p>
<script type="text/javascript">
alert("I am broken');
alert("I am good");
</script>
<p>Two Paragraph</p>
<script type="text/javascript">
alert("Second time");
</script>
<p>Three Paragraph</p>
Seeing the Error
• Since theenduser really cannottakeanyactionto fixtheJavaScriptcoming as partofa
webpage,thebrowsereats theerrors.
• As developers, weneed tolook forthe errors -sometimes it takesa minute toeven
remember tocheck fora JSerror.
JavaScript Basics with baby steps
ConsoleLogging
• Debuggingusingalert() can get tiring- sometimes youwantto recordwhathappensin
casesomething goes wrong
• console.log("String") - andmanymorefunctions
Note: Requires recent browsers
<p>One Paragraph</p>
<script type="text/javascript">
console.log("First log");
alert("YO");
</script>
<p>Two Paragraph</p>
<script type="text/javascript">
console.log("Second log");
</script>
<p>Three Paragraph</p>
Console is Not AlwaysThere
Some browsers onlydefine theconsole if adebuggeris running.
window.console && console.log(...)
if (typeof console == "undefined") {
this.console = {log: function() {} }
}
http://stackoverflow.com/questions/3326650/console-is-undefined-error-for-internet-explorer
Using the Debugger (Chrome)
• Get intoa source view.
• Click ona line ofJavaScriptto set a breakpoint.
• Reload thepage.
JavaScript Basics with baby steps
JavaScriptLanguage
Comments in JavaScript = Awesome
// This is a comment
/* This is a section of
multiline comments that will
not be interpreted */
Statements
• White spaceandnewlines donot matter.
• Statementsendwith a semicolon ;
• There arecases whereyoucan leave the semicolon off,butdon’tbotherexploiting this
feature- just addsemicolons like inC,Java, PHP,C++,etc.
<p>One Paragraph</p>
<script type="text/javascript">
x = 3 +
5 * 4; console.log(
x);
</script>
<p>Second Paragraph</p>
Variable Names
• ValidCharacters: a-z, A-Z, 0-9, _ and$
• Mustnot startwith anumber
• Names are case sensitive
• Startingwitha dollarsign is considered“tacky”
String Constants
• DoubleorSingleQuotes -Singlequotes areused typicallyinJavaScript andwelet
HTML usedoublequotes tokeep ourminds alittlesane.
• Escaping- doneusingthe backslashcharacter
<script type="text/javascript">
alert('One linenTwoLine');
</script>
Numeric Constants
As youwouldexpect…
Operators
Assignment (side effect) Operators
Comparison Operators
LogicalOperators
String Concatenation
• JavaScriptstringconcatenationis like PythonandJava anduses “+”,versus PHP
which uses “.”
• Like thePHP“.”operator,it automaticallyconverts non-stringvalues tostringsas
needed.
Variable Typing
JavaScriptis aloosely typedlanguageanddoes automatictypeconversion when evaluating
expressions.
Variable Conversion
Ifastringcannotbeconverted toanumber,youendupwith“Not aNumber” or“NaN”. Itis a
value,butit is sticky -all operationswithNaN asa operandendupwithNaN.
Determining Type
JavaScriptprovides aunary typeofoperatorthatreturnsthe type ofa variableorconstantas a
string.
Functions
• Functions use atypicalsyntaxandare indicatedusingthe functionkeyword.
• The returnkeywordfunctions asexpected.
<script type="text/javascript">
function product(a,b) {
value = a + b;
return value;
}
console.log("Prod = "+product(4,5));
</script>
Scope - Global (default)
• Variablesdefinedoutsidea functionthatare referenced inside of afunctionhave
globalscope.
• This isa littledifferentthanwhatweexpect.
<script type="text/javascript">
gl = 123;
function check() {
gl = 456;
}
check();
window.console && console.log("GL = "+gl);
</script>
Making a Variable Local
Ina function,theparameters(formalarguments) arelocalandanyvariables we markwith
thevarkeywordarelocal too.
<script type="text/javascript">
gl = 123;
function check() {
var gl = 456;
}
check();
window.console && console.log("GL = "+gl);
</script>
Arrays
Arrays in JavaScript
JavaScriptsupportsbothlinear arraysand
associativestructures, butthe associative
structuresare actuallyobjects.
Linear Arrays
Array Constructor / Constants
ControlStructuresLite...
Control Structures
• Weuse curlybracesforcontrolstructure.
• Whitespace / line ends donot matter.
• if statements arelike PHP.
• while loops arelike PHP.
• Countedforloopsare like PHP– for( ; ; ) ...
• Inloops,breakandcontinue arelike PHP.
Definite Loops (for)
balls = {"golf": "Golf balls",
"tennis": "Tennis balls",
"ping": "Ping Pong balls"};
for (ball in balls) {
console.log(ball+' = '+balls[ball]);
}
js-12.htm
DOM
DocumentObjectModel
Web Server Database ServerTime
Apache
PHP
MySql
Browser
JavaScri
pt
D
O
M Parse
Respons
e
ind.php P
D
O
Send
Request
http://www.wa4e.com/code/rrc/
Document Object Model
• JavaScriptcan manipulatethe current HTML document.
• The “Document Object Model” tells us the syntaxtouse toaccess various “bits”of
the current screen toreadand/ormanipulate.
• You caneven findpieces ofthe model byidattributeandchangethem.
• Wecan read andwritetheDOM fromJavaScript.
http://en.wikipedia.org/wiki/Document_Object_Model
DOMs are Not Identical
• Not allbrowsers represent theirpageexactly thesame way.
• This makes it achallenge to keepallofyourJavaScript workingonallbrowsers.
• Italso means youneed totest yourcodeover andover on each browser.
• Aargh..
JavaScript Basics with baby steps
Using getElementById()
Inordernotto havetotraverse each uniqueDOM, weuse afunctioncall thatallbrowsers
support.This allows us tobypassthe DOM structureandjumpto aparticulartagwithin the
DOM andmanipulatethattag.
<p>
Hello <b><span id="person">Chuck</span></b> there.
</p>
<script type="text/javascript">
console.dir(document.getElementById('person'));
st = document.getElementById('person').innerHTML;
console.log("ST = "+st);
alert('Hi there ' + st);
document.getElementById('person').innerHTML = 'Joseph';
</script>
js-13.htm
console.dir(document.getElementById('person'));
Updating the Browser Document
<a href="#"
onclick="document.getElementById('stuff').innerHTML='BACK';return false;">
Back</a>
<a href="#"
onclick="document.getElementById('stuff').innerHTML='FORTH';return false;">
Forth</a>
</p>
<p>
Hello <b><span id="stuff">Stuff</span></b> there.
This is one reason whyyoucan only have
one id per document.
<p>
<a href="#" onclick="add();return false;">More</a>
</p>
<ul id="the-list">
<li>First Item</li>
</ul>
<script>
counter = 1;
console.log(document.getElementById('the-list'))
function add() {
var x = document.createElement('li');
x.className = "list-item";
x.innerHTML = "The counter is "+counter;
document.getElementById('the-list').appendChild(x);
counter++;
}
</script>
js-15.htm
JQuery tothe Rescue
• While the DOMs arenotparticularlyportable, and direct DOM manipulationis alittleclunky,
therearea number of JavaScriptframeworks thathandle themyriad of subtlediffereces
between browsers.
• WithJQuery, insteadof manipulatingtheDOM, we useJQuery functions andeverything works
much better...
http://jquery.org
Summary
• UsingJavaScript
• Syntaxerrors
• Debugging
• Languagefeatures
• Globalandlocal scope
• Arrays
• Controlstructures
• Document Object Model
• JQuery
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) as part of www.wa4e.com and made
available under a Creative Commons Attribution 4.0 License.
Please maintain this last slide in all copies of the document to
comply with the attribution requirements of the license. If you
make a change, feel free to add your name and organization
to the list of contributors on this page as you republish the
materials.
Initial Development: Charles Severance, University of
Michigan School of Information
Insert new Contributors and Translators here including names
and dates
ContinuenewContributorsandTranslatorshere

More Related Content

PDF
Ajax Security
PDF
Java script tutorial
PPT
Java script
PDF
HTML5: friend or foe (to Flash)?
PPT
Javascript and Jquery Best practices
PPTX
jQuery from the very beginning
PDF
How to make Ajax work for you
Ajax Security
Java script tutorial
Java script
HTML5: friend or foe (to Flash)?
Javascript and Jquery Best practices
jQuery from the very beginning
How to make Ajax work for you

What's hot (20)

PPTX
Java script Session No 1
PDF
Wt unit 4 server side technology-2
PPTX
Introduction to JavaScript
PDF
Building Advanced XSS Vectors
PPT
How to learn to build your own PHP framework
PDF
JavaScript-Core
PDF
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
PPTX
Introduction to Javascript By Satyen
PPTX
Javascript
PDF
The DOM is a Mess @ Yahoo
PDF
Workshop 6: Designer tools
PPT
Even Faster Web Sites at The Ajax Experience
PPTX
JavaScript Core fundamentals - Learn JavaScript Here
PDF
JavaScript Library Overview
PDF
A XSSmas carol
PDF
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
DOC
Basics java scripts
PDF
JavaScript guide 2020 Learn JavaScript
RTF
Java scripts
PDF
Polyglot payloads in practice by avlidienbrunn at HackPra
Java script Session No 1
Wt unit 4 server side technology-2
Introduction to JavaScript
Building Advanced XSS Vectors
How to learn to build your own PHP framework
JavaScript-Core
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
Introduction to Javascript By Satyen
Javascript
The DOM is a Mess @ Yahoo
Workshop 6: Designer tools
Even Faster Web Sites at The Ajax Experience
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Library Overview
A XSSmas carol
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Basics java scripts
JavaScript guide 2020 Learn JavaScript
Java scripts
Polyglot payloads in practice by avlidienbrunn at HackPra
Ad

Similar to JavaScript Basics with baby steps (20)

PPTX
Java script
PDF
Unit 4(it workshop)
PDF
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
PDF
Wt unit 2 ppts client side technology
PDF
Wt unit 2 ppts client sied technology
PPTX
Final Java-script.pptx
PPTX
Unit III.pptx IT3401 web essentials presentatio
PPTX
Java script.pptx v
PPTX
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
PDF
8.-Javascript-report powerpoint presentation
PDF
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
DOC
Java script by Act Academy
PDF
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
PPT
JAVA SCRIPT
PPTX
Java script
PPTX
concept of server-side JavaScript / JS Framework: NODEJS
PPTX
HNDIT1022 Week 08, 09 10 Theory web .pptx
PDF
Intro to mobile web application development
PPTX
Java script writing javascript
Java script
Unit 4(it workshop)
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
Wt unit 2 ppts client side technology
Wt unit 2 ppts client sied technology
Final Java-script.pptx
Unit III.pptx IT3401 web essentials presentatio
Java script.pptx v
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
8.-Javascript-report powerpoint presentation
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
Java script by Act Academy
CS8651- Unit 2 - JS.internet programming paper anna university -2017 regulation
JAVA SCRIPT
Java script
concept of server-side JavaScript / JS Framework: NODEJS
HNDIT1022 Week 08, 09 10 Theory web .pptx
Intro to mobile web application development
Java script writing javascript
Ad

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Approach and Philosophy of On baking technology
PDF
cuic standard and advanced reporting.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Monthly Chronicles - July 2025
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Modernizing your data center with Dell and AMD
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Cloud computing and distributed systems.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Big Data Technologies - Introduction.pptx
Electronic commerce courselecture one. Pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Approach and Philosophy of On baking technology
cuic standard and advanced reporting.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Monthly Chronicles - July 2025
“AI and Expert System Decision Support & Business Intelligence Systems”
Agricultural_Statistics_at_a_Glance_2022_0.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Modernizing your data center with Dell and AMD
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Digital-Transformation-Roadmap-for-Companies.pptx

JavaScript Basics with baby steps

Editor's Notes

  • #2: https://www.destroyallsoftware.com/talks/wat
  • #57: Note from Chuck. Please retain and maintain this page as you remix and republish these materials. Please add any of your own improvements or contributions.