WP-Unit 3
WP-Unit 3
➢ JAVASCRIPT:
JavaScript is the world's most popular programming language. JavaScript is the programming language of
the Web. JavaScript is easy to learn. JavaScript is a scripting or programming language that allows you to
implement complex features on web pages — every time a web page does more than just sit there and
display static information for you to look at — displaying timely content updates, interactive maps,
animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved.
It is the third layer of the layer cake of standard web technologies, two of which HTML and CSS.
<script>
function changeText() {
document.getElementById("demo").innerHTML = "Text changed!";
}
</script>
</body>
</html>
In this example:
The <script> tag is used to contain JavaScript code.
Inside the <script> tags, a function changeText() is defined. This function changes the content of the
paragraph with the id demo.
The onclick attribute of the button element is set to call the changeText() function when the button is
clicked.
When the button is clicked, the content of the paragraph with id demo changes to "Text changed!".
This is a simple example, but JavaScript can be used for much more complex interactions and
manipulations within an HTML document.
2
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
<noscript>Sorry, your browser does not support JavaScript!</noscript>
Data Types: JavaScript supports several data types, including numbers, strings, booleans, arrays, objects,
and more.
var num = 10;
var str = "Hello";
var bool = true;
var arr = [1, 2, 3];
var obj = { name: "John", age: 30 };
Operators: JavaScript supports various operators for performing operations on variables and values, such
as arithmetic operators (+, -, *, /), comparison operators (==, !=, >, <), logical operators (&&, ||, !), etc.
var a = 5;
var b = 3;
var sum = a + b;
var isGreaterThan = a > b;
Control Flow: JavaScript provides structures for controlling the flow of your code, including if statements,
switch statements, for loops, while loops, and do-while loops.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
while (condition) {
// code to be executed while condition is true
}
3
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Functions: Functions are blocks of code that can be reused. You can define functions using the function
keyword.
function greet(name) {
return "Hello, " + name + "!";
}
var message = greet("John");
Objects and Classes: JavaScript is an object-oriented language. Objects are collections of properties and
methods. Classes provide a blueprint for creating objects.
// Object
var person = {
name: "John",
age: 30,
greet: function() {
return "Hello, my name is " + this.name + ".";
}
};
// Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return "Hello, my name is " + this.name + ".";
}
}
var john = new Person("John", 30);
These are some fundamental concepts in JavaScript. Understanding them will provide you with a solid
foundation for further learning and development.
• Create a JavaScript File: First, create a new file with a .js extension. For example, script.js.
4
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• Write Your JavaScript Code: Inside the JavaScript file, write your JavaScript code just as you would
between <script> tags in your HTML document.
// script.js
function greet(name) {
alert("Hello, " + name + "!");
}
• Link the JavaScript File in HTML: In your HTML file, use the <script> tag to link to the external
JavaScript file. Place this <script> tag either in the <head> section or at the end of the <body>
section.
<html>
<head>
<title>External JavaScript Example</title>
<!-- Link to external JavaScript file -->
<script src="script.js"></script>
</head>
<body>
<h1>External JavaScript Example</h1>
In this example:
The JavaScript code is saved in an external file named script.js.
In the HTML file, we link to the script.js file using the <script> tag with the src attribute pointing to the
location of the JavaScript file.
Now, the greet() function defined in the external JavaScript file can be called directly from the HTML file.
This approach keeps your code modular and maintainable, especially for larger projects.
➢ Variables:
Variables in JavaScript are containers for storing data values. You can think of them as named storage
locations for holding information that can be referenced and manipulated within a program. Here are some
key points about variables in JavaScript:
Variable Declaration: You can declare variables using three different keywords: var, let, and const.
• var: The traditional way of declaring variables in JavaScript. It has function-level scope.
• let: Introduced in ECMAScript 6 (ES6). It has block-level scope.
• const: Also introduced in ES6. It declares a constant variable whose value cannot be reassigned.
var x = 10;
let y = "Hello";
const PI = 3.14;
5
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Variable Naming: Variable names (identifiers) can contain letters, digits, underscores, and dollar signs.
They must begin with a letter, dollar sign, or underscore. Variable names are case-sensitive.
var firstName = "John";
var age = 30;
var _variable = 5;
Data Types: Variables in JavaScript can hold various data types, including numbers, strings, booleans,
arrays, objects, and more.
var num = 10;
var str = "Hello";
var bool = true;
var arr = [1, 2, 3];
var obj = { name: "John", age: 30 };
Variable Scope: The scope of a variable defines where in your code the variable can be accessed. Variables
declared with var have function-level scope, while variables declared with let and const have block-level
scope.
function myFunction() {
var localVar = 10;
if (true) {
let blockVar = 20;
console.log(localVar); // Accessible
console.log(blockVar); // Accessible
}
console.log(localVar); // Accessible
console.log(blockVar); // Not accessible (ReferenceError)
}
Hoisting: In JavaScript, variable declarations are hoisted to the top of their scope. This means you can
access a variable before it's declared, but its value will be undefined.
console.log(myVar); // undefined
var myVar = 10;
Understanding variables is essential for writing JavaScript code because they are used extensively for
storing and manipulating data throughout your programs.
➢ Operators:
Operators in JavaScript are symbols that allow you to perform operations on variables and values.
JavaScript supports various types of operators, including arithmetic, assignment, comparison, logical,
bitwise, and more. Here's an overview of the main types of operators in JavaScript:
Arithmetic Operators: Used to perform arithmetic operations like addition, subtraction, multiplication,
division, and modulus (remainder).
var x = 10;
6
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
var y = 5;
var sum = x + y; // Addition
var difference = x - y; // Subtraction
var product = x * y; // Multiplication
var quotient = x / y; // Division
var remainder = x % y; // Modulus
Comparison Operators: Used to compare two values and return a boolean result (true or false).
var x = 10;
var y = 5;
var isEqual = x == y; // Equality
var isGreater = x > y; // Greater than
var isLess = x < y; // Less than
var isNotEqual = x != y; // Inequality
These are some of the most used operators in JavaScript. Understanding how to use them effectively is
crucial for writing efficient and concise code.
• If Statement
• Using If-Else Statement
• Using Switch Statement
• Using the Ternary Operator (Conditional Operator)
• Using For loop
Example: In this example, we are using an if statement to check our given condition.
const num = 5;
if (num > 0)
{
console.log("The number is positive.");
};
Output
The number is positive.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
8
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
}
}
Example: In this example, we are using the if..else statement to verify whether the given number is positive
or negative.
Output
The number is negative
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
9
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
case 2:
console.log("Number is two.");
break;
default:
console.log("Number is greater than 2.");
};
Output
Number is greater than 2.
• Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop
body. For Loop and While Loops are entry-controlled loops.
• Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the
loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. the do-while loop is exit controlled loop.
Syntax:
while (condition)
{
// Statements
}
Output
1
2
3
4
5
Syntax:
do
{
// Statements
}
while (condition);
val += 1;
Output
1
2
3
4
5
Syntax:
for (statement 1; statement 2; statement 3)
{
// Code here . . .
}
Example: In this example, we are using Iterative Statement as a for loop, in which we find the even number
between 0 to 10.
11
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Output
0
2
4
6
8
10
Example
for (let i = 0; i < 10; i++)
{
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
In this example, the break statement ends the loop ("breaks" the loop) when the loop counter (i) is 3.
➢ Popup Boxes:
To Create Popups
12
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
<span class="popuptext" id="myPopup">Popup text...</span>
</div>
/* Popup arrow */
.popup .popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
13
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
from {opacity: 0;}
to {opacity: 1;}
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
In Javascript, popup boxes are used to display the message or notification to the user.
There are three types of pop-up boxes in JavaScript:
• Alert Box
• Prompt Box
• Confirm Box
Syntax
window.alert("sometext");
Syntax:
alert("your Alert here");
<body>
<center>
<h1>Welcome to Pop-up Alerts</h1>
<h3>Alert Box</h3>
<button onclick="newAlert()">
Click here for alert box
</button>
Syntax
window.confirm("sometext");
or
confirm("your query here");
Example
<html>
<body>
<p id="demo"></p>
<script>
15
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
function myFunction()
{
var txt;
if (confirm("Press a button!"))
{
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
Syntax
window.prompt("sometext","defaultText");
or
prompt("your Prompt here");
Example
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "")
{
text = "User cancelled the prompt.";
}
else
{
text = "Hello " + person + "! How are you today?";
16
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
➢ Functions:
JavaScript function is a set of statements that take inputs, do some specific computation, and produce
output. A JavaScript function is executed when “something” invokes it (calls it).
Example 1: A basic javascript function, here we create a function that divides the 1st element by the
second element.
Output:
4
You must already have seen some commonly used functions in JavaScript like alert(), which is a built-in
function in JavaScript. But JavaScript allows us to create user-defined functions also. We can create
functions in JavaScript using the keyword `function`.
To create a function in JavaScript, we have to first use the keyword function, separated by the name of the
function and parameters within parenthesis. The part of the function inside the curly braces {} is the body
of the function. In javascript, functions can be used in the same way as variables for assignments, or
calculations.
• Every function should begin with the keyword function followed by,
17
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• A user-defined function name that should be unique,
• A list of parameters enclosed within parentheses and separated by commas,
• A list of statements composing the body of the function enclosed within curly braces {}.
Output
15
• Function Declaration: It declares a function with a function keyword. The function declaration
must have a function name.
Syntax:
function functionName(paramA, paramB) {
// Set of statements
}
• Function Expression:
It is similar to a function declaration without the function name. Function expressions can be stored in a
variable assignment.
Syntax:
let functionName= function(paramA, paramB) {
// Set of statements
}
Output
16
18
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• Arrow Function:
It is one of the most used and efficient methods to create a function in JavaScript because of its
comparatively easy implementation. It is a simplified as well as a more compact version of a regular or
normal function expression or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Example: This example describes the usage of the Arrow function.
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = a.map(function (s) {
return s.length;
});
console.log("Normal way ", a2); // [8, 6, 7, 9]
const a3 = a.map((s) => s.length);
console.log("Using Arrow Function ", a3); // [8, 6, 7, 9]
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
19
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Parameters are additional information passed to a function. For example, in the above example, the task of
the function calcAddition is to calculate the addition of two numbers. These two numbers on which we
want to perform the addition operation are passed to this function as parameters. The parameters are
passed to the function within parentheses after the function name and separated by commas. A function in
JavaScript can have any number of parameters and also at the same time, a function in JavaScript can not
have a single parameter.
Output
69
Example:
function add(a, b) {
console.log(a + b);
}
add(5, 3);
Output: 8
Parameter Rules:
• JavaScript function definitions do not specify data types for parameters.
• JavaScript functions do not perform type checking on the passed arguments.
• JavaScript functions do not check the number of arguments received.
Default Parameters
If a function is called with missing arguments (less than declared), the missing values are set to undefined.
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter.
Example:
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
}
Function Rest Parameter: The rest parameter (...) allows a function to treat an indefinite number of
arguments as an array:
Example
function sum(...args) {
20
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
Example
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
let max = -Infinity;
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Example
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
If a function is called with too many arguments (more than declared), these arguments can be reached
using the arguments object.
21
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
➢ Functions – Defining a Return Statement:
The return statement ends function execution and specifies a value to be returned to the function caller.
Syntax
return;
return expression;
Expression is Optional. The expression whose value is to be returned. If omitted, undefined is returned.
The return statement can only be used within function bodies. When a return statement is used in a
function body, the execution of the function is stopped. The return statement has different effects when
placed in different functions:
• In a plain function, the call to that function evaluates to the return value.
• In an async function, the produced promise is resolved with the returned value.
• In a generator function, the produced generator object's next() method returns { done: true, value:
returnedValue }.
• In an async generator function, the produced async generator object's next() method returns a
promise fulfilled with { done: true, value: returnedValue }.
If a return statement is executed within a try block, its finally block, if present, is first executed, before the
value is actually returned.
This makes the function return undefined and the a + b expression is never evaluated. This may generate a
warning in the console. To avoid this problem (to prevent ASI), you could use parentheses:
return (
a+b
);
Using JavaScript, this event can be dynamically added to any element. It supports all HTML elements except
<html>, <head>, <title>, <style>, <script>, <base>, <iframe>, <bdo>, <br>, <meta>, and <param>. It means
we cannot apply the onclick event on the given tags.
22
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
In HTML, we can use the onclick attribute and assign a JavaScript function to it. We can also use the
JavaScript's addEventListener() method and pass a click event to it for greater flexibility.
Syntax
Now, we see the syntax of using the onclick event in HTML and in javascript (without addEventListener()
method or by using the addEventListener() method).
In HTML
<element onclick = "fun()">
In JavaScript
object.onclick = function() { myScript };
Let's see how to use onclick event by using some illustrations. Now, we will see the examples of using the
onclick event in HTML, and in JavaScript.
<!DOCTYPE html>
<html>
<head>
<script>
function fun() {
alert("Welcome to the javaTpoint.com");
}
</script>
</head>
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">Click me</button>
</body>
</html>
➢ JavaScript Objects:
Objects, in JavaScript, are the most important data type and form the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s primitive data types (Number, String,
Boolean, null, undefined, and symbol) in the sense that these primitive data types all store a single value
each (depending on their types).
23
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,
...
}
Note:- Object() can be called with or without new. Both create a new object.
Example: Below is an example of Objects in JavaScript.
const o = new Object();
o.foo = 42;
console.log(o);
// { foo: 42 }
Output
{ foo: 42 }
Example: In this example “name”, “location”, and “established” are all “keys” and “Vivekananda School”,
“Delhi” and 1971 are values of these keys respectively. Each of these keys is referred to as properties of the
object. An object in JavaScript may also have a function as a member, in which case it will be known as a
method of that object. Here “displayinfo” is a method of the school object that is being used to work with
the object’s data, stored in its properties.
// JavaScript code demonstrating a simple object
let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
displayInfo: function () {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
24
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
}
school.displayInfo();
Output
Vivekananda School was established
in 1971 at Delhi
Objects are more complex and each object may contain any combination of these primitive data-types as
well as reference data-types.
An object is a reference data type. Variables that are assigned a reference value are given a reference or a
pointer to that value. That reference or pointer points to the location in memory where the object is
stored. The variables don’t actually store the value.
Loosely speaking, objects in JavaScript may be defined as an unordered collection of related data, of
primitive or reference types, in the form of “key: value” pairs. These keys can be variables or functions and
are called properties and methods, respectively, in the context of an object.
An object can be created with figure brackets {…} with an optional list of properties. A property is a “key:
value” pair, where a key is a string (also called a “property name”), and the value can be anything.
Creating Objects:
In JavaScript, Objects can be created using two different methodologies namely Literal Form and
Constructed Form.
• Literal Form: The literal form uses the construction of object literals that can be said as a collection
of key-value pairs enclosed within a pair of curly braces. The syntaxial form is shown below.
let obj = {
key1: value1,
key2: value2,
...
};
• Constructed Form: The Constructed form uses either an object constructor function or the new
keyword to create an empty object ad then adds properties to the object one by one. The syntaxial
forms are shown below.
o Object Constructor Function: In this methodology, the user creates an explicit function to
take required values as parameters and assign them as the properties of the desired object.
function obj(value1, value2, ...) {
this.key1 = value1;
this.key2 = value2;
25
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
...
}
• Using New Keyword: This methodology uses the New keyword in front of any constructor method
or any built-in constructor method ( such as Object, Date, String, etc) and creates a new instance of
the following object by mounting it on memory.
let obj = new Object();
obj.key1 = value1;
obj.key2 = value2;
...
Differences between using Object Literals and the Constructed Form: Both the constructed form and literal
form result in creating exactly the same sort of object i.e. the end result is the same for both
methodologies. The only difference between the both is that object literals can take care of several key-
value pairs at once and thus is more convenient while on the other hand with the constructed-form
objects, we must add the properties one-by-one in separate statements.
You can create JavaScript Strings by enclosing text in single or double quotes. String literals and the String
constructor provide options. Strings allow dynamic manipulation, making it easy to modify or extract
elements as needed.
Declaration of a String
1. Using Single Quotes
Single Quotes can be used to create a string in JavaScript. Simply enclose your text within single quotes to
declare a string.
Syntax:
let str = 'String with single quote';
Example:
let str = 'Create String with Single Quote';
console.log(str);
Output
Create String with Single Quote
26
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
2. Using Double Quotes
Double Quotes can also be used to create a string in JavaScript. Simply enclose your text within double
quotes to declare a string.
Syntax:
let str = “String with double quote”;
Example:
let str = "Create String with Double Quote";
console.log(str);
Output
Create String with Double Quote
3. String Constructor
You can create a string using the String Constructor. The String Constructor is less common for direct string
creation, it provides additional methods for manipulating strings. Generally, using string literals is preferred
for simplicity.
Example
let str = new String('Create String with String Constructor');
console.log(str);
Output
[String: 'Create String with String Constructor']
Example:
let str = 'Template Litral String';
let newStr = `String created using ${str}`;
console.log(newStr);
Output
String created using Template Litral String
5. Empty String
You can create an empty string by assigning either single or double quotes with no characters in between.
Syntax:
// Create Empty Strign with Single Quotes
let str1 = '';
// Create Empty Strign with Double Quotes
let str2 = "";
Example:
27
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
let str1 = '';
let str2 = "";
console.log("Empty String with Single Quotes: " + str1);
console.log("Empty String with Double Quotes: " + str2);
Output
Empty String with Single Quotes:
Empty String with Double Quotes:
Example:
let str = `
This is a
multiline
string`;
console.log(str);
Output
This is a
multiline
string
Syntax
/pattern/modifiers;
Example
/modelcollege/i;
Example explained:
/modelcoellge/i is a regular expression.
model college is a pattern (to be used in a search). i is a modifier (modifies the search to be case-
insensitive).
• The search() method uses an expression to search for a match, and returns the position of the
match.
• The replace() method returns a modified string where the pattern is replaced.
Example
Use a string to do a search for "Model College" in a string:
Example
Use a regular expression to do a case-insensitive search for "Model College" in a string:
Example
Use a case insensitive regular expression to replace Microsoft with ModelCollege in a string:
29
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all)
m Perform multiline matching
d Perform start and end matching (New in ES2022)
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD,
or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
➢ Using test()
The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or
false, depending on the result. The following example searches a string for the character "e":
Example
const pattern = /e/;
pattern.test("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
true
You don't have to put the regular expression in a variable first. The two lines above can be shortened to
one:
30
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
➢ Using exec()
The exec() method is a RegExp expression method. It searches a string for a specified pattern, and returns
the found text as an object. If no match is found, it returns an empty (null) object. The following example
searches a string for the character "e":
Example
/e/.exec("The best things in life are free!");
Math is an inbuilt object that has attributes and methods for mathematical functions and constants. It’s not
a function object.
Math object works with the Number type. The Math object does not have a constructor. All properties and
methods of Math are fixed/static. The cosine function is known as Math.cos(y) while the constant pi is
known as Math.PI, where y is the method’s argument. All the properties and methods of Math are static
and can be called by using Math as an object without creating it.
Static Math Properties: The Math properties & their descriptions are listed below:
Syntax:
Math.property
31
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Example 1: This example uses math object properties to return their values.
console.log("Math.LN10: " + Math.LN10);
console.log("Math.LOG2E: " + Math.LOG2E);
console.log("Math.Log10E: " + Math.LOG10E);
console.log("Math.SQRT2: " + Math.SQRT2);
console.log("Math.SQRT1_2: " + Math.SQRT1_2);
console.log("Math.LN2: " + Math.LN2);
console.log("Math.E: " + Math.E);
console.log("Math.PI: " + Math.PI);
Output
Math.LN10: 2.302585092994046
Math.LOG2E: 1.4426950408889634
Math.Log10E: 0.4342944819032518
Math.SQRT2: 1.4142135623730951
Math.SQRT1_2: 0.7071067811865476
Math.LN2: 0.6931471805599453
Math.E: 2.71828...
Static Math Methods: The methods associated with the Math object are listed below, along with their
descriptions.
Syntax:
Math.method(number)
Method Description
32
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
Math.abs(y) The positive value of y is returned.
Math.ceil(y) Returns the smallest integer greater than or equal to y.
Math.cos(y) Returns the cosine of the angle y.
Math.floor(y) Returns the largest integer less than or equal to y.
Math.max([x[, y[, …]]]) Largest number is returned from x,y.
Math.min([x[, y[, …]]]) The smallest of all the numbers is returned from x,y.
Math.pow(x, y) Returns the exponent power y of the base value x (that is, x^y).
Math.random() An arbitrary number between 0 and 1 is returned.
Math.round(y) The value of y, rounded to the closest integer, is returned.
Math.sin(y) The sine of the angle y is returned.
Math.tan(y) The tangent of y is returned.
Output
Math.abs(-4.7): 4.7
Math.ceil(4.4): 5
Math.floor(4.7): 4
Math.sin(90 * Math.PI / 180): 1
Math.min(0, 150, 30, 20, -8, -200): -200
Math.random(): 0.7416861489868538
Supported Browsers:
Chrome
Edge
Firefox
Opera
Safari
33
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
• new Date(year,month,day,hours)
• new Date(year,month,day,hours,minutes)
• new Date(year,month,day,hours,minutes,seconds)
• new Date(year,month,day,hours,minutes,seconds,ms)
• new Date(milliseconds)
Example
const d = new Date();
Examples
const d = new Date("October 13, 2014 11:13:00");
const d = new Date("2022-03-25");
Date string formats are described in the next chapter.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
Example
const d = new Date(2018, 11, 24, 10, 33, 30, 0);
Note:
JavaScript counts months from 0 to 11:
January = 0.
….
December = 11.
Specifying a month higher than 11, will not result in an error but add the overflow to the next year:
Specifying:
Specifying:
34
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
const d = new Date(2018, 6, 5, 10, 33, 30);
Using 6, 4, 3, or 2 Numbers
You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
Example
const d = new Date(2018);
Previous Century
One and two digit years will be interpreted as 19xx:
Example
const d = new Date(99, 11, 24);
Example
const d = new Date(9, 11, 24);
Now the time is: 1708526523291 milliseconds past January 01, 1970
➢ new Date(milliseconds)
new Date(milliseconds) creates a new date object as milliseconds plus zero time:
Examples
01 January 1970 plus 100 000 000 000 milliseconds is:
35
F.Y.C.S-SEM II WEB PROGRAMMING - I NOTES - UNIT 3
const d = new Date(100000000000);
Date Methods
When a date object is created, a number of methods allow you to operate on it.
Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date
objects, using either local time or UTC (universal, or GMT) time.
➢ Displaying Dates
JavaScript will (by default) output dates using the toString() method. This is a string representation of the
date, including the time zone. The format is specified in the ECMAScript specification:
Example
Wed Feb 21 2024 20:12:03 GMT+0530 (India Standard Time)
When you display a date object in HTML, it is automatically converted to a string, with the toString()
method.
Example
const d = new Date();
d.toString();
The toDateString() method converts a date to a more readable format:
Example
const d = new Date();
d.toDateString();
The toUTCString() method converts a date to a string using the UTC standard:
Example
const d = new Date();
d.toUTCString();
The toISOString() method converts a date to a string using the ISO standard:
Example
const d = new Date();
d.toISOString();
36