02 JavaScript Syntax

76
JavaScript Programming the WWW Saturday, December 15, 12

Transcript of 02 JavaScript Syntax

Page 1: 02 JavaScript Syntax

JavaScriptProgramming the WWW

Saturday, December 15, 12

Page 2: 02 JavaScript Syntax

Agenda

Key Concepts

Core Types

Syntax

The Global Object & Scope Chain

Function Objects

Saturday, December 15, 12

Page 3: 02 JavaScript Syntax

History1995 Brendan Eich started developing a new language for Netscape Navigator 2.0

Original name was LiveScript

Announced on Dec 1995 as JavaScript

1996 Microsoft responded with JScript

Saturday, December 15, 12

Page 4: 02 JavaScript Syntax

JavaScript Key Ideas

Interpreter based (no compilation)

Loosely typed language

Objects are just hash tables

Saturday, December 15, 12

Page 5: 02 JavaScript Syntax

JavaScript Key Ideas

Interpreter based (no compilation)

Loosely typed language

Objects are just hash tables

Saturday, December 15, 12

Page 6: 02 JavaScript Syntax

JavaScript Key Ideas

Interpreter based (no compilation)

Loosely typed language

Objects are just hash tables

Saturday, December 15, 12

Page 7: 02 JavaScript Syntax

Hello JavaScript

var text = “Hello World”;

console.log(text);

Define and initialize a variable called ‘text’ with the string “Hello World”

Saturday, December 15, 12

Page 8: 02 JavaScript Syntax

Hello JavaScript

var text = “Hello World”;

console.log(text);

Call the log function from the console object on the variable ‘text’

Saturday, December 15, 12

Page 9: 02 JavaScript Syntax

Hello JavaScript

var text = “Hello World”;

console.log(text);

Call the log function from the console object on the variable ‘text’

Define and initialize a variable called ‘text’ with the string “Hello World”

Saturday, December 15, 12

Page 10: 02 JavaScript Syntax

Running JavaScript

Easy way: jsbin

Completely offline using node.js

Using a simple HTML file

Saturday, December 15, 12

Page 11: 02 JavaScript Syntax

DemoJavaScript Basic Syntax

Saturday, December 15, 12

Page 12: 02 JavaScript Syntax

JavaScript Core TypesNumbers

Strings

Booleans

null

undefined

Objects

Saturday, December 15, 12

Page 13: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 14: 02 JavaScript Syntax

Numeric FunctionsNumber(string)

converts string to number returns NaN on error

parseInt(string, radix)converts string to numbertries its best (so '7hello' is OK)

Math.random()returns a random between 0 and 1

Saturday, December 15, 12

Page 15: 02 JavaScript Syntax

Numeric Functionsx = 3;

y = Number(7);

z = Number(‘9’);

console.log(x + y + z);

Saturday, December 15, 12

Page 16: 02 JavaScript Syntax

Q & ANumbers

Strings

Booleans

null

undefined

Objects

Saturday, December 15, 12

Page 17: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 18: 02 JavaScript Syntax

String Examples'hello'.length === 5

String(10).length === 2

'hello'.indexOf('l') === 2

'hello'.lastIndexOf('l')=== 3

'hello'.toUpperCase() === 'HELLO'

Saturday, December 15, 12

Page 19: 02 JavaScript Syntax

Lab

http://ynonperek.com/javascript-exer.html

Exercises 1-5

Saturday, December 15, 12

Page 20: 02 JavaScript Syntax

Q & ANumbers

Strings

Booleans

null

undefined

Objects

Saturday, December 15, 12

Page 21: 02 JavaScript Syntax

Boolean TypeJavaScript 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

Saturday, December 15, 12

Page 22: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 23: 02 JavaScript Syntax

undefined

Not even the nothing

JavaScript puts undefined in anything that hasn't yet been assigned a value

Saturday, December 15, 12

Page 24: 02 JavaScript Syntax

JavaScript False/True

These are all falsy:

false, null, undefined

“” (the empty string)

0, NaN

Everything else is truthy

Saturday, December 15, 12

Page 25: 02 JavaScript Syntax

ObjectsEverything 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.

Saturday, December 15, 12

Page 26: 02 JavaScript Syntax

Objects

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

name Ynon Perek

email [email protected]

web http://ynonperek.com

Saturday, December 15, 12

Page 27: 02 JavaScript Syntax

Q & ANumbers

Strings

Booleans

null

undefined

Objects

Saturday, December 15, 12

Page 28: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 29: 02 JavaScript Syntax

JavaScript SyntaxIdentifiers

Reserved Words

Comments

Loops and Branches

Functions

Objects & Arrays

Saturday, December 15, 12

Page 30: 02 JavaScript Syntax

JavaScript Identifiers

Starts with a letter, an _, or a $

Followed by letters, digits, _ or $

Saturday, December 15, 12

Page 31: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 32: 02 JavaScript Syntax

Identifier Examples

counter

file_name

function getName()

function Person()

Saturday, December 15, 12

Page 33: 02 JavaScript Syntax

JavaScript Reserved Wordsabstract

boolean break bytecase catch char class const continuedebugger default delete do doubleelse enum export extendsfalse final finally float for functiongotoif implements import in instanceof int interfacelongnative new nullpackage private protected publicreturnshort static super switch synchronizedthis throw throws transient true try typeofvar volatile voidwhile with

Saturday, December 15, 12

