Slide 1

Slide 1 text

JavaScript From Novice To Ninja Friday, February 10, 2012

Slide 2

Slide 2 text

Agenda Key Concepts Core Types Syntax The Global Object & Scope Chain Function Objects Friday, February 10, 2012

Slide 3

Slide 3 text

JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tables Prototypical inheritance model Functions are regular objects (with a twist) Arrays are regular objects (with a twist) Friday, February 10, 2012

Slide 4

Slide 4 text

Hello JavaScript text = “Hello World”; console.log(text); DEFINE AND INITIALIZE A VARIABLE CALLED ‘TEXT’ WITH THE STRING “HELLO WORLD” CALL THE LOG FUNCTION FROM THE CONSOLE OBJECT ON THE VARIABLE ‘TEXT’ Friday, February 10, 2012

Slide 5

Slide 5 text

JavaScript Core Types Numbers Strings Booleans null undefined Objects Friday, February 10, 2012

Slide 6

Slide 6 text

Numbers JavaScript has only one number type called number number is a 64-bit floating point (double) Same arithmetical problems double have (0.1+0.2 ! =0.3) A special value NaN represents errors Friday, February 10, 2012

Slide 7

Slide 7 text

Numeric Functions Number(string) converts string to number returns NaN on error parseInt(string, radix) converts string to number tries its best (so '7hello' is OK) Math.random() returns a random between 0 and 1 Friday, February 10, 2012

Slide 8

Slide 8 text

Numeric Functions x = 3; y = Number(7); z = Number(‘9’); console.log(x + y + z); Friday, February 10, 2012

Slide 9

Slide 9 text

Numeric Functions Note that: Number(“9”) === parseInt(“9”) But ... Number(“09”) !== parseInt(“09”) Friday, February 10, 2012

Slide 10

Slide 10 text

Q & A Numbers Strings Booleans null undefined Objects Friday, February 10, 2012

Slide 11

Slide 11 text

Strings Strings are unicode 16-bit chars (like in Java). No char class. Characters are strings of length 1 Strings are immutable (like in Java) Both Single and Double quotes make a string Friday, February 10, 2012

Slide 12

Slide 12 text

String Examples 'hello'.length === 5 String(10).length === 2 'hello'.indexOf('l') === 2 'hello'.lastIndexOf('l')=== 3 'hello'.toUpperCase() === 'HELLO' Friday, February 10, 2012

Slide 13

Slide 13 text

Q & A Numbers Strings Booleans null undefined Objects Friday, February 10, 2012

Slide 14

Slide 14 text

Boolean Type JavaScript supports ‘true’ and ‘false’ as boolean values Boolean(value) is a function returning the truthness of a value returns false if value is falsy, and true if value is truthy !!value has the same meaning Friday, February 10, 2012

Slide 15

Slide 15 text

null represents the "nothing" of JavaScript usually used to mark errors JavaScript will not give null to a variable. It's always the result of an assignment performed on purpose Friday, February 10, 2012

Slide 16

Slide 16 text

undefined Not even the nothing JavaScript puts undefined in anything that hasn't yet been assigned a value Friday, February 10, 2012

Slide 17

Slide 17 text

JavaScript False/True These are all falsy: false, null, undefined “” (the empty string) 0, NaN Everything else is truthy Friday, February 10, 2012

Slide 18

Slide 18 text

Objects Everything else is an object An object is a collection of key/value pairs. Objects are fully dynamic, so new methods and fields can be added at runtime Objects have no classes Each object has a prototype. We'll talk about that later. Friday, February 10, 2012

Slide 19

Slide 19 text

Objects var me = { name : 'Ynon Perek', email : '[email protected]', web : 'http://ynonperek.com' }; name Ynon Perek email [email protected] web http://ynonperek.com Friday, February 10, 2012

Slide 20

Slide 20 text

Q & A Numbers Strings Booleans null undefined Objects Friday, February 10, 2012

Slide 21

Slide 21 text

Exercise Write a JS program that randomizes 3 numbers from 1 to 100, and prints their sum total Write a JS function that takes two values and returns their sum. If it got only one, it should return that number Friday, February 10, 2012

Slide 22

Slide 22 text

JavaScript Syntax Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Friday, February 10, 2012

Slide 23

