SlideShare a Scribd company logo
JavaScript
       Programming the WWW




Saturday, December 15, 12
Agenda

                  Key Concepts

                  Core Types

                  Syntax

                  The Global Object & Scope Chain

                  Function Objects



Saturday, December 15, 12
History
             1995 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
JavaScript Key Ideas


                  Interpreter based (no compilation)

                  Loosely typed language

                  Objects are just hash tables




Saturday, December 15, 12
JavaScript Key Ideas


                  Interpreter based (no compilation)

                  Loosely typed language

                  Objects are just hash tables




Saturday, December 15, 12
JavaScript Key Ideas


                  Interpreter based (no compilation)

                  Loosely typed language

                  Objects are just hash tables




Saturday, December 15, 12
Hello JavaScript
                             Define and initialize a variable called ‘text’ with
                             the string “Hello World”


                  var text = “Hello World”;

                  console.log(text);




Saturday, December 15, 12
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
Hello JavaScript
                              Define and initialize a variable called ‘text’ with
                              the string “Hello World”


                  var text = “Hello World”;

                  console.log(text);



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


Saturday, December 15, 12
Running JavaScript


                  Easy way: jsbin

                  Completely offline using node.js

                  Using a simple HTML file




Saturday, December 15, 12
Demo
             JavaScript Basic Syntax




Saturday, December 15, 12
JavaScript Core Types
                  Numbers

                  Strings

                  Booleans

                  null

                  undefined

                  Objects


Saturday, December 15, 12
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
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



Saturday, December 15, 12
Numeric Functions
                      x = 3;

                      y = Number(7);

                      z = Number(‘9’);



                      console.log(x + y + z);




Saturday, December 15, 12
Q&A
                  Numbers

                  Strings

                  Booleans

                  null

                  undefined

                  Objects


Saturday, December 15, 12
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
String Examples
                   'hello'.length          === 5

                   String(10).length       === 2

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

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

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




Saturday, December 15, 12
Lab


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

                  Exercises 1-5




Saturday, December 15, 12
Q&A
                  Numbers

                  Strings

                  Booleans

                  null

                  undefined

                  Objects


Saturday, December 15, 12
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



Saturday, December 15, 12
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
undefined


                  Not even the nothing

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




Saturday, December 15, 12
JavaScript False/True

                  These are all falsy:

                        false, null, undefined

                        “” (the empty string)

                        0, NaN

                  Everything else is truthy



Saturday, December 15, 12
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.


Saturday, December 15, 12
Objects

     name            Ynon Perek
                                            var me = {
                                               name  : 'Ynon Perek',
                                               email : 'ynonperek@yahoo.com',
     email           ynonperek@yahoo.com       web   : 'http://ynonperek.com'
                                            }; 


     web             http://ynonperek.com




Saturday, December 15, 12
Q&A
                  Numbers

                  Strings

                  Booleans

                  null

                  undefined

                  Objects


Saturday, December 15, 12
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
JavaScript Syntax
                  Identifiers

                  Reserved Words

                  Comments

                  Loops and Branches

                  Functions

                  Objects & Arrays


Saturday, December 15, 12
JavaScript Identifiers


                  Starts with a letter, an _, or a $

                  Followed by letters, digits, _ or $




Saturday, December 15, 12
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
Identifier Examples

                  counter

                  file_name

                  function getName()

                  function Person()




Saturday, December 15, 12
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




Saturday, December 15, 12
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
Syntax Q & A
                  Identifiers

                  Reserved Words

                  Comments

                  Loops and Branches

                  Functions

                  Objects & Arrays


Saturday, December 15, 12
Loop Controls

                  JavaScript has:

                        while and do-while loops

                        for loops

                        for-in loops




Saturday, December 15, 12
While Loop

                  Syntax:

                    while (expression) {

                            statement;
                    }




Saturday, December 15, 12
Do-while Loop

                  Syntax:

                   do {

                     statement;
                   } while (expression);

                  Note the ending semicolon



Saturday, December 15, 12
For Loop

                     Syntax:

                     for ( initialize; test; increment) {
                       statement;

                     }




Saturday, December 15, 12
For Example

                   var sum = 0;

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

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




Saturday, December 15, 12
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
Branches
                  Syntax:

                   if ( expression ) {
                   }

                   else if
                   ( something_else ) {
                   }

                   else {
                   }


Saturday, December 15, 12
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
Syntax Q & A
                  Identifiers

                  Reserved Words

                  Comments

                  Loops and Branches

                  Functions

                  Objects & Arrays


