SlideShare a Scribd company logo
JAVA SCRIPT
It is case sensitive language.
alert('hello');
Message
document.write('we are learning javascript');
Display
// Coments
Documentation/Comments
document.write('we are learning javascript');
Display
External File Support
1.Make new file
2.Write java code with ext js
3.Don’t need to write script tags in js files
4.<script scr = “ path of file ”>
DATA TYPES
String ‘shahwaiz’
Integer 6, 7, 9
Variable assign value, simple text
Space not allowed
name = ‘shahwaiz’;
document.write(name);
DATA TYPES
V1=3
V2=4
document.write(v1+v2);
alert(v1+v2);
USING HTML IN JAVA SCRIPT
Document.write(‘<h1>html</h1>in java script’);
Document.write(‘style=“background:red”java script’);
POP UP BOX
Prompt(‘Enter your name’,’name’);
name = Prompt(‘Enter your name’,’name’)
document.write(‘hello<h3>’+name+’</h3>welcome’);
MATH OPERATOR +
-
*
/
%
=
++
--
IF-ELSE var = 3
var2=4
if(var==3){
alert(‘Display’);
}
!== -> type
===
LOGICAL OP
&&
||
!
FUNCTION
Function myFunction()
{
document.write(‘this is function’);
}
myFunction();
JAVASCRIPT OBJECTS
Real Life Objects, Properties,
and Methods
A car has properties like weight
and color, and methods like start
and stop:
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Variable.</p>
<p id="demo"></p>
<script>
var car = "Fiat";
document.getElementById("demo").innerHTML
= car;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var car = {type:"Fiat", model:"500", color:"white"};
document.getElementById("demo").innerHTML = car.type;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
ACCESSING OBJECT PROPERTIES
objectName.propertyName
Or
objectName["propertyName"]
p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566
};
document.getElementById("demo").innerHTML
=
person.firstName + " " + person.lastName;
</script>
ACCESSING OBJECT METHODS
objectName.methodName()
or
name = person.fullName();
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
document.getElementById("demo").innerHTML =
person.fullName();
</script>
JAVASCRIPT EVENTS
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on these events.
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
COMMON HTML EVENTS
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
SAMPLES
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
<button onclick="this.innerHTML = Date()">The time is?</button>
<button onclick="displayDate()">The time is?</button>
STRING
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = txt.length;
</script>
SPECIAL CHARACTERS
The backslash () escape character turns special characters into string characters:
' ' Single quote
" " Double quote
  Backslash
