Intro to JavaScript

Report
Intro to JavaScript
Anna Gerber
Intro to JavaScript
Anna Gerber
Programming is like writing a recipe…
Ingredients
(values &
variables)
Directions
(statements)
Intro to JavaScript
Anna Gerber
Programming languages
Intro to JavaScript
Anna Gerber
Tools
Web Browser
• We will use Google
Chrome with built-in
developer tools
https://developers.goog
le.com/chromedeveloper-tools/
Intro to JavaScript
Anna Gerber
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 JS
• We will use Chrome's
console and JSFiddle
(online editor)
http://jsfiddle.net/
Console
• Right-click in Chrome
and select Inspect
Element or select
View > Developer >
Developer Tools
from the menu
Intro to JavaScript
Anna Gerber
• Select the Console tab
from the top of the
developer tools panel
• Type in and hit return to
run (evaluate)
statements
Values
• Numbers
– Integers (whole numbers) e.g. 0, 1, 2, 3, 4
– Floats (fractional numbers) e.g. 3.14
• Strings
– "A string of characters"
– 'This is also a string, but in single quotes'
– "Escape quotes with backslash like this: \" ";
• Booleans
– true
– false
Intro to JavaScript
Anna Gerber
Numeric operators
•
•
•
•
•
•
•
Addition: 5 + 3
Subtraction: 7 – 6
Multiplication: 5.3 * 2.7
Division: 20 / 4
Modulo: 8 % 2
Increment: 5++
Decrement: 2--
Intro to JavaScript
Anna Gerber
Try evaluating
some numeric
expressions
using the console
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
Try it in the
console!
Intro to JavaScript
Anna Gerber
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";
Intro to JavaScript
Anna Gerber
Assignment shorthands
Shorthands for variable assignment include:
+=
-=
Experiment with
variable
*=
declarations and
/=
assignment
statements using
%=
the console
x += 3
is equivalent to
x = x + 3
Intro to JavaScript
Anna Gerber
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)
Intro to JavaScript
Anna Gerber
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";
Intro to JavaScript
Anna Gerber
Functions
• A block of statements that can be named and called
• Can take parameters e.g. radius
• Can 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);
Intro to JavaScript
Anna Gerber
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
Intro to JavaScript
Anna Gerber
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()
Experiment with
these functions
using the console
• console.log() is a built-in function (in Chrome)
that prints values to the console
Intro to JavaScript
Anna Gerber
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)
Intro to JavaScript
Anna Gerber
Boolean operators
• Combine boolean expressions using logical
operators:
– AND
&&
– OR
||
– NOT
!
Intro to JavaScript
Anna Gerber
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");
}
Intro to JavaScript
Anna Gerber
JSFiddle
• Online editor and development environment,
allows code to be saved and shared
• Great for prototyping
Intro to JavaScript
Anna Gerber
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/
Intro to JavaScript
Anna Gerber
Loops
While loop
var maxLimit = 20, counter = 0, value = 0;
while (value != 6 && counter < maxLimit) {
// ensure variables in loop condition can change
}
For loop
for (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/
Intro to JavaScript
Anna Gerber
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/
Intro to JavaScript
Anna Gerber
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"
Intro to JavaScript
Anna Gerber
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 2
var myString = "here's a string"
myString.length // 15
myString.split(" ") // ["here's", "a", "string"]
myString.toUpperCase() // "HERE'S A STRING"
Intro to JavaScript
Anna Gerber
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"]
}
]
Intro to JavaScript
Anna Gerber
Including scripts using JSFiddle
• Developers often make use use of libraries or
frameworks when developing web applications
• In 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 Resources
• Content Distribution Networks provide hosted
versions of many popular JS libraries and
frameworks. We will use http://cdnjs.com/
Intro to JavaScript
Anna Gerber
Exercise: Working with maps
• We will use the leaflet library to create a map
• Create a JSFiddle and include leaflet JS and
CSS from CDNJS
• Add HTML element to contain the map
<div style="width:100%;height:400px" id="map"></div>
• Add JS to render the map
var 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);
Intro to JavaScript
Anna Gerber
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/
Intro to JavaScript
Anna Gerber
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
NSW &
Year ACT
2005 498
NT
477
QLD
478
SA
206
TAS
1250
VIC
616
WA
306
2004 493
637
610
214
1223
578
463
2003 484
686
518
260
1227
611
388
Data
source:http://www.water.gov.au/WaterAvailability/Whatisourtotalwaterresourc
e/Rainfalldistribution/index.aspx?Menu=Level1_3_1_2
Intro to JavaScript
Anna Gerber
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/
Intro to JavaScript
Anna Gerber
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/
Intro to JavaScript
Anna Gerber

similar documents