310 likes | 464 Views
Intro to JavaScript. Anna Gerber. Programming is like writing a recipe…. Ingredients (values & variables). Directions (statements). Programming languages. Python. C. PHP. Ruby. Java. Lisp. C#. JavaScript. C++. Perl. Tools. Web Browser. Editor.
E N D
Intro to JavaScript Anna Gerber Intro to JavaScript
Programming is like writing a recipe… Ingredients (values & variables) Directions (statements) Intro to JavaScript
Programming languages Python C PHP Ruby Java Lisp C# JavaScript C++ Perl Intro to JavaScript
Tools Web Browser 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/ • We will use Google Chrome with built-in developer toolshttps://developers.google.com/chrome-developer-tools/ Intro to JavaScript
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) statements Intro to JavaScript
Values Intro to JavaScript • 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
Numeric operators Try evaluating some numeric expressions using the console Intro to JavaScript Addition: 5 + 3 Subtraction: 7 – 6 Multiplication: 5.3 * 2.7 Division: 20 / 4 Modulo: 8 % 2 Increment: 5++ Decrement: 2--
String operators Try it in the console! Intro to JavaScript • 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
Variables Intro to JavaScript Store a value with a name for reference elsewhere in the program Declaration: varmyVariable; Assignment statements: myVariable = true; Declaration and initial assignment: varx = 0; varmyString = "This is a string";
Assignment shorthands Experiment with variable declarations and assignment statements using the console Intro to JavaScript Shorthands for variable assignment include: +=-=*=/=%= x += 3 is equivalent to x = x + 3
Statements Intro to JavaScript 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)
Comments Intro to JavaScript // This is a comment until the end of this line only varaVariable = "Not a comment"; /* * This is a comment spanning several lines, * until the star slash */ // Use comments to disable/enable statements // varanotherVariable = "Disabled code";
Functions Intro to JavaScript 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 varmyCircumference = calculateCircumference(3);
Evaluating a function via the console Intro to JavaScript 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
Built-in libraries Experiment with these functions using the console Intro to JavaScript • 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
Comparison operators Intro to JavaScript • 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)
Boolean operators Intro to JavaScript • Combine boolean expressions using logical operators: • AND && • OR || • NOT !
Conditional statements Intro to JavaScript 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"); }
JSFiddle Intro to JavaScript Online editor and development environment, allows code to be saved and shared Great for prototyping
Exercise: Dice game Intro to JavaScript Using JSFiddle, write a function that generates a random number between 1 and 6 to simulate the toss of a dievardiceToss = 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/
Loops Intro to JavaScript While loop varmaxLimit = 20, counter = 0, value = 0; while (value != 6 && counter < maxLimit) { // ensure variables in loop condition can change } For loop for (vari = 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/
Exercise: Using the DOM Intro to JavaScript • 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/
Arrays Intro to JavaScript An ordered list of values varmyArray = [1,6,10]; varanotherArray = ["first value", 5, "third value", false]; // Access values – indexed from 0 myArray[0]// 1 mnotherArray[2] // "third value"
Objects Intro to JavaScript • Objects have • State (variables) • Behaviour (functions) • Many built-in types are objects e.g. Array, String varanArray = 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 varmyString = "here's a string" myString.length// 15 myString.split(" ") // ["here's", "a", "string"] myString.toUpperCase()// "HERE'S A STRING"
JavaScript Object Notation (JSON) Intro to JavaScript varmyMovies = [ { 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"] } ]
Including scripts using JSFiddle Intro to JavaScript 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/
Exercise: Working with maps Intro to JavaScript • We will use the leaflet library to create a map • Create a JSFiddle and include leafletJSandCSSfrom 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);
Exercise: Working with maps (continued) Intro to JavaScript • 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/
Exercise: Data Visualisation Data source:http://www.water.gov.au/WaterAvailability/Whatisourtotalwaterresource/Rainfalldistribution/index.aspx?Menu=Level1_3_1_2 Intro to JavaScript 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
Exercise: Data visualisation (continued) Intro to JavaScript 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/
Exercise: Data visualisation (continued) Intro to JavaScript • 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/