SlideShare a Scribd company logo
Building Web Sites: Introduction to JavaScript Kaushal Kishore Software Engineer OSSCube LLC [email_address] www.adhouraacademy.com
What is JavaScript JavaScript was originally developed by Brendan Eich of Netscape under the name  Mocha , which was later renamed to  LiveScript , and finally to JavaScript  A lightweight programming language that runs in a Web browser  JavaScript is a Client Side Scripting Language. Also known as ECMAScript   Interpreted, not compiled. JavaScript Syntax are similar to C and Java Language. JavaScript code is usually embedded directly into HTML pages JavaScript is  reasonably  platform-independent
What Can JavaScript Do? JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate input data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies
When not to use JavaScript When you need to access other resources. Files Programs Databases When you are using sensitive or copyrighted data or algorithms. Your JavaScript code is open to the public .
JavaScript is not Java Java and JavaScript are two completely different languages in both concept and design! JavaScript has some features that resemble features in Java: JavaScript has Objects and primitive data types JavaScript has qualified names; for example, document.write("Hello World"); JavaScript has Events and event handlers Exception handling in JavaScript is almost the same as in Java JavaScript has some features unlike anything in Java: Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way JavaScript  is an interpreted language but java is both interpreted and compiled
Where Do You Place Scripts? JavaScript can be put in the   <head> or in the <body> of  an HTML document JavaScript  functions  should be defined in  the <head> This ensures that the function is loaded before it is needed JavaScript in the   <body>   will be executed as the page loads JavaScript can be put in a separate   .js   file <script src=&quot;myJavaScriptFile.js&quot;></script> Put this HTML wherever you would put the actual JavaScript code An external   .js file  lets you use the same JavaScript on multiple HTML pages The external   .js file cannot itself contain a   <script> tag JavaScript can be put in HTML  form object,  such as a button This JavaScript will be executed when the form object is used
Referencing External JavaScript File Scripts can be provided locally or remotely accessible JavaScript file using  src  attribute <html> <head> <script language=&quot;JavaScript“ type=&quot;text/javascript“ src=&quot;http://somesite/myOwnJavaScript.js&quot;> </script> <script language=&quot;JavaScript“ type=&quot;text/javascript“ src=&quot;myOwnSubdirectory/myOwn2ndJavaScript.js&quot;> </script>
Primitive Datatypes JavaScript has three “primitive” types:  number ,  string , and  boolean Numbers are always stored as floating-point values Hexadecimal numbers begin with 0x Some platforms treat 0123 as octal, others treat it as decimal Strings may be enclosed in single quotes or double quotes Strings can contains \n (newline), \&quot; (double quote), etc. Booleans are either  true  or  false 0 ,   &quot;0&quot;,  empty strings,   undefined ,   null , and   NaN   are   false   , other values are  true
JavaScript Variable You create a variable with or without the “var” statement var  num = “1”; var  name = “Kaushal”; var  phone = “123-456-7890”; Variables names must begin with a letter or underscore Variable names are case-sensitive  Variables are  untyped  (they can hold values of any type) The word var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page)
Comments Comments are as in C or Java: Single Line Comment // Paragraph Comment /*….*/ Java’s  javadoc comments, /** ... */, are  treated just the  same as /* ... */ comments ; they have no special meaning in JavaScript
Operators of JavaScript 1 Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it Arithmetic operators:   +  -  *  /  %  ++  -- Comparison operators:   <  <=  ==  !=  >=  > Logical operators:   &&  ||  !  (&& and || are short-circuit operators) Bitwise operators:   &  |  ^  ~  <<  >>  >>> Assignment operators:   +=  -=  *=  /=  %=  <<=  >>=  >>>=  &=  ^=  |=
Operators of JavaScript 2 String operator:   + The conditional operator:   condition ? value_if_true : value_if_false Special equality tests: ==   and  !=  try to convert their operands to the same type before performing the test ===  and   !==   consider their operands  unequal  if they are of different types  Additional operators (to be discussed): new  typeof  void  delete
JavaScript Conditional Statements In JavaScript we have the following conditional statements: if statement   if...else statement   if...else if....else statement   s witch statement
JavaScript Looping Statement while  Syntax:  while ( condition ) {  code to be executed  }  d o...while   Syntax:  do {  code to be executed  } while ( condition )  For Syntax: for ( initialization ;  condition ;  increment )  {  code to be executed  } For…in Syntax: for ( variable  in  object )  {  code to be executed  }
Example of for..in Statement <html> <body> <script>  var person={fname:&quot;John&quot;,lname:&quot;Doe&quot;,age:25}; for (x in person) { document.write(person[x] + &quot; &quot;); } </script> </body> </html>
Array Literals You don’t declare the  types  of variables in JavaScript JavaScript has array  literals,  written with brackets and commas Example: color = [&quot;red&quot;, &quot;yellow&quot;, &quot;green&quot;, &quot;blue&quot;]; Arrays are zero-based: color[0] is &quot;red&quot; If you put two commas in a row, the array has an “empty” element in that location Example: color = [&quot;red&quot;, , , &quot;green&quot;, &quot;blue&quot;]; color has 5 elements However, a single comma at the end is ignored Example: color = [&quot;red&quot;, , , &quot;green&quot;, &quot;blue”,]; still has 5 elements
Four ways to create an Array You can use an array literal:   var colors = [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]; You can use new Array() to create an empty array: var colors = new Array(); You can add elements to the array later: colors[0] = &quot;red&quot;; colors[2] = &quot;blue&quot;; colors[1]=&quot;green&quot;; You can use new Array(n) with a single numeric argument to create an array of that size var colors = new Array(3); You can use new Array(…) with two or more arguments to create an array containing those values: var colors = new Array(&quot;red&quot;,&quot;green&quot;, &quot;blue&quot;);
The length of an array If myArray is an array, its length is given by myArray.length Array length can be changed by assignment beyond the current length Example: var myArray = new Array(5); myArray[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value Example: myArray[50000] = 3; is perfectly OK But indices must be between 0 and 2 32 -1 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]
Arrays and objects Arrays  are  objects car = { myCar: &quot;Saturn&quot;,  7: &quot;Mazda&quot; } car[7] is the same as car.7 car.myCar is the same as car[&quot;myCar&quot;] If you know the name of a property, you can use dot notation: car.myCar If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car.[&quot;my&quot; + &quot;Car&quot;]
Array functions If myArray is an array, myArray.sort() sorts the array alphabetically myArray.reverse() reverses the array elements myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length myArray.pop() removes and returns the last element of the array, and decrements the array’s length myArray.toString() returns a string containing the values of the array elements, separated by  commas
Exception Handling 1 Exception handling in JavaScript is  almost  the same as in Java throw expression creates and throws an exception The expression is the value of the exception, and can be of any type (often, it's a literal String) try {   statements to try } catch (e) {  // Notice: no type declaration for e   exception-handling statements } finally {  // optional, as usual   code that is always executed } With this form, there is only one catch clause
Exception Handling 2 try {   statements to try } catch (e if test1) {    exception-handling for the case that test1 is true } catch (e if test2) {    exception-handling for when test1 is false and test2 is true } catch (e) {    exception-handling for when both test1and test2 are false } finally {  // optional, as usual   code that is always executed } Typically, the test would be something like   e == &quot;InvalidNameException&quot;
JavaScript Popup Boxes Alert box User will have to click &quot;OK&quot; to proceed alert(&quot;sometext&quot;) Confirm box User will have to click either &quot;OK&quot; or &quot;Cancel&quot; to proceed confirm(&quot;sometext&quot;) Prompt box User will have to click either &quot;OK&quot; or &quot;Cancel&quot; to proceed after entering an input value prompt(&quot;sometext&quot;,&quot;defaultvalue&quot;)
JavaScript Functions JavaScript functions are created by the help of “function” keyword. Syntax: function function_name(arguments) {statement here} A JavaScript function contains some code that will be executed only by an event or by a call to that function To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file). Functions can be defined either <head> or <body> section. As a convention, they are typically defined in the <head> section
Example: JavaScript Function <html> <head> <script type=&quot;text/javascript&quot;> function displaymessage() {  alert(&quot;Hello World!&quot;) } </script> </head> <body> <form> <input type=&quot;button&quot; value=&quot;Click me!“ onclick=&quot;displaymessage()&quot; > </form> </body> </html>
Events & Event Handlers Every element on a web page has certain events which can trigger invocation of event handlers Attributes are inserted into HTML tags to define events and event handlers Examples of events A mouse click A web page or an image loading Mouse over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke
Events onabort - Loading of an image is interrupted onblur - An element loses focus onchange - The content of a field changes onclick - Mouse clicks an object ondblclick - Mouse double-clicks an object onerror - An error occurs when loading a document or an image onfocus - An element gets focus onkeydown - A keyboard key is pressed onkeypress - A keyboard key is pressed or held down onkeyup - A keyboard key is released onload - A page or an image is finished loading onmousedown - A mouse button is pressed onmousemove - The mouse is moved
Events onmouseout - The mouse is moved off an element onmouseover - The mouse is moved over an element onmouseup - A mouse button is released onreset - The reset button is clicked onresize - A window or frame is resized onselect - Text is selected onsubmit - The submit button is clicked onunload - The user exits the page
onSubmit The  onSubmit  event is used to validate all form fields before submitting it. Example: The  checkForm()  function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be canceled. The function  checkForm()  returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method=&quot;post&quot; action=&quot;xxx.html“ onsubmit=&quot;return  checkForm() &quot;>
Example & Demo: onSubmit <html> <head> <script type=&quot;text/javascript&quot;> function validate() { // return true or false based on validation logic } </script> </head> <body> <form action=&quot;tryjs_submitpage.htm&quot; onsubmit=&quot;return validate()&quot;> Name (max 10 chararcters): <input type=&quot;text&quot; id=&quot;fname&quot; size=&quot;20&quot;><br /> Age (from 1 to 100): <input type=&quot;text&quot; id=&quot;age&quot; size=&quot;20&quot;><br /> E-mail: <input type=&quot;text&quot; id=&quot;email&quot; size=&quot;20&quot;><br /> <br /> <input type=&quot;submit&quot; value=&quot;Submit&quot;> </form> </body> </html>
Example & Demo: onblur <html> <head> <script type=&quot;text/javascript&quot;> function upperCase() { var x=document.getElementById(&quot;fname&quot;).value document.getElementById(&quot;fname&quot;).value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type=&quot;text&quot; id=&quot;fname&quot; onblur=&quot;upperCase()&quot;> </body> </html>
JavaScript Object JavaScript is an Object Oriented Programming (OOP) language A JavaScript object has properties and methods Example:  String  JavaScript object has  length  property and  toUpperCase()  method <script type=&quot;text/javascript&quot;> var txt=&quot;Hello World!&quot; document.write(txt.length) document.write(txt.toUpperCase()) </script>
JavaScript Built-in Objects Array object Boolean object Date object Math object Number object String object Window object Navigator object Screen object History object Location object
Creating Your Own JavaScript Objects 3 different ways Create a direct instance of an object by using built-in constructor for the  Object  class Create a template (Constructor) first and then create an instance of an object from it Create object instance as Hash Literal
Option 1: Creating a Direct Instance of a JavaScript Object By invoking the built-in constructor for the Object class personObj=new Object(); // Initially empty with no properties or methods Add properties to it personObj.firstname=&quot;John&quot;; personObj.age=50; Add an anonymous function to the  personObj personObj.tellYourage=function(){ alert(“This age is ” + this.age); } // You can call then tellYourage function as following personObj.tellYourage();
Option 1:Creating a Direct Instance of a JavaScript Object Add a pre-defined function function tellYourage(){ alert(“The age is” + this.age); } personObj.tellYourage=tellYourage; Note that the following two lines of code are doing completely different things // Set property with a function personObj.tellYourage=tellYourage; // Set property with returned value of the function personObj.tellYourage=tellYourage();
Option 2: Creating a template of a JavaScript Object The template defines the structure of a JavaScript object in the form of a function You can think of the template as a constructor function Person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.tellYourage=function(){ alert(“This age is ” + this.age); } }
Option 2: Creating a template of a JavaScript Object Once you have the template, you can create new instances of the object myFather=new Person(&quot;John&quot;,&quot;Doe&quot;,50,&quot;blue&quot;); myMother=new Person(&quot;Sally&quot;,&quot;Rally&quot;,48,&quot;green&quot;); You can add new properties and functions to new objects myFather.newField = “some data”; myFather.myfunction = function() { alert(this[&quot;fullName&quot;] + ” is ” + this.age); }
Option 3: Creating JavaScript Object as a Hash Literal Create  personObj  JavaScript object var personObj = { firstname: &quot;John&quot;, lastname: &quot;Doe&quot;, age: 50, tellYourage: function () { alert(“The age is ” + this.age ); } tellSomething: function(something) { alert(something); } } personObj.tellYourage(); personObj.tellSomething(“Life is good!”);
HTML DOM The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents All HTML elements, along with their containing text and attributes, can be accessed through the DOM. The contents can be modified or deleted, and new elements can be created. JavaScript uses the HTML Document Object Model to manipulate HTML. Levels of the DOM are dot-separated in the syntax.
HTML DOM Objects Anchor object Document object Event object Form and Form Input object Frame, Frameset, and IFrame objects Image object Location object Navigator object Option and Select objects Screen object Table, TableHeader, TableRow, TableData objects Window object
Document Tree Structure
Document Object: Write text to the output <html> <body> <script type=&quot;text/javascript&quot;> document.write(“<h1>Hello World!</h1>&quot;) </script> </body> </html>
Document Object: Use getElementById() <html> <head> <script type=&quot;text/javascript&quot;> function getElement()  { var x=document.getElementById(&quot;myHeader&quot;) alert(&quot;I am a &quot; + x.tagName + &quot; element&quot;) } </script> </head> <body> <h1 id=&quot;myHeader&quot; onclick=&quot;getElement()&quot;>Click to see what element I am!</h1> </body> </html>
Document Object: Use getElementsByName() <html> <head> <script type=&quot;text/javascript&quot;> function getElements() { var x=document.getElementsByName(&quot;myInput&quot;) alert(x.length + &quot; elements!&quot;) } </script> </head> <body> <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br /> <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br /> <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br /> <br /> <input type=&quot;button&quot; onclick=&quot;getElements()&quot; value=&quot;How many elements named 'myInput'?&quot;> </body> </html>
Return the innerHTML of the first anchor in a document <html> <body> <a name=&quot;first&quot;>First anchor</a><br /> <a name=&quot;second&quot;>Second anchor</a><br /> <a name=&quot;third&quot;>Third anchor</a><br /> <br /> InnerHTML of the first anchor in this document: <script type=&quot;text/javascript&quot;> document.write(document.anchors[0].innerHTML) </script> </body> </html>
Event Object: What are the coordinates of the cursor? <html> <head> <script type=&quot;text/javascript&quot;> function show_coords(event) { x=event.clientX y=event.clientY alert(&quot;X coords: &quot; + x + &quot;, Y coords: &quot; + y) } </script> </head> <body onmousedown=&quot;show_coords(event)&quot;> <p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html>
Event Object: What is the unicode of the key pressed? <html> <head> <script type=&quot;text/javascript&quot;> function whichButton(event) { alert(event.keyCode) } </script> </head> <body onkeyup=&quot;whichButton(event)&quot;> <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p> <p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p> </body> </html>
Event Object: Which event type occurred? <html> <head> <script type=&quot;text/javascript&quot;> function whichType(event) { alert(event.type) } </script> </head> <body onmousedown=&quot;whichType(event)&quot;> <p> Click on the document. An alert box will alert which type of event occurred. </p> </body> </html>
Questions
Thank you for your Time and Attention! For more information visit http://adhouraacademy.com Or drop-in an email to kaushal.rahuljaiswal@gmail.com

More Related Content

What's hot (20)

3. Java Script
3. Java Script3. Java Script
3. Java Script
Jalpesh Vasa
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
Nir Kaufman
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
shreesenthil
 
React js
React jsReact js
React js
Rajesh Kolla
 
Java script
Java scriptJava script
Java script
Sadeek Mohammed
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Javascript
JavascriptJavascript
Javascript
Nagarajan
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
jQuery
jQueryjQuery
jQuery
Dileep Mishra
 
Jquery
JqueryJquery
Jquery
Girish Srivastava
 
React js
React jsReact js
React js
Oswald Campesato
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
ReactJs
ReactJsReactJs
ReactJs
Sahana Banerjee
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
Nir Kaufman
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 

Viewers also liked (20)

Java script
Java scriptJava script
Java script
Shyam Khant
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Java script
Java scriptJava script
Java script
Fajar Baskoro
 
Java script
Java scriptJava script
Java script
Soham Sengupta
 
A quick guide to Css and java script
A quick guide to Css and  java scriptA quick guide to Css and  java script
A quick guide to Css and java script
AVINASH KUMAR
 
Java script
Java scriptJava script
Java script
Jay Patel
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
Sun Technlogies
 
Javascript conditional statements 1
Javascript conditional statements 1Javascript conditional statements 1
Javascript conditional statements 1
Jesus Obenita Jr.
 
Ajax
AjaxAjax
Ajax
gauravashq
 
AK css
AK cssAK css
AK css
gauravashq
 
1 introduction to xml
1   introduction to xml1   introduction to xml
1 introduction to xml
gauravashq
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
Mohammad Shaker
 
Java script
Java scriptJava script
Java script
Abhishek Kesharwani
 
Inside jQuery (2011)
Inside jQuery (2011)Inside jQuery (2011)
Inside jQuery (2011)
Kenneth Auchenberg
 
JSON - Quick Overview
JSON - Quick OverviewJSON - Quick Overview
JSON - Quick Overview
Signure Technologies
 
3 xml namespaces and xml schema
3   xml namespaces and xml schema3   xml namespaces and xml schema
3 xml namespaces and xml schema
gauravashq
 
5 xsl (formatting xml documents)
5   xsl (formatting xml documents)5   xsl (formatting xml documents)
5 xsl (formatting xml documents)
gauravashq
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
gauravashq
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
A quick guide to Css and java script
A quick guide to Css and  java scriptA quick guide to Css and  java script
A quick guide to Css and java script
AVINASH KUMAR
 
HTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts BasicsHTML, CSS and Java Scripts Basics
HTML, CSS and Java Scripts Basics
Sun Technlogies
 
Javascript conditional statements 1
Javascript conditional statements 1Javascript conditional statements 1
Javascript conditional statements 1
Jesus Obenita Jr.
 
1 introduction to xml
1   introduction to xml1   introduction to xml
1 introduction to xml
gauravashq
 
C++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+OperatorsC++ L02-Conversion+enum+Operators
C++ L02-Conversion+enum+Operators
Mohammad Shaker
 
3 xml namespaces and xml schema
3   xml namespaces and xml schema3   xml namespaces and xml schema
3 xml namespaces and xml schema
gauravashq
 
5 xsl (formatting xml documents)
5   xsl (formatting xml documents)5   xsl (formatting xml documents)
5 xsl (formatting xml documents)
gauravashq
 
Ad

Similar to Java script final presentation (20)

Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
JavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascriptaJavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascripta
nehatanveer5765
 
Presentation JavaScript Introduction Data Types Variables Control Structure
Presentation JavaScript Introduction  Data Types Variables Control StructurePresentation JavaScript Introduction  Data Types Variables Control Structure
Presentation JavaScript Introduction Data Types Variables Control Structure
SripathiRavi1
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
KennyPratheepKumar
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
SadhanaParameswaran
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
JavaScript
JavaScriptJavaScript
JavaScript
Doncho Minkov
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
rashmiisrani1
 
Javascript
JavascriptJavascript
Javascript
vikram singh
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
introduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptxintroduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptx
gayatridwahane
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
JavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascriptaJavaScript ppt for introduction of javascripta
JavaScript ppt for introduction of javascripta
nehatanveer5765
 
Presentation JavaScript Introduction Data Types Variables Control Structure
Presentation JavaScript Introduction  Data Types Variables Control StructurePresentation JavaScript Introduction  Data Types Variables Control Structure
Presentation JavaScript Introduction Data Types Variables Control Structure
SripathiRavi1
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
Bernard Loire
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 
introduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptxintroduction to java scriptsfor sym.pptx
introduction to java scriptsfor sym.pptx
gayatridwahane
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Ad

More from Adhoura Academy (7)

Docker Presentation
Docker PresentationDocker Presentation
Docker Presentation
Adhoura Academy
 
Google Dorks
Google DorksGoogle Dorks
Google Dorks
Adhoura Academy
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
Adhoura Academy
 
Drupal Content Management System
Drupal Content Management SystemDrupal Content Management System
Drupal Content Management System
Adhoura Academy
 
Content management system
Content management systemContent management system
Content management system
Adhoura Academy
 
Android Presentation
Android PresentationAndroid Presentation
Android Presentation
Adhoura Academy
 
Open Source Presentation
Open Source PresentationOpen Source Presentation
Open Source Presentation
Adhoura Academy
 

Recently uploaded (20)

ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Top 25 AI Coding Agents for Vibe Coders to Use in 2025.pdf
Top 25 AI Coding Agents for Vibe Coders to Use in 2025.pdfTop 25 AI Coding Agents for Vibe Coders to Use in 2025.pdf
Top 25 AI Coding Agents for Vibe Coders to Use in 2025.pdf
SOFTTECHHUB
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
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
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
IntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdfIntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdf
Luiz Carneiro
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
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
 
Compliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf textCompliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf text
Earthling security
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Top 25 AI Coding Agents for Vibe Coders to Use in 2025.pdf
Top 25 AI Coding Agents for Vibe Coders to Use in 2025.pdfTop 25 AI Coding Agents for Vibe Coders to Use in 2025.pdf
Top 25 AI Coding Agents for Vibe Coders to Use in 2025.pdf
SOFTTECHHUB
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
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
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
IntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdfIntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdf
Luiz Carneiro
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
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
 
Compliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf textCompliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf text
Earthling security
 

Java script final presentation

  • 1. Building Web Sites: Introduction to JavaScript Kaushal Kishore Software Engineer OSSCube LLC [email_address] www.adhouraacademy.com
  • 2. What is JavaScript JavaScript was originally developed by Brendan Eich of Netscape under the name  Mocha , which was later renamed to  LiveScript , and finally to JavaScript A lightweight programming language that runs in a Web browser JavaScript is a Client Side Scripting Language. Also known as ECMAScript  Interpreted, not compiled. JavaScript Syntax are similar to C and Java Language. JavaScript code is usually embedded directly into HTML pages JavaScript is reasonably platform-independent
  • 3. What Can JavaScript Do? JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate input data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies
  • 4. When not to use JavaScript When you need to access other resources. Files Programs Databases When you are using sensitive or copyrighted data or algorithms. Your JavaScript code is open to the public .
  • 5. JavaScript is not Java Java and JavaScript are two completely different languages in both concept and design! JavaScript has some features that resemble features in Java: JavaScript has Objects and primitive data types JavaScript has qualified names; for example, document.write(&quot;Hello World&quot;); JavaScript has Events and event handlers Exception handling in JavaScript is almost the same as in Java JavaScript has some features unlike anything in Java: Variable names are untyped: the type of a variable depends on the value it is currently holding Objects and arrays are defined in quite a different way JavaScript is an interpreted language but java is both interpreted and compiled
  • 6. Where Do You Place Scripts? JavaScript can be put in the <head> or in the <body> of an HTML document JavaScript functions should be defined in the <head> This ensures that the function is loaded before it is needed JavaScript in the <body> will be executed as the page loads JavaScript can be put in a separate .js file <script src=&quot;myJavaScriptFile.js&quot;></script> Put this HTML wherever you would put the actual JavaScript code An external .js file lets you use the same JavaScript on multiple HTML pages The external .js file cannot itself contain a <script> tag JavaScript can be put in HTML form object, such as a button This JavaScript will be executed when the form object is used
  • 7. Referencing External JavaScript File Scripts can be provided locally or remotely accessible JavaScript file using src attribute <html> <head> <script language=&quot;JavaScript“ type=&quot;text/javascript“ src=&quot;http://somesite/myOwnJavaScript.js&quot;> </script> <script language=&quot;JavaScript“ type=&quot;text/javascript“ src=&quot;myOwnSubdirectory/myOwn2ndJavaScript.js&quot;> </script>
  • 8. Primitive Datatypes JavaScript has three “primitive” types: number , string , and boolean Numbers are always stored as floating-point values Hexadecimal numbers begin with 0x Some platforms treat 0123 as octal, others treat it as decimal Strings may be enclosed in single quotes or double quotes Strings can contains \n (newline), \&quot; (double quote), etc. Booleans are either true or false 0 , &quot;0&quot;, empty strings, undefined , null , and NaN are false , other values are true
  • 9. JavaScript Variable You create a variable with or without the “var” statement var num = “1”; var name = “Kaushal”; var phone = “123-456-7890”; Variables names must begin with a letter or underscore Variable names are case-sensitive Variables are untyped (they can hold values of any type) The word var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page)
  • 10. Comments Comments are as in C or Java: Single Line Comment // Paragraph Comment /*….*/ Java’s javadoc comments, /** ... */, are treated just the same as /* ... */ comments ; they have no special meaning in JavaScript
  • 11. Operators of JavaScript 1 Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it Arithmetic operators: + - * / % ++ -- Comparison operators: < <= == != >= > Logical operators: && || ! (&& and || are short-circuit operators) Bitwise operators: & | ^ ~ << >> >>> Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= |=
  • 12. Operators of JavaScript 2 String operator: + The conditional operator: condition ? value_if_true : value_if_false Special equality tests: == and != try to convert their operands to the same type before performing the test === and !== consider their operands unequal if they are of different types Additional operators (to be discussed): new typeof void delete
  • 13. JavaScript Conditional Statements In JavaScript we have the following conditional statements: if statement if...else statement if...else if....else statement s witch statement
  • 14. JavaScript Looping Statement while  Syntax: while ( condition ) { code to be executed } d o...while Syntax: do { code to be executed } while ( condition ) For Syntax: for ( initialization ; condition ; increment ) { code to be executed } For…in Syntax: for ( variable  in  object ) { code to be executed }
  • 15. Example of for..in Statement <html> <body> <script> var person={fname:&quot;John&quot;,lname:&quot;Doe&quot;,age:25}; for (x in person) { document.write(person[x] + &quot; &quot;); } </script> </body> </html>
  • 16. Array Literals You don’t declare the types of variables in JavaScript JavaScript has array literals, written with brackets and commas Example: color = [&quot;red&quot;, &quot;yellow&quot;, &quot;green&quot;, &quot;blue&quot;]; Arrays are zero-based: color[0] is &quot;red&quot; If you put two commas in a row, the array has an “empty” element in that location Example: color = [&quot;red&quot;, , , &quot;green&quot;, &quot;blue&quot;]; color has 5 elements However, a single comma at the end is ignored Example: color = [&quot;red&quot;, , , &quot;green&quot;, &quot;blue”,]; still has 5 elements
  • 17. Four ways to create an Array You can use an array literal: var colors = [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]; You can use new Array() to create an empty array: var colors = new Array(); You can add elements to the array later: colors[0] = &quot;red&quot;; colors[2] = &quot;blue&quot;; colors[1]=&quot;green&quot;; You can use new Array(n) with a single numeric argument to create an array of that size var colors = new Array(3); You can use new Array(…) with two or more arguments to create an array containing those values: var colors = new Array(&quot;red&quot;,&quot;green&quot;, &quot;blue&quot;);
  • 18. The length of an array If myArray is an array, its length is given by myArray.length Array length can be changed by assignment beyond the current length Example: var myArray = new Array(5); myArray[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value Example: myArray[50000] = 3; is perfectly OK But indices must be between 0 and 2 32 -1 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]
  • 19. Arrays and objects Arrays are objects car = { myCar: &quot;Saturn&quot;, 7: &quot;Mazda&quot; } car[7] is the same as car.7 car.myCar is the same as car[&quot;myCar&quot;] If you know the name of a property, you can use dot notation: car.myCar If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car.[&quot;my&quot; + &quot;Car&quot;]
  • 20. Array functions If myArray is an array, myArray.sort() sorts the array alphabetically myArray.reverse() reverses the array elements myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length myArray.pop() removes and returns the last element of the array, and decrements the array’s length myArray.toString() returns a string containing the values of the array elements, separated by commas
  • 21. Exception Handling 1 Exception handling in JavaScript is almost the same as in Java throw expression creates and throws an exception The expression is the value of the exception, and can be of any type (often, it's a literal String) try { statements to try } catch (e) { // Notice: no type declaration for e exception-handling statements } finally { // optional, as usual code that is always executed } With this form, there is only one catch clause
  • 22. Exception Handling 2 try { statements to try } catch (e if test1) { exception-handling for the case that test1 is true } catch (e if test2) { exception-handling for when test1 is false and test2 is true } catch (e) { exception-handling for when both test1and test2 are false } finally { // optional, as usual code that is always executed } Typically, the test would be something like e == &quot;InvalidNameException&quot;
  • 23. JavaScript Popup Boxes Alert box User will have to click &quot;OK&quot; to proceed alert(&quot;sometext&quot;) Confirm box User will have to click either &quot;OK&quot; or &quot;Cancel&quot; to proceed confirm(&quot;sometext&quot;) Prompt box User will have to click either &quot;OK&quot; or &quot;Cancel&quot; to proceed after entering an input value prompt(&quot;sometext&quot;,&quot;defaultvalue&quot;)
  • 24. JavaScript Functions JavaScript functions are created by the help of “function” keyword. Syntax: function function_name(arguments) {statement here} A JavaScript function contains some code that will be executed only by an event or by a call to that function To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file). Functions can be defined either <head> or <body> section. As a convention, they are typically defined in the <head> section
  • 25. Example: JavaScript Function <html> <head> <script type=&quot;text/javascript&quot;> function displaymessage() { alert(&quot;Hello World!&quot;) } </script> </head> <body> <form> <input type=&quot;button&quot; value=&quot;Click me!“ onclick=&quot;displaymessage()&quot; > </form> </body> </html>
  • 26. Events & Event Handlers Every element on a web page has certain events which can trigger invocation of event handlers Attributes are inserted into HTML tags to define events and event handlers Examples of events A mouse click A web page or an image loading Mouse over a hot spot on the web page Selecting an input box in an HTML form Submitting an HTML form A keystroke
  • 27. Events onabort - Loading of an image is interrupted onblur - An element loses focus onchange - The content of a field changes onclick - Mouse clicks an object ondblclick - Mouse double-clicks an object onerror - An error occurs when loading a document or an image onfocus - An element gets focus onkeydown - A keyboard key is pressed onkeypress - A keyboard key is pressed or held down onkeyup - A keyboard key is released onload - A page or an image is finished loading onmousedown - A mouse button is pressed onmousemove - The mouse is moved
  • 28. Events onmouseout - The mouse is moved off an element onmouseover - The mouse is moved over an element onmouseup - A mouse button is released onreset - The reset button is clicked onresize - A window or frame is resized onselect - Text is selected onsubmit - The submit button is clicked onunload - The user exits the page
  • 29. onSubmit The onSubmit event is used to validate all form fields before submitting it. Example: The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be canceled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method=&quot;post&quot; action=&quot;xxx.html“ onsubmit=&quot;return checkForm() &quot;>
  • 30. Example & Demo: onSubmit <html> <head> <script type=&quot;text/javascript&quot;> function validate() { // return true or false based on validation logic } </script> </head> <body> <form action=&quot;tryjs_submitpage.htm&quot; onsubmit=&quot;return validate()&quot;> Name (max 10 chararcters): <input type=&quot;text&quot; id=&quot;fname&quot; size=&quot;20&quot;><br /> Age (from 1 to 100): <input type=&quot;text&quot; id=&quot;age&quot; size=&quot;20&quot;><br /> E-mail: <input type=&quot;text&quot; id=&quot;email&quot; size=&quot;20&quot;><br /> <br /> <input type=&quot;submit&quot; value=&quot;Submit&quot;> </form> </body> </html>
  • 31. Example & Demo: onblur <html> <head> <script type=&quot;text/javascript&quot;> function upperCase() { var x=document.getElementById(&quot;fname&quot;).value document.getElementById(&quot;fname&quot;).value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type=&quot;text&quot; id=&quot;fname&quot; onblur=&quot;upperCase()&quot;> </body> </html>
  • 32. JavaScript Object JavaScript is an Object Oriented Programming (OOP) language A JavaScript object has properties and methods Example: String JavaScript object has length property and toUpperCase() method <script type=&quot;text/javascript&quot;> var txt=&quot;Hello World!&quot; document.write(txt.length) document.write(txt.toUpperCase()) </script>
  • 33. JavaScript Built-in Objects Array object Boolean object Date object Math object Number object String object Window object Navigator object Screen object History object Location object
  • 34. Creating Your Own JavaScript Objects 3 different ways Create a direct instance of an object by using built-in constructor for the Object class Create a template (Constructor) first and then create an instance of an object from it Create object instance as Hash Literal
  • 35. Option 1: Creating a Direct Instance of a JavaScript Object By invoking the built-in constructor for the Object class personObj=new Object(); // Initially empty with no properties or methods Add properties to it personObj.firstname=&quot;John&quot;; personObj.age=50; Add an anonymous function to the personObj personObj.tellYourage=function(){ alert(“This age is ” + this.age); } // You can call then tellYourage function as following personObj.tellYourage();
  • 36. Option 1:Creating a Direct Instance of a JavaScript Object Add a pre-defined function function tellYourage(){ alert(“The age is” + this.age); } personObj.tellYourage=tellYourage; Note that the following two lines of code are doing completely different things // Set property with a function personObj.tellYourage=tellYourage; // Set property with returned value of the function personObj.tellYourage=tellYourage();
  • 37. Option 2: Creating a template of a JavaScript Object The template defines the structure of a JavaScript object in the form of a function You can think of the template as a constructor function Person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.tellYourage=function(){ alert(“This age is ” + this.age); } }
  • 38. Option 2: Creating a template of a JavaScript Object Once you have the template, you can create new instances of the object myFather=new Person(&quot;John&quot;,&quot;Doe&quot;,50,&quot;blue&quot;); myMother=new Person(&quot;Sally&quot;,&quot;Rally&quot;,48,&quot;green&quot;); You can add new properties and functions to new objects myFather.newField = “some data”; myFather.myfunction = function() { alert(this[&quot;fullName&quot;] + ” is ” + this.age); }
  • 39. Option 3: Creating JavaScript Object as a Hash Literal Create personObj JavaScript object var personObj = { firstname: &quot;John&quot;, lastname: &quot;Doe&quot;, age: 50, tellYourage: function () { alert(“The age is ” + this.age ); } tellSomething: function(something) { alert(something); } } personObj.tellYourage(); personObj.tellSomething(“Life is good!”);
  • 40. HTML DOM The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents All HTML elements, along with their containing text and attributes, can be accessed through the DOM. The contents can be modified or deleted, and new elements can be created. JavaScript uses the HTML Document Object Model to manipulate HTML. Levels of the DOM are dot-separated in the syntax.
  • 41. HTML DOM Objects Anchor object Document object Event object Form and Form Input object Frame, Frameset, and IFrame objects Image object Location object Navigator object Option and Select objects Screen object Table, TableHeader, TableRow, TableData objects Window object
  • 43. Document Object: Write text to the output <html> <body> <script type=&quot;text/javascript&quot;> document.write(“<h1>Hello World!</h1>&quot;) </script> </body> </html>
  • 44. Document Object: Use getElementById() <html> <head> <script type=&quot;text/javascript&quot;> function getElement() { var x=document.getElementById(&quot;myHeader&quot;) alert(&quot;I am a &quot; + x.tagName + &quot; element&quot;) } </script> </head> <body> <h1 id=&quot;myHeader&quot; onclick=&quot;getElement()&quot;>Click to see what element I am!</h1> </body> </html>
  • 45. Document Object: Use getElementsByName() <html> <head> <script type=&quot;text/javascript&quot;> function getElements() { var x=document.getElementsByName(&quot;myInput&quot;) alert(x.length + &quot; elements!&quot;) } </script> </head> <body> <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br /> <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br /> <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br /> <br /> <input type=&quot;button&quot; onclick=&quot;getElements()&quot; value=&quot;How many elements named 'myInput'?&quot;> </body> </html>
  • 46. Return the innerHTML of the first anchor in a document <html> <body> <a name=&quot;first&quot;>First anchor</a><br /> <a name=&quot;second&quot;>Second anchor</a><br /> <a name=&quot;third&quot;>Third anchor</a><br /> <br /> InnerHTML of the first anchor in this document: <script type=&quot;text/javascript&quot;> document.write(document.anchors[0].innerHTML) </script> </body> </html>
  • 47. Event Object: What are the coordinates of the cursor? <html> <head> <script type=&quot;text/javascript&quot;> function show_coords(event) { x=event.clientX y=event.clientY alert(&quot;X coords: &quot; + x + &quot;, Y coords: &quot; + y) } </script> </head> <body onmousedown=&quot;show_coords(event)&quot;> <p>Click in the document. An alert box will alert the x and y coordinates of the cursor.</p> </body> </html>
  • 48. Event Object: What is the unicode of the key pressed? <html> <head> <script type=&quot;text/javascript&quot;> function whichButton(event) { alert(event.keyCode) } </script> </head> <body onkeyup=&quot;whichButton(event)&quot;> <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p> <p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p> </body> </html>
  • 49. Event Object: Which event type occurred? <html> <head> <script type=&quot;text/javascript&quot;> function whichType(event) { alert(event.type) } </script> </head> <body onmousedown=&quot;whichType(event)&quot;> <p> Click on the document. An alert box will alert which type of event occurred. </p> </body> </html>
  • 51. Thank you for your Time and Attention! For more information visit http://adhouraacademy.com Or drop-in an email to [email protected]