Page 34: 02 JavaScript Syntax

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

*/

Saturday, December 15, 12

Page 35: 02 JavaScript Syntax

Syntax Q & AIdentifiers

Reserved Words

Comments

Loops and Branches

Functions

Objects & Arrays

Saturday, December 15, 12

Page 36: 02 JavaScript Syntax

Loop Controls

JavaScript has:

while and do-while loops

for loops

for-in loops

Saturday, December 15, 12

Page 37: 02 JavaScript Syntax

While Loop

Syntax:

while (expression) {

statement;}

Saturday, December 15, 12

Page 38: 02 JavaScript Syntax

Do-while Loop

Syntax:

Note the ending semicolon

do {

statement;} while (expression);

Saturday, December 15, 12

Page 39: 02 JavaScript Syntax

For Loop

Syntax:

for ( initialize; test; increment) { statement;

}

Saturday, December 15, 12

Page 40: 02 JavaScript Syntax

For Example

var sum = 0;

for ( var i=0; i < 10; ++i ) {

sum += i;}console.log(sum);

Saturday, December 15, 12

Page 41: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 42: 02 JavaScript Syntax

BranchesSyntax:

if ( expression ) {}

else if ( something_else ) {}

else {}

Saturday, December 15, 12

Page 43: 02 JavaScript Syntax

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 + ...)

Saturday, December 15, 12

Page 44: 02 JavaScript Syntax

Syntax Q & AIdentifiers

Reserved Words

Comments

Loops and Branches

Functions

Objects & Arrays

Saturday, December 15, 12

Page 45: 02 JavaScript Syntax

Functions & Scope

Outside all functions, variables have the “global” scope.

Count how many globals are on the right

var text = 'Hello Scope'; var sum = 0; for ( var i=0; i < 10; i++ ) {  sum += i;  } console.log( sum );

Saturday, December 15, 12

Page 46: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 47: 02 JavaScript Syntax

Creating A Functionfunction foo(x, y) {  return x + y;}

var bar = function(x, y) {  return x + y;};

Saturday, December 15, 12

Page 48: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 49: 02 JavaScript Syntax

Functions & Scope

Best Practices:

Write all code inside a function block

Use only one var statement at the beginning of that function

Saturday, December 15, 12

Page 50: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 51: 02 JavaScript Syntax

Functions & ScopeWhat 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()); }

Saturday, December 15, 12

Page 52: 02 JavaScript Syntax

Functions Q & A

Saturday, December 15, 12

Page 53: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 54: 02 JavaScript Syntax

Objects

var pos = { x : 50; y : 10 };

pos.move = function(dx, dy) {

this.x += dx;

this.y += dy;};

Saturday, December 15, 12

Page 55: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 56: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 57: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 58: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 59: 02 JavaScript Syntax

Syntax Q & AIdentifiers

Reserved Words

Comments

Loops and Branches

Functions

Objects & Arrays

Saturday, December 15, 12

Page 60: 02 JavaScript Syntax

DOM ScriptingUsing JS To Manipulate the web page

http://www.flickr.com/photos/jram23/3088840966/

Saturday, December 15, 12

Page 61: 02 JavaScript Syntax

The DOM

Stands for Document Object Model

Every HTML element has a JS object “bound” to it in a special bond HTMLDivElement

HTMLdiv

JS

Saturday, December 15, 12

Page 62: 02 JavaScript Syntax

The DOM

Can use getElementByIdto find a specific element

Can use getElementsByTagName to get all elements with a specified name

<p id="text"></p>

var t = document.getElementById('text');

t.innerHTML = "Hello World";

Saturday, December 15, 12

Page 63: 02 JavaScript Syntax

DOM Agenda

jQuery Introduction

Handling Events

Writing a simple web app

Saturday, December 15, 12

Page 64: 02 JavaScript Syntax

The Facts

Every browser is different. Really.

W3 Standard

Webkit

Mozilla

Microsoft

Saturday, December 15, 12

Page 65: 02 JavaScript Syntax

Ajax Libraries

Developer tools that wrap common functionality and create a standard

Many options to choose from. We’ll use jQuery

Saturday, December 15, 12

Page 66: 02 JavaScript Syntax

jQuery BasicsWrap a normal DOM element inside a jQuery object

All operations on the element are performed by jQuery

Unified and cross browser API

<p></p>

$('p').html('hello jQUery');

Saturday, December 15, 12

Page 67: 02 JavaScript Syntax

jQuery Basics: Selectors

Powerful element selection and manipulations

Works “the same” for all mobile & desktop browsers

<p id="text"></p>

$('p#text').html("Hello World");

Selector returning a jQuery Object

An action to perform on the object

Saturday, December 15, 12

Page 68: 02 JavaScript Syntax

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();    

Saturday, December 15, 12

Page 69: 02 JavaScript Syntax

jQuery Actions Example

Zebra stripe a table using jQuery

$('table tr:nth-child(2n)').css('background', '#ccc');

Saturday, December 15, 12

Page 70: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 71: 02 JavaScript Syntax

jQuery Eventsdocument.ready

click

hover

keypress

mousemove

resize

scroll

select

submit

Full list: http://api.jquery.com/category/events/

Saturday, December 15, 12

Page 72: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 73: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 74: 02 JavaScript Syntax

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

Saturday, December 15, 12

Page 75: 02 JavaScript Syntax

Q & A

Saturday, December 15, 12