Course Evaluation

 5 lectures and 5 labs

 Evaluation:
    60% Project and Assignments
    40% Labs and Quizzes
Lecture Outline

 Introduction

 JavaScript Syntax

 Built-in objects

 Functions
How did it all start?

 Invented by Brendan Eich at Netscape

 First appeared in Navigator 2.0 browser.

 Appeared since Microsoft Internet Explorer 3.0.
What JS isn‟t ?
What JavaScript isn‟t?

 It isn‟t Java

 It isn‟t HTML or a version of it

 It isn‟t compiled

 For Client-Side JS:
    It has no graphics capabilities, except for the powerful
     ability to dynamically generate HTML.
    It isn‟t allowed the reading or writing of files.
    It has no support for networking of any kind.
What JS is ?
What JavaScript is?
 It is a scripting language, to be processed and executed
  by a JavaScript interpreter.

 It is dynamic.

 It is Object Oriented or Object-based (controversial
  subject).
    "ECMAScript is an object-oriented programming language
     for performing computations and manipulating
     computational objects within a host environment." ECMA-
     262

 It is general purpose programming language.

 It is event-driven.
At the Beginning
Javascript Engines

 Brendan Eich first engine SpiderMonkey

 Google Chrome  V8

 Safari  Nitro JavaScript engine

 Opera  Carakan

 IE 9+  Chakra

 Adobe Labs for ActionScript  Tamarin
Uses of Client-Side
          Javascript
 Form Validation

 Dynamic, and Highly Responsive content.

 Personalized Interface
Where is JavaScript
            added?
 In HTML file
    Between <script> tags
    Can be added to <head> section
       Mostly used to define functions
    Can be added inside <body> section

 In External file
    File will have only JavaScript Code, with extension .js
    In HTML file refer to this file using src attribute of
     <script> tag
Where is JavaScript
              added?
     Inside HTML file                 In external .js file

<!DOCTYPE html>                   <!DOCTYPE html>
<html>                            <html>
<head>
                                  <head>
<script type="text/javascript">
JavaScript goes here...           <script type="text/javascript"
</script>                         src="file.js">
</head>                           </script>
<body>                            </head>
Mark-up goes here...              <body>
<script type="text/javascript">
JavaScript goes here...
                                  Mark-up goes here...
</script>                         </body>
</body>                           </html>
</html>
JavaScript Syntax

 Statements

 Variables

 Dialogues and Alerts

 Data Types

 Operators

 Control Statements
Statements

 JS is case-sensitive.

 Statements are places in separate lines or
  separated by semi-colons on the same line.

 Comments are C/C++ like
    Single line //
    Multiple line /*………..*/
Variables

 Variable names follow C/C++ guidelines

 Variables are declared by „var‟ keyword

 A variable can be used direclty without declaring but
  it is not good practice.
Try variables and dialogues
        Use Developer tools
Dialogues and Alerts

 There are 3 types of dialogues
    alert()
       Show a message box with one button, has no return.
    confirm()
       Show a message box with 2 buttons (OK and Cancel).
       Returns true  OK pressed.
       Returns false Cancel pressed.
    prompt()
       Show a message box with 2 buttons (OK and Cancel) and
        a textbox
       Returns the text in textbox OK pressed
       Returns null  Cancel pressed
Data Types
 Primitive Types:
      Number: float or int
      String: any charaters enclosed in “…” or „….‟
      Boolean: true/false
      Undefined
      Null

 Object:
    any value not a primitive is an object.

 JavaScript is un-typed language, thus a variable can
  change it‟s type multiple times.
Useful built-in functions

 isNaN(input ) true/false
 isFinite()  true if finite number, false if not a number or
  Infinity
 parseInt( input, radix=10)  NaN if failed, or number if
  successful
 parseFloat(input) a floating point number or NaN
 eval(input)  tries to evaluate the input string as a
  javascipt code.
Operators

 Arithmetic Operators

 Logical Operators

 Bitwise Operators (self-study)

 Comparison Operators
Arithmetic Operator

