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 Micr...
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...
What JS is ?
What JavaScript is? It is a scripting language, to be processed and executed  by a JavaScript interpreter. It is dynamic...
At the Beginning
Javascript Engines Brendan Eich first engine SpiderMonkey Google Chrome  V8 Safari  Nitro JavaScript engine Opera ...
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       Mo...
Where is JavaScript              added?     Inside HTML file                 In external .js file<!DOCTYPE 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....
Variables Variable names follow C/C++ guidelines Variables are declared by „var‟ keyword A variable can be used direclt...
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....
Data Types Primitive Types:      Number: float or int      String: any charaters enclosed in “…” or „….‟      Boolean:...
Useful built-in functions isNaN(input ) true/false isFinite()  true if finite number, false if not a number or  Infini...
Operators Arithmetic Operators Logical Operators Bitwise Operators (self-study) Comparison Operators
Arithmetic OperatorOperator            Operation+                   Addition or concatenation of strings-                 ...
Logical OperatorsOperator           Operation!                  Logical NOT&&                 Logical AND||               ...
Comparison OperatorsOperator          Operation==                Equality===               Equality and type comparison!= ...
Operator Precedence From lowest to highest   1.   Assignment operators (=, +=, -=, *=, /=, %=)   2.   Conditional (?:)   ...
Try operators and built –in functions on JS console        Use Developer tools
Control Statements1.     Conditional Statements       2.            Loop Statements     a) if….else                       ...
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 )                    ...
Date Object Object to manipulate date and time based on the  local machine time. Examples:    var d=new Date() //return...
Math Object Math is a built-in global object, which provides a  number of methods and properties that are useful for  mat...
Math Objects Methods    Methods    Math.abs()       Returns the absolute unsigned value    Math.ceil()      Return rounde...
Arrays A datatype(object) that contains a number of other  datatypes (primitive or objects). An array is a data store, c...
Arrays (Cont‟d) Retrieving an element    use the index in square brackets         myarr[0] Deleting an element    Del...
Array PropertiesProperty           DescriptionLength             Return number of elements of array
Array MethodsMethod       Descriptionconcat()     Concatenates elements from one array to another array.join()       Joins...
Associative Arrays             (HASH) Arrays with index of elements a string instead of number. All objects are Associat...
For/in loop Special type of for loop To loop over elements of an array, or properties of an  object/associative array. ...
Functions Functions are objects, can be returned from another functions. Functions are first-class citizens. Functions ...
Functions (Cont‟d) Anonymous functions is a function without name Example:       var f=function(a,b){return a+b} To cal...
Functions (Cont‟d) Callback functions:    Functions sent to other functions.    Example:      function invoke_and_add(a...
Functions and Variable            Scope There is No Block Scope, all variables declared in a  function, no matter where, ...
What is the output of the         execution?function f1(x,y)     {        if(x>3)        {            var z=3;        }   ...
What is the output of the      execution now?function f1(x,y)     {        if(x>3)        {            var z=3;        }  ...
What is the output ?var scope = "global";function f( ){       alert(scope);       var scope = "local";       alert(scope);...
References http://www.ecma-international.org/publications/files/ECMA-  ST/Ecma-262.pdf https://developer.mozilla.org/en-...
Introduction to Client-Side Javascript
Introduction to Client-Side Javascript
Introduction to Client-Side Javascript
Introduction to Client-Side Javascript
Introduction to Client-Side Javascript
Introduction to Client-Side Javascript
Introduction to Client-Side Javascript
Upcoming SlideShare
Loading in …5
×

Introduction to Client-Side Javascript

925 views

Published on

An introduction to JavaScript that covers JavaScript syntax and built-in objects and functions

Published in: Technology
  • Be the first to comment

Introduction to Client-Side Javascript

  1. 1. Course Evaluation 5 lectures and 5 labs Evaluation:  60% Project and Assignments  40% Labs and Quizzes
  2. 2. Lecture Outline Introduction JavaScript Syntax Built-in objects Functions
  3. 3. 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.
  4. 4. What JS isn‟t ?
  5. 5. 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.
  6. 6. What JS is ?
  7. 7. 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.
  8. 8. At the Beginning
  9. 9. Javascript Engines Brendan Eich first engine SpiderMonkey Google Chrome  V8 Safari  Nitro JavaScript engine Opera  Carakan IE 9+  Chakra Adobe Labs for ActionScript  Tamarin
  10. 10. Uses of Client-Side Javascript Form Validation Dynamic, and Highly Responsive content. Personalized Interface
  11. 11. 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
  12. 12. 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>
  13. 13. JavaScript Syntax Statements Variables Dialogues and Alerts Data Types Operators Control Statements
  14. 14. 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 /*………..*/
  15. 15. 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.
  16. 16. Try variables and dialogues Use Developer tools
  17. 17. 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
  18. 18. 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.
  19. 19. 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.
  20. 20. Operators Arithmetic Operators Logical Operators Bitwise Operators (self-study) Comparison Operators
  21. 21. Arithmetic OperatorOperator 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
  22. 22. Logical OperatorsOperator Operation! Logical NOT&& Logical AND|| Logical OR
  23. 23. Comparison OperatorsOperator 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
  24. 24. 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(())
  25. 25. Try operators and built –in functions on JS console Use Developer tools
  26. 26. Control Statements1. 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)
  27. 27. Built-in Objects String Date Math Array
  28. 28. String Object Properties: Property Name Description length The number of characters in the string.
  29. 29. 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.
  30. 30. 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
  31. 31. 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
  32. 32. 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
  33. 33. 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
  34. 34. Arrays (Cont‟d) Retrieving an element  use the index in square brackets  myarr[0] Deleting an element  Delete myarr[2]
  35. 35. Array PropertiesProperty DescriptionLength Return number of elements of array
  36. 36. Array MethodsMethod Descriptionconcat() 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.
  37. 37. 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;
  38. 38. 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);
  39. 39. 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
  40. 40. 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
  41. 41. 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;})
  42. 42. 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.
  43. 43. 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);
  44. 44. 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);
  45. 45. What is the output ?var scope = "global";function f( ){ alert(scope); var scope = "local"; alert(scope);}f( );
  46. 46. 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/

×