Saturday, December 15, 12
Functions & Scope

                                             var text = 'Hello Scope';
                  Outside all functions,      
                                             var sum = 0;
                  variables have the          
                  “global” scope.            for ( var i=0; i < 10; i++ ) {
                                               sum += i;  
                                             }
                  Count how many              
                  globals are on the right   console.log( sum );




Saturday, December 15, 12
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
Creating A Function
                   function foo(x, y) {
                     return x + y;
                   }


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




Saturday, December 15, 12
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
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
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
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());
                   }




Saturday, December 15, 12
Functions Q & A



Saturday, December 15, 12
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
Objects

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

                   pos.move = function(dx, dy) {

                            this.x += dx;

                            this.y += dy;
                   };




Saturday, December 15, 12
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
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
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
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
Syntax Q & A
                  Identifiers

                  Reserved Words

                  Comments

                  Loops and Branches

                  Functions

                  Objects & Arrays


Saturday, December 15, 12
DOM
             Scripting
             Using JS To Manipulate the
             web page



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




Saturday, December 15, 12
The DOM

                  Stands for Document
                                             div         HTML
                  Object Model

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




Saturday, December 15, 12
The DOM
                                     <p id="text"></p>
                  Can use
                  getElementById
                  to find a specific   var t = document.getElementById('text');

                  element            t.innerHTML = "Hello World";

                  Can use
                  getElementsByTagNam
                  e to get all elements
                  with a specified name



Saturday, December 15, 12
DOM Agenda

                  jQuery Introduction

                  Handling Events

                  Writing a simple web
                  app




Saturday, December 15, 12
The Facts

                  Every browser is different. Really.

                  W3 Standard

                  Webkit

                  Mozilla

                  Microsoft



Saturday, December 15, 12
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
jQuery Basics
                                         Wrap a normal DOM
          $('p').html('hello jQUery');   element inside a jQuery
                                         object
           <p></p>
                                         All operations on the
                                         element are performed
                                         by jQuery

                                         Unified and cross
                                         browser API


Saturday, December 15, 12
jQuery Basics: Selectors
                                          <p id="text"></p>
                  Powerful element
                  selection and
                  manipulations           $('p#text').html("Hello World");


                  Works “the same” for
                  all mobile & desktop
                  browsers          Selector returning a
                                     jQuery Object
                                                      An action to perform
                                                      on the object
Saturday, December 15, 12
jQuery Actions
                                  $('div#foo').addClass('wide');
                  Each jQuery     $('div#foo').removeClass('wide');
                  object
                                  $('div#foo').css('background', 'red');
                  supports a
                  wide range of   $('div#foo').hide();
                  functions to    $('div#foo').show();    

                  alter the
                  elements




Saturday, December 15, 12
jQuery Actions Example


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




Saturday, December 15, 12
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
jQuery Events
                  document.ready   scroll

                  click            select

                  hover            submit

                  keypress         Full list: http://
                  mousemove
                                   api.jquery.com/
                                   category/events/
                  resize



Saturday, December 15, 12
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
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
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
Q&A



Saturday, December 15, 12
Thank You


                  Ynon Perek

                  ynonperek@yahoo.com

                  ynonperek.com




Saturday, December 15, 12

More Related Content

What's hot (20)

Dom
DomDom
Dom
Rakshita Upadhyay
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
Java Methods
Java MethodsJava Methods
Java Methods
OXUS 20
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy
 
Css selectors
Css selectorsCss selectors
Css selectors
Parth Trivedi
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
SAMIR BHOGAYTA
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
Mukesh Kumar
 
TypeScript
TypeScriptTypeScript
TypeScript
Saray Chak
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).ppt
MuhammadRehan856177
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
EPAM Systems
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 

Viewers also liked (20)

Web Programming Intro
Web Programming IntroWeb Programming Intro
Web Programming Intro
Ynon Perek
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScript
Ynon Perek
 
Performance
PerformancePerformance
Performance
Ynon Perek
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer Toolbox
Ynon Perek
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
Ynon Perek
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
Ynon Perek
 
основні теги мови Html
основні теги мови Htmlосновні теги мови Html
основні теги мови Html
Larisa023
 
01 Mobile Web Introduction
01 Mobile Web Introduction01 Mobile Web Introduction
01 Mobile Web Introduction
Ynon Perek
 