Operator            Operation
+                   Addition or concatenation of strings
-                   Subtraction
*                   Multiplication
/                   Division
%                   Modulo, reminder of a division
++                  Increment (post or pre)
--                  Decrement (post or pre)
=                   Assignment
+=, -=,*=,/=, %=    Compound operators
Logical Operators

Operator           Operation
!                  Logical NOT
&&                 Logical AND
||                 Logical OR
Comparison Operators

Operator          Operation
==                Equality
===               Equality and type comparison
!=                Not Equal
!==               Not equal with type comparison
>, >=             greater than and greater than or
                  equal
<, <=             Less than and less than or equal
Operator Precedence

 From lowest to highest
   1.   Assignment operators (=, +=, -=, *=, /=, %=)
   2.   Conditional (?:)
   3.   Logical or (||)
   4.   Logical and (&&)
   5.   Equality (==, !=)
   6.   Relational (<, <=, >=, >)
   7.   Addition/Subtraction (+, -)
   8.   Multiply/divide/modulus (*, /, %)
   9.   Parentheses(())
Try operators and built –in
 functions on JS console
        Use Developer tools
Control Statements
1.     Conditional Statements       2.            Loop Statements
     a) if….else                              a) for
      if (some condition is true)
                                     for ( var i=0 ;i<10;i++)
       {
                                     {
           do something;
                                        document.write(“this is number” + i)
         }
                                     }
      else
       {                                      b) while
           do something else;
       }                                 while (condition)
                                         {
     b) switch / case                    statements
                                         }
     switch (expression)
     {                                        c) do…while
     case label1:
                statements               do
                [break]                  {
     default :                              statements
     }                                   }while(condition)
Built-in Objects

 String

 Date

 Math

 Array
String Object

 Properties:
  Property Name     Description
  length            The number of characters in the string.
String Object (Cont‟d)

 Methods :   Method Name                    Description
              charAt(n )                     Return the character at a given position

              indexOf( substr,[start])       Searches for first occurrence for a
                                             substring.
              lastIndexOf( substr,[start])   Searches for last occurrence for a
                                             substring.
              toString( )                    Returns the primitive string value.

              toUpperCase( )                 Returns with all characters converted to
                                             uppercase.
              substr(start, length)          Extracts a substring of a string.

              substring(from, to)            Extracts a substring of a string.

              slice(start , end)             Extracts a substring of a string. What‟s
                                             the difference then ??
              split(delimiter, limit)        Return array of strings, from splitting
                                             string into substrings at the
                                             boundaries specified by delimiter.
Date Object

 Object to manipulate date and time based on the
  local machine time.

 Examples:
    var d=new Date() //returns date of local machine now
    var d = new Date(2008, 1, 1); //1/2/2008
    d.setFullYear(d.getFullYear( ) + 1);
   //return 1/2/2009
    var weekday = d.getDay( ); //0  Sunday
Math Object

 Math is a built-in global object, which provides a
  number of methods and properties that are useful for
  mathematical operations, but can‟t be instantiated.

 Constant Properties:

     Constants             value
     Math.PI               3.141592653589793
     Math.E                2.718281828459045
     Math.LN2              0.6931471805599453
Math Objects

 Methods
    Methods
    Math.abs()       Returns the absolute unsigned value
    Math.ceil()      Return rounded number up to nearest interger
    Math.cos()       Returns cosine of number
    Math.floor()     Returns number down to nearest integer
    Math.pow()       Returns the number raised to a power
    Math.random()    Returns a number between 0 and 1.0
    Math.sqrt()      Returns square root of number
    Math.round()     Returns number rounded to closest integer
Arrays
 A datatype(object) that contains a number of other
  datatypes (primitive or objects).
 An array is a data store, contains indexed elements
  (index start @ 0)
 Declaring an array
    var myarr=[]; //declaring an array literal
    var myarr=[1 , 2 , ‘three’,’four’,false];
    var myarr= new Array() //using array constructor.
    Var myarr=new Array(2) //an array with 2 undefined
     elements
    var myarr=new Array(1,2,’r’,true); //an array with 4
     elements
