Chap 01 Basics of Javascript
Chap 01 Basics of Javascript
Chap 01 Basics of Javascript
(22519)
Unit 1 :
Basics of JavaScript Programming
(12 M)
Basic Works in the back end which Works at the front end and
could not be visible at the script are visible among the
client end. users.
Processing Requires server interaction Does not need interaction with
the server
Languages PHP, ASP.net, Ruby, Python HTML, CSS, JavaScript
involved
Affect Could effectively customize the Can reduce the load to the
web pages and provide server.
dynamic websites.
Security Relatively secure Insecure
1.1 Features of JavaScript
1.2 Object Name, Property ,
Method, Dot Syntax, Main Event
▪JavaScript is a Object based scripting language.
▪A JavaScript object is a collection of named values.
▪These named values are usually referred to as properties of
the object.
▪A JavaScript objects are collection of properties and
methods.
✓A Methods is a function that is a member of an object.
✓A Property is a value or set of values that is the
member of an object.
Object
In JavaScript, almost "everything" is an object.
✓ Booleans can be objects (if defined with the new keyword)
✓ Numbers can be objects (if defined with the new keyword)
✓ Strings can be objects (if defined with the new keyword)
✓ Dates are always objects
✓ Maths are always objects
✓ Regular expressions are always objects
✓ Arrays are always objects
✓ Functions are always objects
✓ Objects are always objects
Types of Object
Built –in • Defined by JavaScript (such as
Objects Math, Date, String, Array)
</html>
Using “new” keyword
▪new keyword is used to create object.
▪Syntax: var objectname=new Object();
▪Example:
var person = new Object();
person.firstName = “Prasad";
person.lastName = “Koyande";
person.age = 10;
Example
<html>
<body>
<script>
var emp=new Object();
emp.id="VP-179";
emp.name=“Prasad Koyande";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
VP-179 Prasad Koyande
</body> OUTPUT
50000
</html>
By using Object Constructor
▪Here, you need to create function with arguments.
▪Each argument value can be assigned in the current object by
using this keyword.
▪The this keyword refers to the current object.
▪Example:
function person(firstName, lastName, age)
{
this. firstName = firstName;
this. lastName = lastName;
this. age = age;
}
p=new person(“Prasad”,”Koyande”,10);
document.write(p.firstName+" "+p.lastName+" "+p.age);
Example
<html> <body>
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary; OUTPUT VP-179 Prasad Koyande 5000
}
e=new emp("VP-179",”Prasad Koyande",5000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body> </html>
Property
▪Properties are the values associated with a JavaScript object.
▪A JavaScript object is a collection of unordered properties.
▪Properties can usually be changed, added, and deleted, but some are
read only.
▪The syntax for accessing the property of an object is:
objectName.property // person.age
objectName["property"] // person["age"]
onmouseout The user moves the mouse away from an HTML element
Math: Methods
Methods Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns cosine of a number.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is base exponent.
Example : Math
<html>
<head>
<title>JavaScript Math Object Methods</title>
</head>
<body>
<script type="text/javascript">
var value = Math.abs(-20);
document.write("ABS Value : " + value +"<br>");
var value = Math.tan(5);
document.write("TAN Value : " + value +"<br>");
</script>
</body> ABS Value : 20
OUTPUT
</html> TAN Value : -3.380515006246586
Date
•Date is a data type.
•Date object manipulates date and time.
•Date() constructor takes no arguments.
•Date object allows you to get and set the year, month, day, hour, minute,
second and millisecond fields.
•Syntax:
var variable_name = new Date();
Example:
var current_date = new Date();
Date
Methods Description
Date() Returns current date and time.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year.
getHours() Returns the hour.
getMinutes() Returns the minutes.
getSeconds() Returns the seconds.
getMilliseconds() Returns the milliseconds.
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
Date
Methods Description
getTimezoneOffset() Returns the timezone offset in minutes for the current locale.
getMonth() Returns the month.
setDate() Sets the day of the month.
setFullYear() Sets the full year.
setHours() Sets the hours.
setMinutes() Sets the minutes.
setSeconds() Sets the seconds.
setMilliseconds() Sets the milliseconds.
setTime() Sets the number of milliseconds since January 1, 1970 at 12:00 AM.
Date
Methods Description
setMonth() Sets the month.
toDateString() Returns the date portion of the Date as a human-readable string.
toLocaleString() Returns the Date object as a string.
toGMTString() Returns the Date object as a string in GMT timezone.
valueOf() Returns the primitive value of a Date object.
Example : Date Date Methods
Locale String: 7/3/2020, 5:23:19 PM
<html> Hours: 17
OUTPUT Day: 5
<body> Month: 6
<h2>Date Methods</h2> FullYear: 2020
<script type="text/javascript"> Minutes: 23
var d = new Date();
document.write("<b>Locale String:</b> " + d.toLocaleString()+"<br>");
document.write("<b>Hours:</b> " + d.getHours()+"<br>");
document.write("<b>Day:</b> " + d.getDay()+"<br>");
document.write("<b>Month:</b> " + d.getMonth()+"<br>");
document.write("<b>FullYear:</b> " + d.getFullYear()+"<br>");
document.write("<b>Minutes:</b> " + d.getMinutes()+"<br>");
</script>
</body>
</html>
String
•String objects are used to work with text.
•It works with a series of characters.
Syntax:
var variable_name = new String(string);
Example:
var s = new String(string);
Properties:
Properties Description
length It returns the length of the string.
constructor It returns the reference to the String function that created the
object.
String: Methods
Methods Description
charAt() It returns the character at the specified index.
charCodeAt() It returns the ASCII code of the character at the specified position.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object.
match() It is used to match a regular expression against a string.
replace() It is used to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression.
slice() It extracts a session of a string and returns a new string.
split() It splits a string object into an array of strings by separating the
string into the substrings.
toLowerCase() It returns the calling string value converted lower case.
toUpperCase() Returns the calling string value converted to uppercase.
Example : String
<html>
<body>
<script type="text/javascript">
var str = "A JavaScript";
document.write("<b>Char At:</b> " + str.charAt(4)+"<br>");
document.write("<b>CharCode At:</b> " + str.charCodeAt(0)+"<br>");
document.write("<b>Index of:</b> " + str.indexOf(“p")+"<br>");
document.write("<b>Lower Case:</b> " + str.toLowerCase()+"<br>");
document.write("<b>Upper Case:</b> " + str.toUpperCase()+"<br>");
</script> Char At: v
</body> CharCode At: 65
</html> OUTPUT Index of: 10
Lower Case: a javascript
Upper Case: A JAVASCRIPT
Window
✓The window object represents a window in browser.
✓ An object of window is created automatically by the browser.
✓Window is the object of browser, it is not the object of javascript.
Method Description
alert() displays the alert box containing message with ok button.
confirm() displays the confirm dialog box containing message with ok and
cancel button.
prompt() displays a dialog box to get input from the user.
open() opens the new window.
close() closes the current window.
Example : window
<script type="text/javascript">
function msg()
{
var a= window.prompt("Who are you?");
window.alert("I am "+a);
}
</script>
<input type="button" value="click" onclick="msg()">
window: output
DOM getElementById() Method
✓The getElementById() method returns the elements that has given ID
which is passed to the function.
JavaScript Data
Types
<script>
// It is single line comment
document.write("hello javascript");
</script>
Types of JavaScript Comments
There are two types of comments in JavaScript.
2. Multi-line Comment
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
1.4 Operators and Expression
JavaScript operators are symbols that are used to perform operations
on operands.
1.Arithmetic Operators
2.Comparison (Relational) Operators
3.Bitwise Operators
4.Logical Operators
5.Assignment Operators
6.Special Operators
Arithmetic Operator
✓used to perform arithmetic operations on the operands.
Operator Description Example
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus 20%10 = 0
++ Increment var a=10; a++; Now a = 11
-- Decrement var a=10; a--; Now a = 9
Comparison Operator
➢compares the two operands
expression.identifier;
expression[identifier];
✓Exmaple,
emp.firstName;
emp[lastName];
Function Definition Expression
✓A function expression is part of a variable assignment expression
and may or may not contain a name.
✓Since this type of function appears after the assignment operator
=, it is evaluated as an expression.
✓Function expressions are typically used to assign a function to a
variable.
✓Function expressions are evaluated only when the interpreter
reaches the line of code where function expressions are located.
var sq=function (x)
{ return x*x;
}
Invocation Expressions
✓An invocation expression is JavaScript’s syntax for calling (or
executing) a function or method.
✓It starts with a function expression that identifies the function to be
called.
✓ The function expression is followed by an open parenthesis, a
comma-separated list of zero or more argument expressions, and a
close parenthesis.
✓When an invocation expression is evaluated, the function expression
is evaluated first, and then the argument expressions are evaluated to
produce a list of argument values.
Invocation Expressions
f(0) // f is the function expression; 0 is the argument expression.
<html>
✓Example: <body>
<script>
if (new Date().getHours() < 18)
{
document.write("Good day!");
}
</script>
</body>
</html>
The else Statement
✓Use else statement to specify a block of code to be executed if the
condition is false.
✓Syntax:
if (condition)
{
// block of code to be executed if the condition
is true
} else
{
// block of code to be executed if the condition
is false
}
The else Statement-Example
<html> <body>
<script>
if (new Date().getHours() < 18)
{
document.write("Good day!");
}
else
{
document.write("Good Evening!");
}
</script>
</body> </html>
The else if Statement
✓Use else if statement to specify a new condition if the first condition is
false.
✓ Syntax:
if (condition1)
{ // block of code to be executed if condition1 is true
}
else if (condition2)
{ // block of code to be executed if the condition1 is false
and condition2 is true
}
else
{ // block of code to be executed if the condition1 is false
and condition2 is false
}
The else if Statement-Example
<html> greeting = "Good day";
<body> }
<script> else
var greeting; {
var time = new Date().getHours();
greeting = "Good evening";
if (time < 10)
}
{
document.write(greeting);
greeting = "Good morning";
</script>
}
</body>
else if (time < 20)
</html>
{
The switch case Statement
✓The switch statement is used to perform different actions based on
different conditions.
✓It is used to select one of many code blocks to be executed.
✓Syntax:
switch(expression)
{
This is how it works:
case x:
// code block •The switch expression is evaluated once.
break; •The value of the expression is compared with the values
case y: of each case.
// code block •If there is a match, the associated block of code is
break; executed.
default: •If there is no match, the default code block is executed.
// code block
}
1.6 The switch case-Example
<html> case 3:
<body> day = "Wednesday";
<script> break;
var day; Case 4:
switch (new Date().getDay()) day = "Thursday";
{ break;
case 0: case 5:
day = "Sunday"; day = "Friday";
break; break;
case 1: case 6:
day = "Monday"; day = "Saturday";
break; }
case 2: document.write("Today is " + day);
day = "Tuesday"; </script>
break; </body>
</html>
default keyword
✓default keyword specifies the code to run if there is no case match.
✓The getDay() method returns the weekday as a number between 0
and 6.
If today is neither Saturday (6) nor Sunday (0), write a default
message.
switch (new Date().getDay())
{
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
1.7 JavaScript Loop Statement
The JavaScript loops are used to iterate the piece of code using for,
while, do while or for-in loops.
There are four types of loops in JavaScript.
✓for loop
✓while loop
✓do-while loop
✓for-in loop
for Loop
✓The JavaScript for loop iterates the elements for the fixed number
of times. It should be used if number of iteration is known.
✓Syntax: for (initialization; condition; increment)
{
Code to be executed
}
✓Example: <script>
for (i=0; i<=10; i=i+2)
{
document.write(i + "<br/>")
}
</script>
do while Loop
✓loop is a variant of the while loop.
✓This loop will execute the code block once.
✓before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
do
✓Syntax: {
<script> code to be executed
var i=21; }
while (condition);
do{
document.write(i +"<br/>");
✓Example: i++;
}while (i<=25);
</script>
while Loop
✓The JavaScript while loop loops through a block of code as long as a
specified condition is true.
✓Syntax: while ( condition)
{
Code to be executed
}
✓Example: var i=11;
while (i<=20)
{
document.write(i + "<br/>");
i++;
}
For-in Loop
✓The for..in statement loops through the properties of an object.
✓The block of code inside the loop will be executed once for each
property. for (variable_name in object)
✓Syntax: {
Code to be executed
}
<script type = "text/javaScript">
var lang = { first : "C", second : "Java",third : "Python", fourth :
✓Example: “PHP"};
for (prog in lang)
{ C
document.write(lang[prog] + "<br >"); Java
} Python
</script> PHP
break statement
✓break statement breaks the loop and continues executing the code after
the loop.
✓The break statement can also be used to jump out of a loop.
✓Example: var text = "";
var i; The number is 0
for (i = 0; i < 10; i++) The number is 1
{ The number is 2
The number is 3
if (i === 4)
{ break;
}
text =text + "The number is " + i + "<br>";
}
document.write(text);
</script>
continue statement
✓Continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
✓Example:
var text = "";
var i; The number is 0
for (i = 0; i < =6; i++) The number is 1
The number is 2
{
The number is 3
if (i === 4) The number is 5
{continue; The number is 6
}
text =text + "The number is " + i + "<br>";
}
document.write(text);
</script>
1.8 Querying and Setting Properties
✓To obtain the value of a property, use . (dot) operator or square[ ]
bracket.
✓The left hand side should be an expression whose value is an
object.
✓If using dot (.) operator, the right-hand must be a simple
identifier that names the property.
✓If using square brackets, the value within the brackets must be an
expression that evaluates to a string that contains the desired
property name.
1.8 Querying and Setting Properties
✓Example,
var name=author.lastname; //get the “lastname ” property of the book.
var title=book[“main title”]; //get the “main title” property of the book.
<script>
// Create an object:
var person = { firstName: "Chirag", lastName : "Shetty",
fullName : function()
{
return this.firstName + " " + this.lastName;
}
}; This example access fullName as a
document.write(person.fullName()); function: person.fullName().
</script>
JavaScript Function or Getter ?
<script>
// Create an object:
var person = { firstName: "Yash ", lastName : "Desai",
get fullName()
{
return this.firstName + " " + this.lastName;
} This example fullName as a
}; property: person.fullName.
// Display data from the object using a getter
document.write(person.fullName);
</script>