Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

UNIT 01 12 M

Basics of JavaScript
Programmming
WHAT IS JAVASCRIPT
� JavaScript is an interpreted, client-side, event-
based, object oriented scripting language that
you can use to add dynamic interactivity to your web
pages.

Prepared By Mrs.S.J.Patil
� JavaScript is not a compiled language, but it is a
translated language. The JavaScript Translator
(embedded in the browser) is responsible for
translating the JavaScript code for the web browser.
� It was introduced by Brendan Eich in the year 1995
for adding programs to the webpages in the Netscape
Navigator browser.
FEATURES OF JAVA SCRIPT
1. JavaScript is a object-based scripting language.
2. Giving the user more control over the browser.
3. It Detecting the user's browser and OS,
4. It is light weighted.
5. Client – Side Technology

Prepared By Mrs.S.J.Patil
6. JavaScript is a scripting language and it is not java.
7. JavaScript is interpreter based scripting language.
8. JavaScript is case sensitive.
9. JavaScript is object based language as it provides
predefined objects.
10. Every statement in JavaScript must be terminated with
semicolon (;).
11. Most of the JavaScript control statements syntax is same
as syntax of control statements in C language.
12. An important part of JavaScript is the ability to create
new functions within scripts. Declare a function in
JavaScript using function keyword.
APPLICATION OF JAVASCRIPT

� JavaScript is used to create interactive websites.


It is mainly used for:
⮚ Client-side validation,
⮚ Dynamic drop-down menus,

Prepared By Mrs.S.J.Patil
⮚ Displaying date and time,
⮚ Displaying pop-up windows and dialog boxes (like an
alert dialog box, confirm dialog box and prompt
dialog box),
⮚ Displaying clocks etc.
LIMITATIONS(DISADVANTAGES) OF JAVASCRIPT

� Client-side JavaScript does not allow the reading or


writing of files. This has been kept for security
reason.

Prepared By Mrs.S.J.Patil
� JavaScript cannot be used for networking
applications because there is no such support
available.
� JavaScript doesn't have any multithreading or
multiprocessor capabilities.
� Relying on end-user.
HOW TO WRITE A JAVASCRIPT
� JavaScript can be implemented using JavaScript
statements that are placed within the
<script>...</script> HTML tags in a web page.
� You can place the <script>, containing your

Prepared By Mrs.S.J.Patil
JavaScript, within <body> tag or <head>tag or in
both tags.
� The <script> tag alerts the browser program to start
interpreting all the text between these tags as a
script.
� A simple syntax of your JavaScript will appear as
follows.
<script>
//Javascript code
</script>
HOW TO WRITE A JAVASCRIPT
� The script tag attributes
• Language − This attribute specifies what scripting
language you are using. Typically, its value will be
JavaScript. Although recent versions of HTML (and

Prepared By Mrs.S.J.Patil
XHTML, its successor) have phased out the use of
this attribute.
• Type − This attribute is what is now recommended
to indicate the scripting language in use and its
value should be set to "text/javascript".
• src (optional) -specifies the URL of an external
script file.
� Every statement in JavaScript must be terminated
with semicolon;
HOW TO WRITE A JAVASCRIPT
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<!-- Script tag can also be placed here -->

Prepared By Mrs.S.J.Patil
</head>
<body>
<p>Before the script...</p>
<!-- Script tag inside the body -->
<script>
// write the JavaScript code inside it
</script>
<p>...After the script.</p>
</body>
</html>
PRINT “HELLO” MESSAGE ON SCREEN USING
JAVASCRIPT
� we can make use of different methods(Display
output)that JavaScript provides. Most common
are:
1. console.log()

Prepared By Mrs.S.J.Patil
2. document.write()
3. alert()
� ‘document.write()’ is used when we want to print
the content onto the document which is the HTML
Document.
� ‘console.log()’ is mainly used when we are
debugging JavaScript code.
� ‘alert()’-This function will display text in a dialog
box that pops up on the screen.
/* WRITE SIMPLE JAVASCRIPT PROGRAM
TO DISPLAY HELLO MESSAGE */
<html>
<body>
<script type=“text/javascript”>