Arrays (Cont‟d)
 Retrieving an element
    use the index in square brackets
         myarr[0]
 Deleting an element
    Delete myarr[2]
Array Properties

Property           Description
Length             Return number of elements of array
Array Methods

Method       Description
concat()     Concatenates elements from one array to another array.
join()       Joins the elements of an array by a separator to form a
             string.
pop()        Removes and returns the last element of an array.
push()       Adds elements to the end of an array.
reverse()    Reverses the order of the elements in an array.
shift()      Removes and returns the first element of an array.
slice()      Creates a new array from elements of an existing array.
sort()       Sorts an array alphabetically or numerically.
splice()     Removes and/or replaces elements of an array.
toString()   Returns a string representation of the array.
unshift()    Adds elements to the beginning of an array.
Associative Arrays
             (HASH)
 Arrays with index of elements a string instead of number.

 All objects are Associative arrays

 Example:
      var ar=[]; //create an array instance
      ar[„name‟]=„John Smith‟;
      ar[„age‟]=22;
      var x=ar[„name‟] or x=ar.name;
For/in loop

 Special type of for loop
 To loop over elements of an array, or properties of an
  object/associative array.
 Example:
var a = ['a', 'b', 'c', 'x', 'y', 'z'];
var result = 'n';
for (var i in a)
{
     result += 'index: ' + i + ', value: '
                              + a[i] + 'n’;
}
alert(result);
Functions

 Functions are objects, can be returned from another functions.

 Functions are first-class citizens.

 Functions used for code reuse, information hiding, and
  composition.

 Example:
        function square(x)
        {
                  return (x*x)
        }

 To call it:
        var x=square(4)     x=16
Functions (Cont‟d)
 Anonymous functions is a function without name

 Example:
       var f=function(a,b){return a+b}

 To call it,
       var x=f(1,2)  x=3;

 Self-invoked function:
    are anonymous functions invoked just after it declaration.
    To self-invoke an anonymous function add () to the end of its
     definition

 Example:
       var x=(function(a,b){return a+b})(1,2)  x=3
Functions (Cont‟d)

 Callback functions:
    Functions sent to other functions.
    Example:
      function invoke_and_add(a, b)
      {
              return a() + b();
      }
      function one() {return 1;}
      function two() {return 2;}
      invoke_and_add(one, two);
      invoke_and_add(function(){return 1;}, function(){return 2;})
Functions and Variable
            Scope
 There is No Block Scope, all variables declared in a
  function, no matter where, are defined throughout
  the function.

 Variables defined in function using „var‟ (where-
  ever) are local variables, if „var‟ is omitted they
  become global variables.
What is the output of the
         execution?
function f1(x,y)
     {
        if(x>3)
        {
            var z=3;
        }
        else
        {
            var zz=3;
        }
        alert(z+" - "+zz)
        zzz=300;
     }
     f1(1,3);
     alert(zzz);
What is the output of the
      execution now?
function f1(x,y)
     {
        if(x>3)
        {
            var z=3;
        }
        else
        {
            var zz=3;
        }
        alert(z+" - "+zz)
        zzz=300;
     }
     //f1(1,3);
     alert(zzz);
What is the output ?

var scope = "global";
function f( )
{
       alert(scope);
       var scope = "local";
       alert(scope);
}
f( );
References
 http://www.ecma-international.org/publications/files/ECMA-
  ST/Ecma-262.pdf
 https://developer.mozilla.org/en-US/docs/JavaScript
 http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
 http://w3techs.com/technologies/overview/javascript_library/all
 For Testing JS Compatibility:
    http://www.robertnyman.com/javascript/index.html

 Brendan Eich Blog: https://brendaneich.com/
 Useful resources:
    http://yuiblog.com/crockford/