Slide 23 text

JavaScript Identifiers Starts with a letter, an _, or a $ Followed by letters, digits, _ or $ Friday, February 10, 2012

Slide 24

Slide 24 text

Naming Conventions variable names are lowercased multiple words are separated by _ in variable names multiple words are camel cased in function names A constructor function starts with a captial Friday, February 10, 2012

Slide 25

Slide 25 text

Identifier Examples counter file_name function getName() function Person() Friday, February 10, 2012

Slide 26

Slide 26 text

JavaScript Reserved Words abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var volatile void while with Friday, February 10, 2012

Slide 27

Slide 27 text

JavaScript Comments // this is a valid line comment in Javascript /** * Java style multi line comments work well also * they are recommended for commenting on functions */ Friday, February 10, 2012

Slide 28

Slide 28 text

Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Friday, February 10, 2012

Slide 29

Slide 29 text

Loop Controls JavaScript has: while and do-while loops for loops for-in loops Friday, February 10, 2012

Slide 30

Slide 30 text

While Loop Syntax: while (expression) { statement; } Friday, February 10, 2012

Slide 31

Slide 31 text

Do-while Loop Syntax: Note the ending semicolon do { statement; } while (expression); Friday, February 10, 2012

Slide 32

Slide 32 text

For Loop Syntax: for ( initialize; test; increment) { statement; } Friday, February 10, 2012

Slide 33

Slide 33 text

For Example var riddle = 0; for ( var i=0; i < 10; ++i ) { riddle += i; } console.log(riddle); Friday, February 10, 2012

Slide 34

Slide 34 text

For-in loop allows iterating through all the properties of an object Be careful with this one - it yields wrong results when combined with inheritance Friday, February 10, 2012

Slide 35

Slide 35 text

Branches Syntax: if ( expression ) { } else if ( something_else ) { } else { } Friday, February 10, 2012

Slide 36

Slide 36 text

Exercise Write a JS that randomizes 3 number and prints the largest one Write a JS that prints the square-sum of all the numbers divisible by 7 in range 1..100 (1^2 + 7^2 + 14^2 + ...) Friday, February 10, 2012

Slide 37

Slide 37 text

Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Friday, February 10, 2012

Slide 38

Slide 38 text

Functions & Scope Outside all functions, variables have the “global” scope. This means a variable defined outside all functions is accessible from everywhere in the application Friday, February 10, 2012

Slide 39

Slide 39 text

Functions & Scope A function is an object that is callable (meaning we can apply it to arguments) In JavaScript, we have two ways to declare a function. Either as a named function or an anonymous function A function can return a value by using the return keyword Friday, February 10, 2012

Slide 40

Slide 40 text

Functions & Scope Inside a function, a variable can be scoped with the keyword var Using strict mode, all variables must be defined var This helps prevent bugs because we are less likely to mess with outside code Friday, February 10, 2012

Slide 41

Slide 41 text

Functions & Scope function sum(x, y) { return x+y; } console.log(sum(5, 7)); Friday, February 10, 2012

Slide 42

Slide 42 text

Functions & Scope var f = function(n) { return n * n; }; f(5) === 25; Friday, February 10, 2012

Slide 43

Slide 43 text

Functions & Scope Best Practices: Write all code inside a function block Use only one var statement at the beginning of that function Friday, February 10, 2012

Slide 44

Slide 44 text

Functions & Scope A function definition can appear “inside” another function This is called a “closure”, and then the inner function has access to all variables defined by the outer “closing” function It also keeps all variables alive Friday, February 10, 2012

Slide 45

Slide 45 text

Functions & Scope What is printed ? Why ? function Counter(max) { var val = 0; return function() { return (val < max) ? val++ : false; }; } var c = Counter(10); while (c()) { console.log(c()); } Friday, February 10, 2012

Slide 46

Slide 46 text

Functions Q & A Friday, February 10, 2012

Slide 47

Slide 47 text

Objects An object is a collection of key/value pairs Objects are instantiated using the object literal Properties stored in objects are fetched using the square bracket notation or the dot notation Friday, February 10, 2012

Slide 48

Slide 48 text

Objects var pos = { x : 50; y : 10 }; pos.move = function(dx, dy) { this.x += dx; this.y += dy; }; Friday, February 10, 2012