Refactoring out of the mess
Refactoring out of the messRefactoring out of the mess
Refactoring out of the mess
wolframkriesing
 
ES6Katas.org - an introduction and the story behind
ES6Katas.org - an introduction and the story behindES6Katas.org - an introduction and the story behind
ES6Katas.org - an introduction and the story behind
wolframkriesing
 
Диплом программиста получают в Витебском госуниверситете
Диплом программиста получают в Витебском госуниверситетеДиплом программиста получают в Витебском госуниверситете
Диплом программиста получают в Витебском госуниверситете
Liliya Alizarchik
 
Intro to SVGs
Intro to SVGsIntro to SVGs
Intro to SVGs
Ynon Perek
 
Css2
Css2Css2
Css2
Ynon Perek
 
маркетинг кит - Seo - email version (01.01.2015)
маркетинг кит - Seo - email version (01.01.2015)маркетинг кит - Seo - email version (01.01.2015)
маркетинг кит - Seo - email version (01.01.2015)
SEOEXPERT_Kazakhstan
 
Html5 apis
Html5 apisHtml5 apis
Html5 apis
Ynon Perek
 
завуч и директор
завуч и директорзавуч и директор
завуч и директор
Olga Gorbenko
 
Presentationfor lnl
Presentationfor lnlPresentationfor lnl
Presentationfor lnl
WebFX
 
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Michael Rys
 
САЙТ ГИМНАЗИИ
САЙТ ГИМНАЗИИ САЙТ ГИМНАЗИИ
САЙТ ГИМНАЗИИ
Olga Gorbenko
 
Web Programming Intro
Web Programming IntroWeb Programming Intro
Web Programming Intro
Ynon Perek
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScript
Ynon Perek
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer Toolbox
Ynon Perek
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
Ynon Perek
 
основні теги мови Html
основні теги мови Htmlосновні теги мови Html
основні теги мови Html
Larisa023
 
01 Mobile Web Introduction
01 Mobile Web Introduction01 Mobile Web Introduction
01 Mobile Web Introduction
Ynon Perek
 
Refactoring out of the mess
Refactoring out of the messRefactoring out of the mess
Refactoring out of the mess
wolframkriesing
 
ES6Katas.org - an introduction and the story behind
ES6Katas.org - an introduction and the story behindES6Katas.org - an introduction and the story behind
ES6Katas.org - an introduction and the story behind
wolframkriesing
 
Диплом программиста получают в Витебском госуниверситете
Диплом программиста получают в Витебском госуниверситетеДиплом программиста получают в Витебском госуниверситете
Диплом программиста получают в Витебском госуниверситете
Liliya Alizarchik
 
маркетинг кит - Seo - email version (01.01.2015)
маркетинг кит - Seo - email version (01.01.2015)маркетинг кит - Seo - email version (01.01.2015)
маркетинг кит - Seo - email version (01.01.2015)
SEOEXPERT_Kazakhstan
 
завуч и директор
завуч и директорзавуч и директор
завуч и директор
Olga Gorbenko
 
Presentationfor lnl
Presentationfor lnlPresentationfor lnl
Presentationfor lnl
WebFX
 
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Tuning and Optimizing U-SQL Queries (SQLPASS 2016)
Michael Rys
 
САЙТ ГИМНАЗИИ
САЙТ ГИМНАЗИИ САЙТ ГИМНАЗИИ
САЙТ ГИМНАЗИИ
Olga Gorbenko
 
Ad

Similar to 02 JavaScript Syntax (20)

A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
Simon Willison
 
Js in the open
Js in the openJs in the open
Js in the open
Victor Porof
 
javascript teach
javascript teachjavascript teach
javascript teach
guest3732fa
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
guest3732fa
 
Enterprise javascriptsession1
Enterprise javascriptsession1Enterprise javascriptsession1
Enterprise javascriptsession1
Troy Miles
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
KennyPratheepKumar
 
Chapter 1 .pptx
Chapter 1 .pptxChapter 1 .pptx
Chapter 1 .pptx
MohamedAbdullahiYusu
 
Javascript
JavascriptJavascript
Javascript
Prashant Kumar
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
Charles Russell
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1
Kasia Drzyzga
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
Rajat Saxena
 
Java script summary
Java script summaryJava script summary
Java script summary
maamir farooq
 
Javascript
JavascriptJavascript
Javascript
vikram singh
 
Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScript
nodejsbcn
 