Prepared By Mrs.S.J.Patil
// using document.write
document.write('Hello World');
</script>
</body>
</html>

� o/p: Hello World


JAVASCRIPT COMMENT
� It is used to add information about the code,
warnings or suggestions so that end user can easily
interpret the code.
� There are two types of comments in JavaScript:

1. JavaScript Single line Comment

Prepared By Mrs.S.J.Patil
� It is represented by double forward slashes (//).

� It can be used before and after the statement.

2. JavaScript Multiline Comment


� It can be used to add single as well as multi line
comments. So, it is more convenient.
� It is represented by forward slash with asterisk then
asterisk with forward slash.
// It is single line comment
/* this multiline comment */
OBJECT NAME
� JavaScript is an object-based programming
language, so everything in JavaScript is an object.
� A JavaScript object is like a real-world entity
having state and behaviour.

Prepared By Mrs.S.J.Patil
� for example: car, pen, bike, chair, glass, keyboard,
monitor etc.
� We can take a car as an object. It will have a state
like color and model. It will also have behaviours
like accelerating and brake.
� JavaScript is template based and we can create
objects without the need of having a class.
CREATING OBJECTS IN JAVASCRIPT
THERE ARE 3 WAYS TO CREATE OBJECTS.
� By object literal
� By creating instance of Object directly (using new
keyword)
By using an object constructor (using new keyword)

Prepared By Mrs.S.J.Patil

1) JAVASCRIPT OBJECT BY OBJECT LITERAL
� The syntax of creating object using object literal is
given below:
object={property1:value1,property2:value2.....propertyN:valueN}
� As you can see, property and value is separated by :

Prepared By Mrs.S.J.Patil
(colon).
� Let’s see the simple example of creating object in
JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000};
document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>
2) BY CREATING INSTANCE OF OBJECT
� The syntax of creating object directly is given below:
var objectname=new Object();
� Here, new keyword is used to create object.

� Let’s see the example of creating object directly.

Prepared By Mrs.S.J.Patil
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary
);
</script>
3) BY USING AN 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.
� The example of creating object by object constructor is
given below.

Prepared By Mrs.S.J.Patil
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
OBJECT PROPERTIES
� The key:value pairs in JavaScript objects are called
properties:
id:102,
name:"Shyam Kumar",

Prepared By Mrs.S.J.Patil
salary:40000
� Key is always a string and value can be any data type.
� Accessing properties
� To access a property of an object, you use one of two
notations:
⮚ dot notation -objectName.propertyName
⮚ array-like notation[ ] =objectName['propertyName']
❑ Ex for accessing properties :
emp.name;
emp[name];
OBJECT METHODS
� Method is set of instructions performed by an object
when it receives a message.
� Methods are stored in properties as function definitions.
const person =
{

Prepared By Mrs.S.J.Patil
firstName: "John", lastName : "Doe", id : 5566, fullName
: function()
{
return this.firstName + " " + this.lastName;
}
};
� Accessing Object Methods :
• You access an object method with the following syntax:
objectName.methodName()
• Example: name=person.fullName();
EXAMPLE:
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;