Slide 49

Slide 49 text

Objects Exercise Create a person object with three fields: name: your name favorite_color: your favorite color hello: a function that prints out your name and favorite color Friday, February 10, 2012

Slide 50

Slide 50 text

The this Keyword Inside a function, a special keyword named ‘this’ is used to determine the function calling context When a function was called as a method, this refers to the calling object Otherwise, this refers to the global object Friday, February 10, 2012

Slide 51

Slide 51 text

Arrays Arrays represent ordered data in JavaScript Arrays are normal objects, so they can have attributes other than their indexes Arrays have some array related functions we can use Friday, February 10, 2012

Slide 52

Slide 52 text

Arrays var arr = []; arr.push(1, 2, 3); // add data arr.pop(); // returns 3 arr[0] = 5; // changes array console.log(arr[2]); // value at Friday, February 10, 2012

Slide 53

Slide 53 text

Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Friday, February 10, 2012

Slide 54

Slide 54 text

Scope Chain Function var Closure var Global object attribute Friday, February 10, 2012

Slide 55

Slide 55 text

Scope Chain Example var x = 1; function f() { var y = 2; } function g() { var z = 3; } z : 3 y : 2 x : 1 CALL OBJECT OF G CALL OBJECT OF F GLOBAL OBJECT Friday, February 10, 2012

Slide 56

Slide 56 text

Function Scope The smallest scope in JS is the function scope A var inside a function creates an entry in the call object All entries in the call object are created when a function is called Friday, February 10, 2012

Slide 57

Slide 57 text

Global Scope In addition to function scopes, JavaScript has a global object that keeps all variables declared outside all scopes Use of this global scope should be kept to a minimum Friday, February 10, 2012

Slide 58

Slide 58 text

Scope Tips Wrap all code inside a function Use one var statement in the beginning of each function When global scope is required, create a private namespace on the global object Friday, February 10, 2012

Slide 59

Slide 59 text

JS File Template (function (global) { global.app = {}; global.app.hello = function() { console.log(“Hello World”); } global.app.hello(); }(this)); Friday, February 10, 2012

Slide 60

Slide 60 text

Q & A Key Concepts Core Types Syntax The Global Object & Scope Chain Function Objects Friday, February 10, 2012

Slide 61

Slide 61 text

Functions A block of JS code that is defined once, and may be executed (called) any number of times A function takes a list of arguments, and a special “this” argument A function always returns a value Friday, February 10, 2012

Slide 62

Slide 62 text

Defining Functions function factorial(n) { if ( n <= 1 ) { return 1; } return n * factorial(n-1); } Friday, February 10, 2012

Slide 63

Slide 63 text

Defining Functions function distance(p1, p2) { var dx = p2.x - p1.x; var dy = p2.y - p1.y; return Math.sqrt(dx*dx + dy*dy); } Friday, February 10, 2012

Slide 64

Slide 64 text

Invoking Functions Once a function is declared, it can be invoked by using the () operator on the function name or variable. Inside the (), specify any number of arguments that will be passed to the function. Does not have to be the same as in the declaration Friday, February 10, 2012

Slide 65

Slide 65 text

Invoking Functions console.log(factorial(5)); var start = {x : 10, y : 2}; var end = {x : 10, y : 50}; distance(start, end); distance(7); // what happens here? Friday, February 10, 2012

Slide 66

Slide 66 text

Invoking Functions All arguments specified in the function declaration that were not passed in the invocation are assigned ‘undefined’ Friday, February 10, 2012

Slide 67

Slide 67 text

Function Literals Functions are normal JS objects, so this: function foo() { } Is the same as: var foo = function() { }; Friday, February 10, 2012

Slide 68

Slide 68 text

Function Objects Treating functions as variables can clarify the two: Function Scope Passing Functions As Arguments Friday, February 10, 2012

Slide 69

Slide 69 text

Function Scope A function is scoped at the nearest closing scope (closure) or the global object It is best to avoid using global object scope Friday, February 10, 2012

Slide 70

Slide 70 text

Passing Functions As Arguments A function can be passed as an argument to another function - just like normal JS objects Use the normal () operator on the variable to execute Friday, February 10, 2012

Slide 71

Slide 71 text

