SlideShare a Scribd company logo
JAVA SCRIPT
Java script
Java script
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

PDF
SISTEMA DE FACTURACION (Ejemplo desarrollado)
DOC
Baitap tkw
PDF
The Ring programming language version 1.5.2 book - Part 29 of 181
PDF
The Ring programming language version 1.4 book - Part 8 of 30
PDF
Юрий Буянов «Squeryl — ORM с человеческим лицом»
PDF
Oop assignment 02
PDF
The Ring programming language version 1.3 book - Part 83 of 88
PDF
RxSwift 시작하기
SISTEMA DE FACTURACION (Ejemplo desarrollado)
Baitap tkw
The Ring programming language version 1.5.2 book - Part 29 of 181
The Ring programming language version 1.4 book - Part 8 of 30
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Oop assignment 02
The Ring programming language version 1.3 book - Part 83 of 88
RxSwift 시작하기

What's hot (20)

PDF
Using Scala Slick at FortyTwo
PPT
JavaScript Arrays
PPTX
Cnam azure 2014 mobile services
PDF
Elm: give it a try
PDF
The Ring programming language version 1.10 book - Part 47 of 212
PDF
The Ring programming language version 1.2 book - Part 19 of 84
PPTX
PPTX
ES6 in Real Life
PDF
The Ring programming language version 1.6 book - Part 46 of 189
PDF
ES6, WTF?
PDF
Idioms in swift 2016 05c
PDF
7 Habits For a More Functional Swift
DOC
Ds 2 cycle
PPTX
Fact, Fiction, and FP
PPTX
KEY
Lekcja stylu
PDF
C++ Windows Forms L08 - GDI P1
PDF
여자개발자모임터 6주년 개발 세미나 - Scala Language
PDF
C++ Windows Forms L09 - GDI P2
Using Scala Slick at FortyTwo
JavaScript Arrays
Cnam azure 2014 mobile services
Elm: give it a try
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.2 book - Part 19 of 84
ES6 in Real Life
The Ring programming language version 1.6 book - Part 46 of 189
ES6, WTF?
Idioms in swift 2016 05c
7 Habits For a More Functional Swift
Ds 2 cycle
Fact, Fiction, and FP
Lekcja stylu
C++ Windows Forms L08 - GDI P1
여자개발자모임터 6주년 개발 세미나 - Scala Language
C++ Windows Forms L09 - GDI P2
Ad

Similar to Java script (20)

PPTX
FYBSC IT Web Programming Unit III Core Javascript
PPTX
1-JAVA SCRIPT. servere-side applications vs client side applications
PPTX
JavaScript.pptx
PPTX
DOC
14922 java script built (1)
PPTX
Java script
PPSX
Javascript variables and datatypes
PPTX
Learn java script
PPTX
Introduction to Client-Side Javascript
PPT
Javascript
PPTX
Data and time
PDF
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
PPTX
Javascript 101
PPTX
JavaScripts & jQuery
PDF
PPT
JavaScript Missing Manual, Ch. 2
PPTX
Unit II- Java Script, DOM JQuery (2).pptx
PPTX
An introduction to javascript
PPTX
Java script basics
PPTX
gdscWorkShopJavascriptintroductions.pptx
FYBSC IT Web Programming Unit III Core Javascript
1-JAVA SCRIPT. servere-side applications vs client side applications
JavaScript.pptx
14922 java script built (1)
Java script
Javascript variables and datatypes
Learn java script
Introduction to Client-Side Javascript
Javascript
Data and time
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
Javascript 101
JavaScripts & jQuery
JavaScript Missing Manual, Ch. 2
Unit II- Java Script, DOM JQuery (2).pptx
An introduction to javascript
Java script basics
gdscWorkShopJavascriptintroductions.pptx
Ad

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Institutional Correction lecture only . . .
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Computing-Curriculum for Schools in Ghana
PDF
Basic Mud Logging Guide for educational purpose
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Anesthesia in Laparoscopic Surgery in India
Abdominal Access Techniques with Prof. Dr. R K Mishra
human mycosis Human fungal infections are called human mycosis..pptx
PPH.pptx obstetrics and gynecology in nursing
Supply Chain Operations Speaking Notes -ICLT Program
Module 4: Burden of Disease Tutorial Slides S2 2025
Renaissance Architecture: A Journey from Faith to Humanism
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Institutional Correction lecture only . . .
TR - Agricultural Crops Production NC III.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
01-Introduction-to-Information-Management.pdf
GDM (1) (1).pptx small presentation for students
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Computing-Curriculum for Schools in Ghana
Basic Mud Logging Guide for educational purpose
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape

Java script

  • 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.