Unit - 4 all script are here Javascript.pptx
Unit - 4 all script are here Javascript.pptxUnit - 4 all script are here Javascript.pptx
Unit - 4 all script are here Javascript.pptx
kushwahanitesh592
 
Javascript
JavascriptJavascript
Javascript
Sunil Thakur
 
chap04.ppt
chap04.pptchap04.ppt
chap04.ppt
Varsha Uchagaonkar
 
Ad

More from Ynon Perek (20)

Regexp
RegexpRegexp
Regexp
Ynon Perek
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
Ynon Perek
 
09 performance
09 performance09 performance
09 performance
Ynon Perek
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web Intro
Ynon Perek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
Ynon Perek
 
Vimperl
VimperlVimperl
Vimperl
Ynon Perek
 
Syllabus
SyllabusSyllabus
Syllabus
Ynon Perek
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
Ynon Perek
 
Network
NetworkNetwork
Network
Ynon Perek
 
Architecture app
Architecture appArchitecture app
Architecture app
Ynon Perek
 
Cryptography
CryptographyCryptography
Cryptography
Ynon Perek
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
Ynon Perek
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
Ynon Perek
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
Ynon Perek
 
Accessibility
AccessibilityAccessibility
Accessibility
Ynon Perek
 
Angularjs
AngularjsAngularjs
Angularjs
Ynon Perek
 
Js memory
Js memoryJs memory
Js memory
Ynon Perek
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
Ynon Perek
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
Ynon Perek
 
09 performance
09 performance09 performance
09 performance
Ynon Perek
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web Intro
Ynon Perek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
Ynon Perek
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
Ynon Perek
 
Architecture app
Architecture appArchitecture app
Architecture app
Ynon Perek
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
Ynon Perek
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
Ynon Perek
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
Ynon Perek
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
Ynon Perek
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
Ynon Perek
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
Ynon Perek
 

Recently uploaded (20)

National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 