SIX OTHER ESCAPE SEQUENCES ARE VALID IN
JAVASCRIPT:
b Backspace
f Form Feed
n New Line
r Carriage Return
t Horizontal Tabulator
v Vertical Tabulator
STR METHOD
The indexOf() method returns the index of (the position of)
the first occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
The lastIndexOf() method returns the index of
the last occurrence of a specified text in a string:
Both methods accept a second parameter as the starting
position for the search:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate",15);
The search() method searches a string for a specified value
and returns the position of the match:
EXTRACTING STRING PARTS
• slice(start, end)
• substring(start, end)
• substr(start, length)
REPLACING STRING CONTENT
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
By default, the replace() function is case sensitive. Writing
MICROSOFT (with upper-case) will not work:
o replace case insensitive, use a regular expression with
an /i flag (insensitive):
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools");
To replace all matches, use a regular expression with a /g flag (global match):
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");
JAVASCRIPT NUMBERS
JavaScript has only one type of number. Numbers can be written with or without decimals.
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
If you add two numbers, the result will be a number:
If you add two strings, the result will be a string concatenation:
If you add a number and a string, the result will be a string concatenation:
If you add a string and a number, the result will be a string concatenation:
NUMBER METHOD
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
TOFIXED()
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
TOPRECISION()
toPrecision() returns a string, with a number written with a specified length:
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
JAVASCRIPT MATH OBJECT
The JavaScript Math object allows you to perform mathematical tasks on
numbers.
Math.PI; // returns 3.141592653589793
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.pow(8, 2); // returns 64
Math.sqrt(64); // returns 8
Math.abs(-4.7); // returns 4.7
Math.ceil(4.4); // returns 5
Math.floor(4.7); // returns 4
JAVASCRIPT MATH OBJECT
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)
Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Math.random(); // returns a random number
JAVASCRIPT MATH OBJECT
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
JAVASCRIPT RANDOM
Math.floor(Math.random() * 10); // returns a number between 0 and 9
Math.floor(Math.random() * 11); // returns a number between 0 and 10
Math.floor(Math.random() * 100); // returns a number between 0 and 99
JAVASCRIPT DATES
var d = new Date();
document.getElementById("demo").innerHTML = d;
• Years
• Months
• Days
• Hours
• Seconds
• Milliseconds
• JavaScript can display the current date as a full string:
• Sun Apr 08 2018 23:28:32 GMT+0500 (Pakistan Standard Time)
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
JAVASCRIPT DATE INPUT
Type Example
ISO Date "2015-03-25" (The International Standard)
Short Date "03/25/2015"
Long Date "Mar 25 2015" or "25 Mar 2015"
Full Date "Wednesday March 25 2015"
JAVASCRIPT GET DATE METHODS
Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
JAVASCRIPT GET DATE METHODS
Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
JAVASCRIPT SET DATE METHODS
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
<script>
var d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>
JAVASCRIPT ARRAYS
JavaScript arrays are used to store multiple values in a single variable.
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
cars[0] = "Opel";
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
ACCESS THE FULL ARRAY
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
REVERSING AN ARRAY
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements
JAVASCRIPT TYPE CONVERSION
In JavaScript there are 5 different data types that can
contain values:
• string
• number
• boolean
• object
• function
There are 3 types of objects:
Object
Date
Array
And 2 data types that cannot contain values:
null
undefined
THE TYPEOF OPERATOR
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object“
The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently
returned when some mathematical operation failed
JAVASCRIPT ERRORS - THROW AND TRY TO CATCH
• The try statement lets you test a block of code for errors.
• The catch statement lets you handle the error.
• The throw statement lets you create custom errors.
• The finally statement lets you execute code, after try and catch, regardless of the result.

More Related Content

What's hot

What's hot (20)

RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
syed
syedsyed
syed
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile services
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212
 
The Ring programming language version 1.2 book - Part 19 of 84
The Ring programming language version 1.2 book - Part 19 of 84The Ring programming language version 1.2 book - Part 19 of 84
The Ring programming language version 1.2 book - Part 19 of 84
 
Lenses
LensesLenses
Lenses
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
37c
37c37c
37c
 
Lekcja stylu
Lekcja styluLekcja stylu
Lekcja stylu
 
C++ Windows Forms L08 - GDI P1
C++ Windows Forms L08 - GDI P1 C++ Windows Forms L08 - GDI P1
C++ Windows Forms L08 - GDI P1
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 

Similar to Java script

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
saydin_soft
 

Similar to Java script (20)

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 

Recently uploaded

Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 

Recently uploaded (20)

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
NLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptxNLC-2024-Orientation-for-RO-SDO (1).pptx
NLC-2024-Orientation-for-RO-SDO (1).pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

