Anna Gerber Intro to JavaScript Programming is like writing a recipe Anna Gerber Intro to JavaScript Directions statements Ingredients values amp variables Programming languages Anna Gerber ID: 756052
Download Presentation The PPT/PDF document "Intro to JavaScript Anna Gerber" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Intro to JavaScript
Anna Gerber
Anna Gerber
Intro to JavaScriptSlide2
Programming is like writing a recipe…
Anna Gerber
Intro to JavaScript
Directions
(statements)
Ingredients
(values & variables)Slide3
Programming languages
Anna Gerber
Intro to JavaScript
Python
Ruby
Java
PHP
JavaScript
C
C++
C#
Lisp
PerlSlide4
Tools
Web Browser
We will use Google Chrome with built-in developer tools
https://developers.google.com/chrome-developer-tools/
Editor
JavaScript (JS) programs are stored in text files with .
js
file extension or embedded in HTML documents
Use your
favourite
text editor to create and edit JSWe will use Chrome's console and JSFiddle (online editor) http://jsfiddle.net/
Anna Gerber
Intro to JavaScriptSlide5
Console
Right-click in Chrome and select
Inspect Element
or select
View > Developer > Developer Tools
from the menu
Select the
Console
tab from the top of the developer tools panel
Type in and hit return to run (evaluate) statementsAnna Gerber
Intro to JavaScriptSlide6
Values
Numbers
Integers (whole numbers) e.g. 0, 1, 2, 3, 4Floats (fractional numbers) e.g. 3.14Strings
"A string of characters"
'This is also a string, but in single quotes'
"Escape quotes with backslash like this: \" ";
Booleans
true
false
Anna Gerber
Intro to JavaScriptSlide7
Numeric operators
Addition:
5 + 3Subtraction: 7 – 6
Multiplication:
5.3 * 2.7
Division:
20 / 4
Modulo:
8 % 2Increment: 5++Decrement:
2--Anna Gerber
Intro to JavaScript
Try evaluating some numeric expressions using the consoleSlide8
String operators
Concatenation
// Evaluates to "this is a concatenated string"
"this is " + "a concatenated string"
What happens if you add a number to a string?
"Here is a string with a number " + 7
Anna Gerber
Intro to JavaScript
Try it in the console!Slide9
Variables
Store a value with a name for reference elsewhere in the program
Declaration:
var
myVariable
;
Assignment statements:
myVariable
= true;Declaration and initial assignment:
var x
= 0;
var
myString
= "This is a string";
Anna GerberIntro to JavaScriptSlide10
Assignment
shorthands
Shorthands for variable assignment include:
+=
-=
*=
/=
%=
x
+= 3
is equivalent to x =
x
+ 3
Anna Gerber
Intro to JavaScript
Experiment with variable declarations and assignment statements using the consoleSlide11
Statements
Optionally separated by semi-colons
Use curly braces { } to group statements into blocks
var
radius = 3;
var
circumference = 2 *
Math.PI
* radius;
console.log("result is " + circumference)
Anna GerberIntro to JavaScriptSlide12
Comments
// This is a comment until the end of this line only
var
aVariable
= "Not a comment";
/*
* This is a comment spanning several lines,
* until the star slash
*/
// Use comments to disable/enable statements
//
var
anotherVariable
= "Disabled code";
Anna GerberIntro to JavaScriptSlide13
Functions
A block of statements that can be named and called
Can take parameters e.g. radiusCan perform an action or return a result (or both!)
function
calculateCircumference
(radius) {
var
circumference = 2 *
Math.PI
* radius; return circumference;
}
// The function is called elsewhere in the program, we pass in the value 3 for the radius
var
myCircumference
= calculateCircumference(3);Anna Gerber
Intro to JavaScriptSlide14
Evaluating a function via the console
Use the console to evaluate the
calculateCircumference function
We can call the function with different values and combine it with other statements
The console is great for experimenting however our code is lost when we restart the browser
Anna Gerber
Intro to JavaScriptSlide15
Built-in libraries
Math.PI
is a constant (a variable that never changes value) from the built-in Math library. Some additional Math functions:
Math.round(4.7)
Math.sqrt(9)
Math.max(1,5)
Math.min(6,7)
Math.floor(5.6)
Math.random
()console.log
() is a built-in function (in Chrome) that prints values to the console
Anna Gerber
Intro to JavaScript
Experiment with these functions using the consoleSlide16
Comparison operators
Expressions based on comparison operators evaluate to a
boolean:Equal:
3.5 == 2
// (evaluates to false)
Not equal:
"
aString
" != "anotherString"
// (true)Greater than / (or equal): 6 > 6 // (false)
6 >= 6 // (true)Less than / (or equal): 5 < 3
// (false)
5 <= 3
// (false)
Anna Gerber
Intro to JavaScriptSlide17
Boolean operators
Combine
boolean expressions using logical operators:AND
&&
OR
||
NOT
!
Anna Gerber
Intro to JavaScriptSlide18
Conditional statements
Implement alternative behaviours based on conditions
if (temperature < 20) {
console.log("It
is cold");
} else if (temperature >= 20 && temperature < 29) {
console.log("It
is warm");
} else {
console.log("it
is hot");
}
Anna Gerber
Intro to JavaScriptSlide19
JSFiddle
Online editor and development environment, allows code to be saved and shared
Great for prototyping
Anna Gerber
Intro to JavaScriptSlide20
Exercise: Dice game
Using
JSFiddle, write a function that generates a random number between 1 and 6 to simulate the toss of a die
var
diceToss
=
Math.floor(Math.random
() * 6 + 1);
If the number is 6, the game is won. Print a message to the console indicating whether the game was won or lost.
if (diceToss == 6) {
console.log("Hooray
, you won!");
...
Sample solution:
http://jsfiddle.net/AnnaGerber/epaAs/0/ Anna GerberIntro to JavaScriptSlide21
Loops
While loop
var
maxLimit
= 20, counter = 0, value = 0;
while (value != 6 && counter <
maxLimit
) {
// ensure variables in loop condition can change
}For loopfor (
var
i
= 0;
i
< 10; i++){ // print 0,1,2,3,4,5,6,7,8.9
console.log(i);}Update the dice game to keep rolling until the result is 6.Display the number of rolls it took to win.Sample solution: http://jsfiddle.net/AnnaGerber/epaAs/2/Anna GerberIntro to JavaScriptSlide22
Exercise: Using the DOM
We can access the HTML elements on a web page via the DOM (Document Object Model)
Modify the dice game to display the message on the HTML page instead of the console:Create a div element to display the result:
<div id="result"></div>
Update element content within the script:
document.getElementById('result').innerHTML
= ...
Sample solution:
http://jsfiddle.net/AnnaGerber/epaAs/1/
Anna Gerber
Intro to JavaScriptSlide23
Arrays
An ordered list of values
var
myArray
= [1,6,10];
var
anotherArray
= ["first value", 5, "third value", false];
// Access values – indexed from 0
myArray[0]
// 1
mnotherArray[2]
// "third value"
Anna GerberIntro to JavaScriptSlide24
Objects
Objects have
State (variables)Behaviour (functions)
Many built-in types are objects e.g. Array, String
var
anArray
= new Array()
anArray.push("red
") //
behaviour, anArray
is ["red"]
anArray.length
// state, it is 1
anArray.push("blue
") // anArray is ["red","blue
"]anArray.length // value of length is now 2var myString = "here's a string"myString.length
// 15myString.split(" ") // ["here's", "a", "string"]myString.toUpperCase() // "HERE'S A STRING"
Anna GerberIntro to JavaScriptSlide25
JavaScript Object Notation (JSON)
var
myMovies
= [
{
name: "The Hobbit",
year: "2013",
director: "Peter Jackson", stars: ["Ian
McKellen", "Martin Freeman", "Richard Armitage
"]},{ name: "Star Trek",
year: "2009",
director: "J. J. Abrams",
stars: ["Chris Pine", "Zachary
Quinto
", "Leonard
Nimoy", "Zoe Saldana"]}]Anna GerberIntro to JavaScriptSlide26
Including scripts using
JSFiddle
Developers often make use use of libraries or frameworks when developing web applicationsIn addition to code, Libraries and frameworks often provide a Cascading Style Sheet (CSS) to control the appearance of content created
In
JSFiddle
, we can select from a set of popular JS libraries under
Frameworks and Extensions
or link to arbitrary scripts or CSS files under
External ResourcesContent Distribution Networks provide hosted versions of many popular JS libraries and frameworks. We will use
http://cdnjs.com/
Anna Gerber
Intro to JavaScriptSlide27
Exercise: Working with maps
We will use the leaflet library to create a map
Create a JSFiddle and include leaflet
JS
and
CSS
from CDNJSAdd HTML element to contain the map <div style="width:100%;height:400px" id="map"></div>
Add JS to render the mapvar map = L.map('map').setView
([-27.48,153.02], // lat long for South Bank
14
// zoom level
);
// create tile layer using Open Street Map tiles
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png
').addTo(map);Anna Gerber
Intro to JavaScriptSlide28
Exercise: Working with maps (continued)
Add a marker:
L.marker([-27.48,153.02]).addTo(map)
.
bindPopup('South
Bank, Brisbane')
.
openPopup
();Explore the leaflet documentation for more options
http://leafletjs.com/reference.html
Sample solution: http://jsfiddle.net/AnnaGerber/hXxe4/
Anna Gerber
Intro to JavaScriptSlide29
Exercise: Data
Visualisation
We will use the Rickshaw charting library, based on the Data-Driven Documents (D3) framework, to draw a chart to visualise some data
Average rainfall in mm per year per state
Anna Gerber
Intro to JavaScript
Year
NSW
&
ACT
NT
QLD
SA
TAS
VIC
WA
2005498
4774782061250616306
20044936376102141223
5784632003484686
5182601227611388
Data source:http://www.water.gov.au/WaterAvailability/Whatisourtotalwaterresource/Rainfalldistribution/index.aspx?Menu=Level1_3_1_2Slide30
Exercise: Data
visualisation (continued)
Create a JSFiddle
based on the D3 framework
Add CDNJS links to external resources (Rickshaw JS and CSS) to the fiddle
Fork this
JSFiddle
containing the raw data in JSON format:
http://jsfiddle.net/AnnaGerber/zN8Eh/0/
Anna GerberIntro to JavaScriptSlide31
Exercise: Data
visualisation (continued)
Create a Graph object using the data:
var
graph = new
Rickshaw.Graph
( {
// attach the graph to the chart element
element: document.querySelector("#chart"),
// render as a stacked area chart renderer: 'area',
series:
chartData
});
graph.render
();
Look at the Rickshaw docs to find out how to customize the graph e.g add hover tips, legend:http://code.shutterstock.com/rickshaw/
Sample solution: http://jsfiddle.net/AnnaGerber/zN8Eh/1/ Anna GerberIntro to JavaScript