02 JavaScript Syntax

  • 1. JavaScript Programming the WWW Saturday, December 15, 12
  • 2. Agenda Key Concepts Core Types Syntax The Global Object & Scope Chain Function Objects Saturday, December 15, 12
  • 3. History 1995 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
  • 4. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tables Saturday, December 15, 12
  • 5. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tables Saturday, December 15, 12
  • 6. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tables Saturday, December 15, 12
  • 7. Hello JavaScript Define and initialize a variable called ‘text’ with the string “Hello World” var text = “Hello World”; console.log(text); Saturday, December 15, 12
  • 8. 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
  • 9. Hello JavaScript Define and initialize a variable called ‘text’ with the string “Hello World” var text = “Hello World”; console.log(text); Call the log function from the console object on the variable ‘text’ Saturday, December 15, 12
  • 10. Running JavaScript Easy way: jsbin Completely offline using node.js Using a simple HTML file Saturday, December 15, 12
  • 11. Demo JavaScript Basic Syntax Saturday, December 15, 12
  • 12. JavaScript Core Types Numbers Strings Booleans null undefined Objects Saturday, December 15, 12
  • 13. 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
  • 14. 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 Saturday, December 15, 12
  • 15. Numeric Functions x = 3; y = Number(7); z = Number(‘9’); console.log(x + y + z); Saturday, December 15, 12
  • 16. Q&A Numbers Strings Booleans null undefined Objects Saturday, December 15, 12
  • 17. 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
  • 18. String Examples 'hello'.length === 5 String(10).length === 2 'hello'.indexOf('l') === 2 'hello'.lastIndexOf('l')=== 3 'hello'.toUpperCase() === 'HELLO' Saturday, December 15, 12
  • 19. Lab http://ynonperek.com/javascript-exer.html Exercises 1-5 Saturday, December 15, 12
  • 20. Q&A Numbers Strings Booleans null undefined Objects Saturday, December 15, 12
  • 21. 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 Saturday, December 15, 12
  • 22. 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
  • 23. undefined Not even the nothing JavaScript puts undefined in anything that hasn't yet been assigned a value Saturday, December 15, 12
  • 24. JavaScript False/True These are all falsy: false, null, undefined “” (the empty string) 0, NaN Everything else is truthy Saturday, December 15, 12
  • 25. 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. Saturday, December 15, 12
  • 26. Objects name Ynon Perek var me = {    name  : 'Ynon Perek',    email : '[email protected]', email [email protected]    web   : 'http://ynonperek.com' };  web http://ynonperek.com Saturday, December 15, 12
  • 27. Q&A Numbers Strings Booleans null undefined Objects Saturday, December 15, 12
  • 28. 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
  • 29. JavaScript Syntax Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Saturday, December 15, 12
  • 30. JavaScript Identifiers Starts with a letter, an _, or a $ Followed by letters, digits, _ or $ Saturday, December 15, 12
  • 31. 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
  • 32. Identifier Examples counter file_name function getName() function Person() Saturday, December 15, 12
  • 33. 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 Saturday, December 15, 12
  • 34. 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
  • 35. Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Saturday, December 15, 12
  • 36. Loop Controls JavaScript has: while and do-while loops for loops for-in loops Saturday, December 15, 12
  • 37. While Loop Syntax: while (expression) { statement; } Saturday, December 15, 12
  • 38. Do-while Loop Syntax: do { statement; } while (expression); Note the ending semicolon Saturday, December 15, 12
  • 39. For Loop Syntax: for ( initialize; test; increment) { statement; } Saturday, December 15, 12
  • 40. For Example var sum = 0; for ( var i=0; i < 10; ++i ) { sum += i; } console.log(sum); Saturday, December 15, 12
  • 41. 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
  • 42. Branches Syntax: if ( expression ) { } else if ( something_else ) { } else { } Saturday, December 15, 12
  • 43. 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
  • 44. Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Saturday, December 15, 12
  • 45. Functions & Scope var text = 'Hello Scope'; Outside all functions,   var sum = 0; variables have the   “global” scope. for ( var i=0; i < 10; i++ ) {   sum += i;   } Count how many   globals are on the right console.log( sum ); Saturday, December 15, 12
  • 46. 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
  • 47. Creating A Function function foo(x, y) {   return x + y; } var bar = function(x, y) {   return x + y; }; Saturday, December 15, 12
  • 48. 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
  • 49. 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
  • 50. 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
  • 51. 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()); } Saturday, December 15, 12
  • 52. Functions Q & A Saturday, December 15, 12
  • 53. 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
  • 54. Objects var pos = { x : 50; y : 10 }; pos.move = function(dx, dy) { this.x += dx; this.y += dy; }; Saturday, December 15, 12
  • 55. 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
  • 56. 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
  • 57. 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
  • 58. 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
  • 59. Syntax Q & A Identifiers Reserved Words Comments Loops and Branches Functions Objects & Arrays Saturday, December 15, 12
  • 60. DOM Scripting Using JS To Manipulate the web page http://www.flickr.com/photos/jram23/3088840966/ Saturday, December 15, 12
  • 61. The DOM Stands for Document div HTML Object Model Every HTML element has a JS object “bound” to it in a special bond HTMLDivElement JS Saturday, December 15, 12
  • 62. The DOM <p id="text"></p> Can use getElementById to find a specific var t = document.getElementById('text'); element t.innerHTML = "Hello World"; Can use getElementsByTagNam e to get all elements with a specified name Saturday, December 15, 12
  • 63. DOM Agenda jQuery Introduction Handling Events Writing a simple web app Saturday, December 15, 12
  • 64. The Facts Every browser is different. Really. W3 Standard Webkit Mozilla Microsoft Saturday, December 15, 12
  • 65. 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
  • 66. jQuery Basics Wrap a normal DOM $('p').html('hello jQUery'); element inside a jQuery object <p></p> All operations on the element are performed by jQuery Unified and cross browser API Saturday, December 15, 12
  • 67. jQuery Basics: Selectors <p id="text"></p> Powerful element selection and manipulations $('p#text').html("Hello World"); Works “the same” for all mobile & desktop browsers Selector returning a jQuery Object An action to perform on the object Saturday, December 15, 12
  • 68. jQuery Actions $('div#foo').addClass('wide'); Each jQuery $('div#foo').removeClass('wide'); object $('div#foo').css('background', 'red'); supports a wide range of $('div#foo').hide(); functions to $('div#foo').show();     alter the elements Saturday, December 15, 12
  • 69. jQuery Actions Example Zebra stripe a table using jQuery $('table tr:nth-child(2n)').css('background', '#ccc'); Saturday, December 15, 12
  • 70. 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
  • 71. jQuery Events document.ready scroll click select hover submit keypress Full list: http:// mousemove api.jquery.com/ category/events/ resize Saturday, December 15, 12
  • 72. 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
  • 73. 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
  • 74. 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
  • 76. Thank You Ynon Perek [email protected] ynonperek.com Saturday, December 15, 12