Java script

  • 2.
  • 3.
  • 4.
  • 5. It is case sensitive language. alert('hello'); Message document.write('we are learning javascript'); Display
  • 7. External File Support 1.Make new file 2.Write java code with ext js 3.Don’t need to write script tags in js files 4.<script scr = “ path of file ”>
  • 8. DATA TYPES String ‘shahwaiz’ Integer 6, 7, 9 Variable assign value, simple text Space not allowed name = ‘shahwaiz’; document.write(name);
  • 10. USING HTML IN JAVA SCRIPT Document.write(‘<h1>html</h1>in java script’); Document.write(‘style=“background:red”java script’);
  • 11. POP UP BOX Prompt(‘Enter your name’,’name’); name = Prompt(‘Enter your name’,’name’) document.write(‘hello<h3>’+name+’</h3>welcome’);
  • 13. IF-ELSE var = 3 var2=4 if(var==3){ alert(‘Display’); } !== -> type ===
  • 16. JAVASCRIPT OBJECTS Real Life Objects, Properties, and Methods A car has properties like weight and color, and methods like start and stop: <!DOCTYPE html> <html> <body> <p>Creating a JavaScript Variable.</p> <p id="demo"></p> <script> var car = "Fiat"; document.getElementById("demo").innerHTML = car; </script> </body> </html>
  • 17. <!DOCTYPE html> <html> <body> <p>Creating a JavaScript Object.</p> <p id="demo"></p> <script> var car = {type:"Fiat", model:"500", color:"white"}; document.getElementById("demo").innerHTML = car.type; </script> </body> </html>
  • 18. <!DOCTYPE html> <html> <body> <p>Creating a JavaScript Object.</p> <p id="demo"></p> <script> var person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue" }; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
  • 19. ACCESSING OBJECT PROPERTIES objectName.propertyName Or objectName["propertyName"] p id="demo"></p> <script> var person = { firstName: "John", lastName : "Doe", id : 5566 }; document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName; </script>
  • 20. ACCESSING OBJECT METHODS objectName.methodName() or name = person.fullName(); <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; document.getElementById("demo").innerHTML = person.fullName(); </script>
  • 21. JAVASCRIPT EVENTS • HTML events are "things" that happen to HTML elements. • When JavaScript is used in HTML pages, JavaScript can "react" on these events. • An HTML web page has finished loading • An HTML input field was changed • An HTML button was clicked
  • 22. COMMON HTML EVENTS onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page
  • 23. SAMPLES <button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button> <button onclick="this.innerHTML = Date()">The time is?</button> <button onclick="displayDate()">The time is?</button>
  • 24. STRING <script> var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = txt.length; </script>
  • 25. SPECIAL CHARACTERS The backslash () escape character turns special characters into string characters: ' ' Single quote " " Double quote Backslash
  • 26. SIX OTHER ESCAPE SEQUENCES ARE VALID IN JAVASCRIPT: b Backspace f Form Feed n New Line r Carriage Return t Horizontal Tabulator v Vertical Tabulator
  • 27. STR METHOD The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string: var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate");
  • 28. The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: Both methods accept a second parameter as the starting position for the search: var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate",15); The search() method searches a string for a specified value and returns the position of the match:
  • 29. EXTRACTING STRING PARTS • slice(start, end) • substring(start, end) • substr(start, length)
  • 30. REPLACING STRING CONTENT str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3Schools"); By default, the replace() function is case sensitive. Writing MICROSOFT (with upper-case) will not work: o replace case insensitive, use a regular expression with an /i flag (insensitive): str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3Schools");
  • 31. To replace all matches, use a regular expression with a /g flag (global match): str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools");
  • 32. JAVASCRIPT NUMBERS JavaScript has only one type of number. Numbers can be written with or without decimals. var x = 123e5; // 12300000 var y = 123e-5; // 0.00123 If you add two numbers, the result will be a number: If you add two strings, the result will be a string concatenation: If you add a number and a string, the result will be a string concatenation: If you add a string and a number, the result will be a string concatenation:
  • 33. NUMBER METHOD var x = 123; x.toString(); // returns 123 from variable x (123).toString(); // returns 123 from literal 123 (100 + 23).toString(); // returns 123 from expression 100 + 23 var x = 9.656; x.toExponential(2); // returns 9.66e+0 x.toExponential(4); // returns 9.6560e+0 x.toExponential(6); // returns 9.656000e+0
  • 34. TOFIXED() var x = 9.656; x.toFixed(0); // returns 10 x.toFixed(2); // returns 9.66 x.toFixed(4); // returns 9.6560 x.toFixed(6); // returns 9.656000
  • 35. TOPRECISION() toPrecision() returns a string, with a number written with a specified length: var x = 9.656; x.toPrecision(); // returns 9.656 x.toPrecision(2); // returns 9.7 x.toPrecision(4); // returns 9.656 x.toPrecision(6); // returns 9.65600
  • 36. JAVASCRIPT MATH OBJECT The JavaScript Math object allows you to perform mathematical tasks on numbers. Math.PI; // returns 3.141592653589793 Math.round(4.7); // returns 5 Math.round(4.4); // returns 4 Math.pow(8, 2); // returns 64 Math.sqrt(64); // returns 8 Math.abs(-4.7); // returns 4.7 Math.ceil(4.4); // returns 5 Math.floor(4.7); // returns 4
  • 37. JAVASCRIPT MATH OBJECT Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees) Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees) Math.min(0, 150, 30, 20, -8, -200); // returns -200 Math.random(); // returns a random number
  • 38. JAVASCRIPT MATH OBJECT Math.E // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E
  • 39. JAVASCRIPT RANDOM Math.floor(Math.random() * 10); // returns a number between 0 and 9 Math.floor(Math.random() * 11); // returns a number between 0 and 10 Math.floor(Math.random() * 100); // returns a number between 0 and 99
  • 40. JAVASCRIPT DATES var d = new Date(); document.getElementById("demo").innerHTML = d; • Years • Months • Days • Hours • Seconds • Milliseconds
  • 41. • JavaScript can display the current date as a full string: • Sun Apr 08 2018 23:28:32 GMT+0500 (Pakistan Standard Time) There are 4 ways of initiating a date: new Date() new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds)
  • 42. JAVASCRIPT DATE INPUT Type Example ISO Date "2015-03-25" (The International Standard) Short Date "03/25/2015" Long Date "Mar 25 2015" or "25 Mar 2015" Full Date "Wednesday March 25 2015"
  • 43. JAVASCRIPT GET DATE METHODS Method Description getFullYear() Get the year as a four digit number (yyyy) getMonth() Get the month as a number (0-11) getDate() Get the day as a number (1-31) getHours() Get the hour (0-23) getMinutes() Get the minute (0-59) getSeconds() Get the second (0-59) getMilliseconds() Get the millisecond (0-999) getTime() Get the time (milliseconds since January 1, 1970) getDay() Get the weekday as a number (0-6)
  • 44. JAVASCRIPT GET DATE METHODS Method Description getFullYear() Get the year as a four digit number (yyyy) getMonth() Get the month as a number (0-11) getDate() Get the day as a number (1-31) getHours() Get the hour (0-23) getMinutes() Get the minute (0-59) getSeconds() Get the second (0-59) getMilliseconds() Get the millisecond (0-999) getTime() Get the time (milliseconds since January 1, 1970) getDay() Get the weekday as a number (0-6)
  • 45. JAVASCRIPT SET DATE METHODS Method Description setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970)
  • 46. <script> var d = new Date(); d.setFullYear(2020); document.getElementById("demo").innerHTML = d; </script>
  • 47. JAVASCRIPT ARRAYS JavaScript arrays are used to store multiple values in a single variable. var cars = ["Saab", "Volvo", "BMW"]; var cars = new Array("Saab", "Volvo", "BMW"); cars[0] = "Opel"; var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars[0];
  • 48. ACCESS THE FULL ARRAY var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars;
  • 49. REVERSING AN ARRAY var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits fruits.reverse(); // Reverses the order of the elements
  • 50. JAVASCRIPT TYPE CONVERSION In JavaScript there are 5 different data types that can contain values: • string • number • boolean • object • function There are 3 types of objects: Object Date Array And 2 data types that cannot contain values: null undefined
  • 51. THE TYPEOF OPERATOR typeof "John" // Returns "string" typeof 3.14 // Returns "number" typeof NaN // Returns "number" typeof false // Returns "boolean" typeof [1,2,3,4] // Returns "object" typeof {name:'John', age:34} // Returns "object" typeof new Date() // Returns "object" typeof function () {} // Returns "function" typeof myCar // Returns "undefined" * typeof null // Returns "object“ The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed
  • 52. JAVASCRIPT ERRORS - THROW AND TRY TO CATCH • The try statement lets you test a block of code for errors. • The catch statement lets you handle the error. • The throw statement lets you create custom errors. • The finally statement lets you execute code, after try and catch, regardless of the result.