Prepared By Mrs.S.J.Patil
this.changeSalary=changeSalary;
function changeSalary(otherSalary)
{
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
� o/p:103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
WHAT IS AN EVENT
� JavaScript's interaction with HTML is handled through
events that occur when the user or the browser
manipulates a page.
� When the page loads, it is called an event. When the

Prepared By Mrs.S.J.Patil
user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a
window, resizing a window, etc.
� Developers can use these events to execute JavaScript
coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated,
and virtually any other type of response imaginable.
• onclick Event Type :This is the most frequently used
event type which occurs when a user clicks the left
button of his mouse. You can put your validation,
warning etc., against this event type.
Prepared By Mrs.S.J.Patil
EXAMPLE :
JAVASCRIPT VARIABLE
� A JavaScript variable is simply a name of storage location.
There are two types of variables in JavaScript : local variable
and global variable.
� There are some rules while declaring a JavaScript variable
(also known as identifiers).
� Name must start with a letter (a to z or A to Z), underscore( _ ),
or dollar( $ ) sign.

Prepared By Mrs.S.J.Patil
� After first letter we can use digits (0 to 9), for example value1.
� JavaScript variables are case sensitive, for example x and X
are different variables.
� Before you use a variable in a JavaScript program, you must
declare it. Variables are declared with the var keyword.
var variablename;
� Eg
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
� A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only. For example:
<script>
function abc()
{
var x=10;//local variable
}
</script>
� A JavaScript global variable is accessible from any function. A variable

Prepared By Mrs.S.J.Patil
i.e. declared outside the function or declared with window object is known
as global variable. For example:
<script>
var data=200;//global variable
function a()
{
document.writeln(data);
}
function b()
{
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
VARIABLE INITIALIZATION
� Storing a value in a variable is called variable
initialization. You can do variable initialization at
the time of variable creation or at a later point in
time when you need that variable.
� JavaScript is a dynamic type language, means

Prepared By Mrs.S.J.Patil
you don't need to specify type of the variable because
it is dynamically used by JavaScript engine. You
need to use var here to specify the data type. It can
hold any type of values such as numbers, strings etc.
� For example:

⮚ var a=40; //holding number


⮚ var b="Rahul"; //holding string
JAVASCRIPT DATA TYPES

� JavaScript provides different data types to hold


different types of values. There are two types of
data types in JavaScript.
⚫ Primitive data type

Prepared By Mrs.S.J.Patil
⚫ Non-primitive (reference) data type
Prepared By Mrs.S.J.Patil
PRIMITIVE DATA TYPE
NON-PRIMITIVE (REFERENCE) DATA TYPE

Prepared By Mrs.S.J.Patil
JAVASCRIPT OPERATORS
� JavaScript operators are symbols that are used to
perform operations on operands.
For example: var sum=10+20;
� There are following types of operators in

Prepared By Mrs.S.J.Patil
JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JAVASCRIPT ARITHMETIC OPERATORS:ARITHMETIC
OPERATORS ARE USED TO PERFORM ARITHMETIC OPERATIONS ON THE
OPERANDS.

Prepared By Mrs.S.J.Patil
JAVASCRIPT COMPARISON OPERATORS:
THE JAVASCRIPT COMPARISON OPERATOR COMPARES THE TWO
OPERANDS. THE COMPARISON OPERATORS ARE AS FOLLOWS:

Prepared By Mrs.S.J.Patil
JAVASCRIPT BITWISE OPERATORS:
THE BITWISE OPERATORS PERFORM BITWISE OPERATIONS ON
OPERANDS. THE BITWISE OPERATORS ARE AS FOLLOWS:

Prepared By Mrs.S.J.Patil
JAVASCRIPT LOGICAL OPERATORS:
THE FOLLOWING OPERATORS ARE KNOWN AS JAVASCRIPT LOGICAL
OPERATORS.

Prepared By Mrs.S.J.Patil
JAVASCRIPT ASSIGNMENT OPERATORS
THE FOLLOWING OPERATORS ARE KNOWN AS JAVASCRIPT
ASSIGNMENT OPERATORS.

Prepared By Mrs.S.J.Patil
JAVASCRIPT SPECIAL OPERATORS
THE FOLLOWING OPERATORS ARE KNOWN AS JAVASCRIPT
SPECIAL OPERATORS.

Prepared By Mrs.S.J.Patil
JAVASCRIPT IF STATEMENT
� The JavaScript if-else statement is used to
execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.

Prepared By Mrs.S.J.Patil
� if Statement
� if else statement
� if else if statement
� nested if statement
JAVASCRIPT IF STATEMENT
� if statement is the most simple decision making statement.
� It is used to decide whether a certain statement or block of
statements will be executed or not.
� If a certain condition is true then a block of statement is executed
otherwise not.
� Syntax:
if(condition)

Prepared By Mrs.S.J.Patil
{
// block of code to be executed
}
� Example
<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>
Prepared By Mrs.S.J.Patil
JAVASCRIPT IF...ELSE STATEMENT
� If the condition is true then if block (true block) will
get executed and if the condition is false then else
block (false block) will get executed.
� Syntax:

Prepared By Mrs.S.J.Patil
if(Condition)
{
// block of code to be executed when condition is true
}
else
{
//block of code to be executed when condition is false
}
Prepared By Mrs.S.J.Patil
EXAMPLE OF IF-ELSE STATEMENT IN JAVASCRIPT TO FIND OUT
THE EVEN OR ODD NUMBER.

<script>
var a=20;
if(a%2==0)

Prepared By Mrs.S.J.Patil
{
document.write("a is even number");
}
else
{
document.write("a is odd number");
}
</script>
JAVASCRIPT IF...ELSE IF STATEMENT
� The if…else…if statement is an advanced form of if…else that allows
JavaScript to make a correct decision out of several conditions.
� All the if conditions will be checked one by one. If any condition is true out
of given then that block will get executed and other blocks are skipped.
� Syntax:
if(expression1)
{
//content to be evaluated if expression1 is true

Prepared By Mrs.S.J.Patil
}
else if(expression2)
{
//content to be evaluated if expression2 is true
}
else if(expression3)
{
//content to be evaluated if expression3 is true
}
else
{
//content to be evaluated if no expression is true
}
EXAMPLE:
<script>
var a=20;
if(a==10)
{
document.write("a is equal to 10");
}

Prepared By Mrs.S.J.Patil
else if(a==15)
{
document.write("a is equal to 15");
}
else if(a==20)
{
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
NESTED IF STATEMENT
� Embedding If Statement inside another IF Statement
called JavaScript Nested If Statement.
� The JavaScript Else Statement allows us to print
different statements depending upon the expression
result (TRUE, FALSE).

Prepared By Mrs.S.J.Patil
� Sometimes we have to check even further when the
condition is TRUE. In this situation, we can use
JavaScript Nested IF statement,
if ( test condition 1)
{ //If the test condition 1 is TRUE then these it will check
for test condition 2
if ( test condition 2)
{ //If the test condition 2 is TRUE then these statements
will be executed Test condition 2 True statements; }
else

Prepared By Mrs.S.J.Patil
{ //If the c test condition 2 is FALSE then these
statements will be executed Test condition 2 False
statements;
}
}
else
{ //If the test condition 1 is FALSE then these
statements will be executed Test condition 1 False
statements;
}
<html>
<body>
<script>
var age = 15;
if( age < 18 )
{
document.write("<b> You are Minor. </b>");
document.write("<br\> Not Eligible to Work " );
}
else

Prepared By Mrs.S.J.Patil
{
if (age >= 18 && age <= 60 )
{ document.write("<b> You are Eligible to Work. </b>");
document.write("<br\> Please fill in your details and apply " );
}
else
{ document.write("<b> You are too old to work as per the Government
rules </b>");
document.write("<br\> Please Collect your pension!" );
}
}
</script>
</body>
</html>
JAVASCRIPT SWITCH
� The objective of a switch statement is to give an expression to
evaluate and several different statements to execute based on the
value of the expression.
� The interpreter checks each case against the value of the
expression until a match is found. If nothing matches, a default
condition will be used.
� Syntax
switch(expression)

Prepared By Mrs.S.J.Patil
{
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
EXAMPLE OF SWITCH CASE
<script>
var grade='B';
var result;
switch(grade)
{
case 'A':

Prepared By Mrs.S.J.Patil
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
JAVASCRIPT LOOPS
� Looping in programming languages facilitates
the execution of a set of instructions/functions
repeatedly while some condition evaluates to
true.
There are four types of loops in JavaScript.

Prepared By Mrs.S.J.Patil

1. for loop
2. while loop
3. do-while loop
4. for-in loop
1) JAVASCRIPT 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.
� The syntax of for loop is given below.
for (initialization; condition; increment)

Prepared By Mrs.S.J.Patil
{
code to be executed
}
� Example:
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
2) JAVASCRIPT WHILE LOOP
� A while loop is a entry-controlled loop that allows code to be executed
repeatedly if the condition is true.
� When the condition becomes false, the loop terminates which marks the
end of its life cycle.
� The while loop executes ZERO or MORE times.
� It should be used if number of iteration is not known.

Prepared By Mrs.S.J.Patil
� The syntax of while loop is given below.
while (condition)
{
code to be executed
}
� Example:
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
3) JAVASCRIPT DO WHILE LOOP
� The JavaScript do while loop iterates the elements for the
infinite number of times like while loop.
� But, code is executed at least once whether condition is true or
false.
� The syntax of do while loop is given below.
do
{

Prepared By Mrs.S.J.Patil
code to be executed
}while (condition);
� Example:
<script>
var i=21;
do
{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
4) JAVASCRIPT FOR IN LOOP
� The for..in loop provides a simpler way to iterate through the
properties of an object.
� This loop is seen to be very useful while working with objects.
� In each iteration, one of the properties of Object is assigned to
the variable named variableName and this loop continues
until all of the properties of the Object are processed.
� Syntax:

Prepared By Mrs.S.J.Patil
for (variablename in object)
{
code block to be executed
}
� Example:
const numbers = [45, 4, 9, 16, 25];
var x;
for ( x in numbers)
{
document.write(numbers[x]);
}
JAVASCRIPT BREAK AND CONTINUE
� The break statement "jumps out" of a loop.
� break statement Stops the execution of a loop entirely.
for (let i = 0; i < 10; i++)
{
if (i === 3) { break; }
text += "The number is " + i + "<br>";

Prepared By Mrs.S.J.Patil
}
� The continue statement "jumps over" one iteration in
the loop.
� The continue statement breaks one iteration (in the
loop), if a specified condition occurs, and continues with
the next iteration in the loop.
for (let i = 0; i < 10; i++)
{
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
PROPERTY GETTERS AND SETTERS
1. Javascript supports two properties: data property and
accessor property.
2. The accessor properties. They are essentially functions that work
on getting and setting a value.
3. Accessor properties are represented by “getter” and “setter”
methods. In an object literal they are denoted by get and set.
4. get- a function without arguments, that works when property is

Prepared By Mrs.S.J.Patil
read.
5. Set- a function with one argument, that is called when the
property is set.

let obj =
{
get propName()
{ // getter, the code executed on
getting obj.propName },
set propName(value)
{ // setter, the code executed on
setting obj.propName = value}
};
PROPERTY GETTERS AND SETTERS
6. An object property is a name, a value and a set of
attributes. The value may be replaced by one or two
methods, known as setter and a getter.
7. When program queries the value of an accessor property,
Javascript invoke getter method(passing no arguments).
The return value of this method become the value of the
property access expression.

Prepared By Mrs.S.J.Patil
8. When program sets the value of an accessor property.
Javascript invoke the setter method, passing the value of
right-hand side of assignment.
This method is responsible for setting the property value.
If property has both getter and a setter method, it is
read/write property.
If property has only a getter method , it is read-only
property.
If property has only a setter method , it is a write-only
property.
9. getter works when obj.propName is read, the setter –
when it is assigned
EXAMPLE:
<html>
<head> <title>functions</title>
<body>
<script language=“javascript”>
var myCar =
{

Prepared By Mrs.S.J.Patil
/* Data properties */
defColor: "blue",
defMake: "Toyota",
/* Accessor properties (getters) */
get color()
{
return this.defColor;
},
get make()
{ return this.defMake;
},
/* Accessor properties (setters) */
set color(newColor)
{
this.defColor = newColor;
},
set make(newMake)
{
this.defMake = newMake;

Prepared By Mrs.S.J.Patil
}
};
document.write("Car color:" + myCar.color + " Car Make: "+myCar.make)
/* Calling the setter accessor properties */
myCar.color = "red";
myCar.make = "Audi“;
/* Checking the new values with the getter accessor properties */
document.write("Car color:" + myCar.color); // red
document.write(" Car Make: "+myCar.make);//Audi
</script>
</head>
</body>
</html>
DELETING PROPERTIES
� The delete keyword deletes a property from an object.
� delete property returns true if deleted successfully.

� Syntax: delete objectname.propertyname;

� Example:

Prepared By Mrs.S.J.Patil
const person =
{
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age; // the person object has no age property

You might also like