Optional Arguments If a function got more arguments that were expected, the extra are not lost The special list arguments holds all the arguments that were passed in the invocation Tip: Do not modify values in that list Friday, February 10, 2012

Slide 72

Slide 72 text

Using Arguments function sum() { var sum = 0; for ( var i=0; i < arguments.length; ++i ) { sum += arguments[i]; } } sum(2, 3, 5); // returns 10 sum(7); // returns 7 Friday, February 10, 2012

Slide 73

Slide 73 text

Using Arguments function max() { var m = Number.NEGATIVE_INFINITY; for ( var i=0; i < arguments.length; ++i ) { if ( arguments[i] > m ) m = arguments[i]; } return m; } Friday, February 10, 2012

Slide 74

Slide 74 text

Exercise Modify the sum function so that when called with no arguments, will return 0 Write a function called filterArray that takes an array and a boolean function, and returns the list of all elements on which the boolean is true Friday, February 10, 2012

Slide 75

Slide 75 text

DOM Scripting Using JS To Manipulate the web page http://www.flickr.com/photos/jram23/3088840966/ Friday, February 10, 2012

Slide 76

Slide 76 text

The DOM Stands for Document Object Model Every HTML element has a JS object “bound” to it in a special bond HTMLDivElement HTML div JS Friday, February 10, 2012

Slide 77

Slide 77 text

The DOM Can use getElementById to find a specific element Can use getElementsByTagNam e to get all elements with a specified name

var t = document.getElementById('text'); t.innerHTML = "Hello World"; Friday, February 10, 2012

Slide 78

Slide 78 text

DOM Agenda jQuery Introduction Handling Events Writing a simple web app Friday, February 10, 2012

Slide 79

Slide 79 text

The Facts Every browser is different. Really. W3 Standard Webkit Mozilla Microsoft Friday, February 10, 2012

Slide 80

Slide 80 text

Ajax Libraries Developer tools that wrap common functionality and create a standard Many options to choose from. We’ll use jQuery Friday, February 10, 2012

Slide 81

Slide 81 text

jQuery Basics Wrap a normal DOM element inside a jQuery object All operations on the element are performed by jQuery Unified and cross browser API

$('p').html('hello jQUery'); Friday, February 10, 2012

Slide 82

Slide 82 text

jQuery Basics: Selectors Powerful element selection and manipulations Works “the same” for all mobile & desktop browsers

$('p#text').html("Hello World"); Selector returning a jQuery Object An action to perform on the object Friday, February 10, 2012

Slide 83

Slide 83 text

jQuery Actions Each jQuery object supports a wide range of functions to alter the elements $('div#foo').addClass('wide'); $('div#foo').removeClass('wide'); $('div#foo').css('background', 'red'); $('div#foo').hide(); $('div#foo').show(); Friday, February 10, 2012

Slide 84

Slide 84 text

jQuery Actions Example Zebra stripe a table using jQuery $('table tr:nth-child(2n)').css('background', '#ccc'); Friday, February 10, 2012

Slide 85

Slide 85 text

jQuery Events Define what to do when something happens in jQuery, “bind” a function to an event After the bind, every time the the event happens your callback is called, with the object as the “this” argument Friday, February 10, 2012

Slide 86

Slide 86 text

jQuery Events document.ready click hover keypress mousemove resize scroll select submit Full list: http:// api.jquery.com/ category/events/ Friday, February 10, 2012

Slide 87

Slide 87 text

jQuery Demo Build a red spotter game Game should present the user with 4 colored squares, only one is red User should click on the red square Friday, February 10, 2012

Slide 88

Slide 88 text

jQuery API Other useful methods: attr - change an attribute value css - change a style attribute html - change innerHTML content data - store arbitrary data inside an element Friday, February 10, 2012

Slide 89

Slide 89 text

jQuery Lab Write a web application that splits the screen into four sections. Each click on a section should display a sentence inside the clicked section Write a web app to convert time units. User should enter time in seconds, minutes or hours, and convert to all the others Use HTML5 Boilerplate and jQuery Friday, February 10, 2012

Slide 90

Slide 90 text

Q & A Friday, February 10, 2012

Slide 91

Slide 91 text

Thank You Ynon Perek [email protected] ynonperek.com Friday, February 10, 2012