Introduction to Client-Side Javascript

  • 2.
    Course Evaluation  5lectures and 5 labs  Evaluation:  60% Project and Assignments  40% Labs and Quizzes
  • 3.
    Lecture Outline  Introduction JavaScript Syntax  Built-in objects  Functions
  • 5.
    How did itall start?  Invented by Brendan Eich at Netscape  First appeared in Navigator 2.0 browser.  Appeared since Microsoft Internet Explorer 3.0.
  • 6.
  • 7.
    What JavaScript isn‟t? It isn‟t Java  It isn‟t HTML or a version of it  It isn‟t compiled  For Client-Side JS:  It has no graphics capabilities, except for the powerful ability to dynamically generate HTML.  It isn‟t allowed the reading or writing of files.  It has no support for networking of any kind.
  • 8.
  • 9.
    What JavaScript is? It is a scripting language, to be processed and executed by a JavaScript interpreter.  It is dynamic.  It is Object Oriented or Object-based (controversial subject).  "ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment." ECMA- 262  It is general purpose programming language.  It is event-driven.
  • 10.
  • 13.
    Javascript Engines  BrendanEich first engine SpiderMonkey  Google Chrome  V8  Safari  Nitro JavaScript engine  Opera  Carakan  IE 9+  Chakra  Adobe Labs for ActionScript  Tamarin
  • 14.
    Uses of Client-Side Javascript  Form Validation  Dynamic, and Highly Responsive content.  Personalized Interface
  • 15.
    Where is JavaScript added?  In HTML file  Between <script> tags  Can be added to <head> section  Mostly used to define functions  Can be added inside <body> section  In External file  File will have only JavaScript Code, with extension .js  In HTML file refer to this file using src attribute of <script> tag
  • 16.
    Where is JavaScript added? Inside HTML file In external .js file <!DOCTYPE html> <!DOCTYPE html> <html> <html> <head> <head> <script type="text/javascript"> JavaScript goes here... <script type="text/javascript" </script> src="file.js"> </head> </script> <body> </head> Mark-up goes here... <body> <script type="text/javascript"> JavaScript goes here... Mark-up goes here... </script> </body> </body> </html> </html>
  • 18.
    JavaScript Syntax  Statements Variables  Dialogues and Alerts  Data Types  Operators  Control Statements
  • 19.
    Statements  JS iscase-sensitive.  Statements are places in separate lines or separated by semi-colons on the same line.  Comments are C/C++ like  Single line //  Multiple line /*………..*/
  • 20.
    Variables  Variable namesfollow C/C++ guidelines  Variables are declared by „var‟ keyword  A variable can be used direclty without declaring but it is not good practice.
  • 21.
    Try variables anddialogues Use Developer tools
  • 22.
    Dialogues and Alerts There are 3 types of dialogues  alert()  Show a message box with one button, has no return.  confirm()  Show a message box with 2 buttons (OK and Cancel).  Returns true  OK pressed.  Returns false Cancel pressed.  prompt()  Show a message box with 2 buttons (OK and Cancel) and a textbox  Returns the text in textbox OK pressed  Returns null  Cancel pressed
  • 23.
    Data Types  PrimitiveTypes:  Number: float or int  String: any charaters enclosed in “…” or „….‟  Boolean: true/false  Undefined  Null  Object:  any value not a primitive is an object.  JavaScript is un-typed language, thus a variable can change it‟s type multiple times.
  • 24.
    Useful built-in functions isNaN(input ) true/false  isFinite()  true if finite number, false if not a number or Infinity  parseInt( input, radix=10)  NaN if failed, or number if successful  parseFloat(input) a floating point number or NaN  eval(input)  tries to evaluate the input string as a javascipt code.
  • 25.
    Operators  Arithmetic Operators Logical Operators  Bitwise Operators (self-study)  Comparison Operators
  • 26.
    Arithmetic Operator Operator Operation + Addition or concatenation of strings - Subtraction * Multiplication / Division % Modulo, reminder of a division ++ Increment (post or pre) -- Decrement (post or pre) = Assignment +=, -=,*=,/=, %= Compound operators
  • 27.
    Logical Operators Operator Operation ! Logical NOT && Logical AND || Logical OR
  • 28.
    Comparison Operators Operator Operation == Equality === Equality and type comparison != Not Equal !== Not equal with type comparison >, >= greater than and greater than or equal <, <= Less than and less than or equal
  • 29.
    Operator Precedence  Fromlowest to highest 1. Assignment operators (=, +=, -=, *=, /=, %=) 2. Conditional (?:) 3. Logical or (||) 4. Logical and (&&) 5. Equality (==, !=) 6. Relational (<, <=, >=, >) 7. Addition/Subtraction (+, -) 8. Multiply/divide/modulus (*, /, %) 9. Parentheses(())
  • 30.
    Try operators andbuilt –in functions on JS console Use Developer tools
  • 31.
    Control Statements 1. Conditional Statements 2. Loop Statements a) if….else a) for if (some condition is true) for ( var i=0 ;i<10;i++) { { do something; document.write(“this is number” + i) } } else { b) while do something else; } while (condition) { b) switch / case statements } switch (expression) { c) do…while case label1: statements do [break] { default : statements } }while(condition)
  • 33.
    Built-in Objects  String Date  Math  Array
  • 34.
    String Object  Properties: Property Name Description length The number of characters in the string.
  • 35.
    String Object (Cont‟d) Methods : Method Name Description charAt(n ) Return the character at a given position indexOf( substr,[start]) Searches for first occurrence for a substring. lastIndexOf( substr,[start]) Searches for last occurrence for a substring. toString( ) Returns the primitive string value. toUpperCase( ) Returns with all characters converted to uppercase. substr(start, length) Extracts a substring of a string. substring(from, to) Extracts a substring of a string. slice(start , end) Extracts a substring of a string. What‟s the difference then ?? split(delimiter, limit) Return array of strings, from splitting string into substrings at the boundaries specified by delimiter.
  • 36.
    Date Object  Objectto manipulate date and time based on the local machine time.  Examples:  var d=new Date() //returns date of local machine now  var d = new Date(2008, 1, 1); //1/2/2008  d.setFullYear(d.getFullYear( ) + 1); //return 1/2/2009  var weekday = d.getDay( ); //0  Sunday
  • 37.
    Math Object  Mathis a built-in global object, which provides a number of methods and properties that are useful for mathematical operations, but can‟t be instantiated.  Constant Properties: Constants value Math.PI 3.141592653589793 Math.E 2.718281828459045 Math.LN2 0.6931471805599453
  • 38.
    Math Objects  Methods Methods Math.abs() Returns the absolute unsigned value Math.ceil() Return rounded number up to nearest interger Math.cos() Returns cosine of number Math.floor() Returns number down to nearest integer Math.pow() Returns the number raised to a power Math.random() Returns a number between 0 and 1.0 Math.sqrt() Returns square root of number Math.round() Returns number rounded to closest integer
  • 39.
    Arrays  A datatype(object)that contains a number of other datatypes (primitive or objects).  An array is a data store, contains indexed elements (index start @ 0)  Declaring an array  var myarr=[]; //declaring an array literal  var myarr=[1 , 2 , ‘three’,’four’,false];  var myarr= new Array() //using array constructor.  Var myarr=new Array(2) //an array with 2 undefined elements  var myarr=new Array(1,2,’r’,true); //an array with 4 elements
  • 40.
    Arrays (Cont‟d)  Retrievingan element  use the index in square brackets  myarr[0]  Deleting an element  Delete myarr[2]
  • 41.
    Array Properties Property Description Length Return number of elements of array
  • 42.
    Array Methods Method Description concat() Concatenates elements from one array to another array. join() Joins the elements of an array by a separator to form a string. pop() Removes and returns the last element of an array. push() Adds elements to the end of an array. reverse() Reverses the order of the elements in an array. shift() Removes and returns the first element of an array. slice() Creates a new array from elements of an existing array. sort() Sorts an array alphabetically or numerically. splice() Removes and/or replaces elements of an array. toString() Returns a string representation of the array. unshift() Adds elements to the beginning of an array.
  • 43.
    Associative Arrays (HASH)  Arrays with index of elements a string instead of number.  All objects are Associative arrays  Example:  var ar=[]; //create an array instance  ar[„name‟]=„John Smith‟;  ar[„age‟]=22;  var x=ar[„name‟] or x=ar.name;
  • 44.
    For/in loop  Specialtype of for loop  To loop over elements of an array, or properties of an object/associative array.  Example: var a = ['a', 'b', 'c', 'x', 'y', 'z']; var result = 'n'; for (var i in a) { result += 'index: ' + i + ', value: ' + a[i] + 'n’; } alert(result);
  • 46.
    Functions  Functions areobjects, can be returned from another functions.  Functions are first-class citizens.  Functions used for code reuse, information hiding, and composition.  Example: function square(x) { return (x*x) }  To call it: var x=square(4)  x=16
  • 47.
    Functions (Cont‟d)  Anonymousfunctions is a function without name  Example: var f=function(a,b){return a+b}  To call it, var x=f(1,2)  x=3;  Self-invoked function:  are anonymous functions invoked just after it declaration.  To self-invoke an anonymous function add () to the end of its definition  Example: var x=(function(a,b){return a+b})(1,2)  x=3
  • 48.
    Functions (Cont‟d)  Callbackfunctions:  Functions sent to other functions.  Example: function invoke_and_add(a, b) { return a() + b(); } function one() {return 1;} function two() {return 2;} invoke_and_add(one, two); invoke_and_add(function(){return 1;}, function(){return 2;})
  • 49.
    Functions and Variable Scope  There is No Block Scope, all variables declared in a function, no matter where, are defined throughout the function.  Variables defined in function using „var‟ (where- ever) are local variables, if „var‟ is omitted they become global variables.
  • 50.
    What is theoutput of the execution? function f1(x,y) { if(x>3) { var z=3; } else { var zz=3; } alert(z+" - "+zz) zzz=300; } f1(1,3); alert(zzz);
  • 51.
    What is theoutput of the execution now? function f1(x,y) { if(x>3) { var z=3; } else { var zz=3; } alert(z+" - "+zz) zzz=300; } //f1(1,3); alert(zzz);
  • 52.
    What is theoutput ? var scope = "global"; function f( ) { alert(scope); var scope = "local"; alert(scope); } f( );
  • 53.
    References  http://www.ecma-international.org/publications/files/ECMA- ST/Ecma-262.pdf  https://developer.mozilla.org/en-US/docs/JavaScript  http://www.w3.org/TR/DOM-Level-3-Events/#event-flow  http://w3techs.com/technologies/overview/javascript_library/all  For Testing JS Compatibility:  http://www.robertnyman.com/javascript/index.html  Brendan Eich Blog: https://brendaneich.com/  Useful resources:  http://yuiblog.com/crockford/

Editor's Notes

  • #6 From ECMA Specification
  • #17 External JS files makes better code reuse, and they’re cached in the browser instead of being downloaded with each page.
  • #20 It is good programming practice to place a semicolon at the end of every statement.
  • #24 To know datatype of a variable or value use typeof operatorSpecial values: InfinityNaNFalse is empty string, null, undefined, 0, NaN, false
  • #32 break  breaks a loopcontinue  break current iteration and jump to next.
  • #37 See methods and properties from notes of lecture or http://www.w3schools.com/jsref/jsref_obj_math.asp
  • #38 There are more constants defines, you can find them in notes or
  • #39 There are more constants defines, you can find them in notes or http://www.w3schools.com/jsref/jsref_obj_math.asp
  • #44 [] must be used instead of . Notation when key is a reserved word or contains space
  • #48 Anonymous functions are used as:Callback functionsSelf-invoked functions
  • #51 First alert  undefined – 3Second alert  300 If a variable is used without being declared using ’var’ keyword is added in the window object, thus becomes like a global variable.
  • #52 Error in page since zzz is undefined.
  • #53 Alert  undefinedVariable initialized at line 2 of function, but defined everywhere alert(scope);
  • #54 Useful books are in the notes of the lecture