Unit 1 CSS (Client Side Scripting)

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

Script

 A script is a small piece of program that can add interactivity to the website. For example, a script
could generate a pop-up alert box message, or provide a dropdown menu. This script could be
JavaScript or VBScript.
 A script language is a subcategory of programming language with which you can write scripts.
Scripting languages need to be interpreted (Scanning the code line by line, not like compiler in one
go) instead of compiled. There is no scope of compiler in scripting languages. Scripting languages
are most widely used to create a website.
 JavaScript, Perl, PHP, Python, VBScript are the most popular examples of scripting Languages.

What is Client side Script?


A client-side script is a small program (or set of instructions) that is embedded (or inserted) into a
web page.
It is processed within the client browser instead of the web server.
The client side script is downloaded at the client end from the server along with the HTML web page
it is embedded in.
The web browser interprets and executes the code and then displays the results on the monitor.
The script that executes on the user’s computer system is called client.
It is embedded (or inserted) within the HTML document or can be stored in an external separate file
(known as external script).
The script files are sent to the client machine from the web server (or severs) when they are
requested.
The client’s web browser executes the script, then displays the web page, including any visible
output from the script.

Client side scripts may also have some instructions for the web browser to follow in response to
certain user actions, such as pressing a page button. They can often be looked if client want to view
the source code of web page.

Client Side Scripting (Unit 1) Arrow Computer Academy


What is JavaScript ?
JavaScript is a dynamic computer programming language.
It is lightweight and most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages.
It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.

Features of JavaScript
 JavaScript is a lightweight, interpreted programming language.
 Interpreter Based Scripting Language
 Case Sensitive
 Designed for creating network-centric applications.
 Integrated with HTML.
 Open and cross-platform
 Validating User’s Input : JavaScript is very useful while using forms. It has the capability to
validate user input for errors and also saves time. If the user leaves a required field empty or the
information is incorrect, JavaScript checks for them before sending the data over to the server.

Advantages of JavaScript
 Speed: Client-side JavaScript is very fast because it can be run immediately within the client-
side browser.
 Simplicity: JavaScript is relatively simple to learn and implement.
 Popularity: JavaScript is used everywhere on the web.
 Interoperability: JavaScript plays nicely with other languages and can be used in a huge
variety of applications.
 Server Load: Being client-side reduces the demand on the website server.
 Gives the ability to create rich interfaces.
 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors
 Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.

Client Side Scripting (Unit 1) Arrow Computer Academy


Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important
features –
 Client-Side Security: Because the code executes on the users’ computer, in some cases it can be
exploited for malicious purposes. This is one reason some people choose to disable Javascript.
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
 JavaScript cannot be used for networking applications because there is no such support
available.
 JavaScript doesn't have any multi-threading or multiprocessor capabilities.

Where to write Javascript code:


1. Directly in Browser Console
2. In HTML file and embed the code of Javascript
3. In separate Javascript File and linking this file in HTML file

Tools to run JavaScript Code:


JavaScript Editors: Notepad,Notepad++, VS, Sublime, Eclipse, Atom
Browser: Chrome,Firefox,Safari,Edge

JavaScript Programming
Q] Explain <script> tag with example?
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> tags, containing your JavaScript, anywhere within your web page.
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>
The script tag takes two important attributes −
1. Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor) have
phased out the use of this attribute.

2. Type – This attribute tells the browser that script is in plain text and text is organised in the
format of javascript.
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Client Side Scripting (Unit 1) Arrow Computer Academy


Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use
spaces, tabs, and newlines freely in your program and you are free to format and indent your
programs.
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in
C, C++, and Java.
JavaScript, however, allows you to omit this semicolon if each of your statements are placed on a
separate line.
For example, the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
document.write("Hello")
document.write("Welcome to Arrow Academy")
</script>

But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
document.write("Hello"); document.write("Welcome to Arrow Academy")
</script>

Note − It is a good programming practice to use semicolons.

Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.

Comments in JavaScript
1JavaScript supports both C-style and C++-style comments, Thus −
 Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
 Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
Example
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
// This is a comment. It is similar to comments in C++
/*
This is a multi-line comment in JavaScript
It is very similar to comments in C Programming
*/
</script>

Client Side Scripting (Unit 1) Arrow Computer Academy


 JavaScript Enabling
All the modern browsers such as Internet Explorer, Firefox, chrome, and Opera come with built-in
support for JavaScript. Frequently, you may need to enable or disable this support manually.

Activate JavaScript in Google Chrome


 Open Chrome on your computer.
 Click More and then Settings.
 Click Security and Privacy.
 Click Site settings.
 Click JavaScript.
 Select Sites can use Javascript.

JavaScript in Internet Explorer


Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
 Follow Tools → Internet Options from the menu.
 Select Security tab from the dialog box.
 Click the Custom Level button.
 Scroll down till you find Scripting option.
 Select Enable radio button under Active scripting.
 Finally click OK and come out

 JavaScript Placement
There is a flexibility given to include JavaScript code anywhere in an HTML document. However the
most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.

a) JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere, then you will
place that script in the head as follows −
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("WELCOME TO ARROW World")
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello"/>
</body>
</html>

Client Side Scripting (Unit 1) Arrow Computer Academy


b) JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document. In this case, you would not have any function
defined using JavaScript. Take a look at the following code.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
</body>
</html>

c) JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Welcome to Arrow World")
}
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />


</body>
</html>

d) JavaScript in External File


The script tag provides a mechanism to allow you to store JavaScript in an external file and then
include it into your HTML files.
<html>
<head>
<script type = "text/javascript" src = "C:\Users\Akshay\Desktop\akshay.js">
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

Client Side Scripting (Unit 1) Arrow Computer Academy


To use JavaScript from an external file source, you need to write all your JavaScript source code in a
simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello()
{
alert("Welcome to Arrow")
}
document.write("I am creating javascript external code<br>");

Client Side Scripting (Unit 1) Arrow Computer Academy


JavaScript Variables
JavaScript includes Variables which are defined as named memory locations. Variable stores a
single data value that can be changed later.

Variable Declaration:
Before you use a variable in a JavaScript program, you must declare it.
Variables are declared with the var keyword as follows.

<script type = "text/javascript">


var money;
var name;
</script>

You can also declare multiple variables with the same var keyword as follows −

<script type = "text/javascript">


var money, name;
</script>

A variable declared without a value will have the value undefined.

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.

<script type = "text/javascript">

var name = "Ali";


var money;
money = 2000.50;

</script>

Note − Use the var keyword only for declaration or initialization, once for the life of any variable
name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value and type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.

var:
1. A variable can be reassigned using var keyword
2. A variable can be redeclared using var keyword

Client Side Scripting (Unit 1) Arrow Computer Academy


Eg:
var a= 12.5;
a=”Arrow”; // Reassign
var a = 15.5; //redeclare

let:
1. A variable can be reassigned using let keyword
2. A variable can not be redeclared using let keyword
Eg:
let b = 15.6;
b = “Academy” // Reassign
let b = 23.5 // Error

const:
In JavaScript, const is a keyword used to declare a variable that cannot be reassigned a new value. It
is similar to let, but the value of a const variable cannot be changed once it has been declared.
1. Variables defined with const cannot be Redeclared
2. Variables defined with const cannot be Reassigned
JavaScript const must be assigned a value when they are declared.

Example:
const PI = 3.14159265359;

Example 2:-
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined. JavaScript variables have
only two scopes.

Global Variables − A global variable has global scope which means it can be defined anywhere in
your JavaScript code.

Local Variables − A local variable will be visible only within a function where it is defined.
Within the body of a function, a local variable takes precedence over a global variable with the same
name.
If you declare a local variable or function parameter with the same name as a global variable, you
effectively hide the global variable.
Example:
<html>
<head>

</head>

Client Side Scripting (Unit 1) Arrow Computer Academy


<body>
<script type = "text/javascript">

var a = 25; // Declare a global variable


function fun( )
{
var a = 10; // Declare a local variable
document.write("Value of a is"+ a);
}
fun();
document.write("Value of a is"+ a);
</script>

</body>
</html>

This produces the following result −


Value of a is 10
Value of a is25

Rules for JavaScript Variable Names:

1. You should not use any of the JavaScript reserved keywords as a variable name.
For example, break or boolean variable names are not valid.

2. JavaScript variable names should not start with a numeral (0-9).


Variable names must start with a letter, an underscore (_) or a dollar sign ($).

3. Variable names cannot contain spaces.

4. JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.

JavaScript Data Types

JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type

1. JavaScript primitive data types


JavaScript primitive data types are data types that refer to a single value.

Client Side Scripting (Unit 1) Arrow Computer Academy


There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description Example

string represents sequence of characters e.g. "hello" var str = “Hello”;

number represents numeric values e.g. 100 var n = 100;


var m = 12.53;
boolean represents boolean value either false or true var x =true;
var y = false;
undefined represents undefined value var x = undefined

null represents null or empty or unknown value. var x = null

2. JavaScript non-primitive data types


The data types that are derived from primitive data types of the JavaScript language are known as
non-primitive data types.
It is also known as derived data types.
It contains single or multiple key-value pair/s.

The non-primitive data types are as follows:


- Object
- Array
- RegExp

1.3 Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

All cars have the same properties, but the property values differ from car to car. All cars have the
same methods, but the methods are performed at different times.

Client Side Scripting (Unit 1) Arrow Computer Academy


A] JavaScript Objects

 JavaScript is an object-based language. Everything is an object in JavaScript.


 All primitive data types can contain only a single thing (either a string or a number). In contrast,
objects are used to store collections of data and more complex entities.
 JavaScript objects are collections of properties and methods.

 A property is a value or set of values that is a member of an object


 A method is a function that is a member of an object.

 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,
 You access an object's properties and methods by using the dot syntax along with the object
name and its property or method.

B] Object Name
 Each object is uniquely identified by a name or ID.
 A web page contains many objects, some of which are the same kind of object. These objects can
be easily distinguishable by using its name or ID.

C] Property
 A property is a data or value associated with an object.
 Objects can have many data's associated with them depending on application of use.
 For example, a form object can have a title, a width and a height as properties whereas a
window object can have a background color, a width and height as properties.
 Hence, each object has its own set of properties. An object can be created with curly brackets
{...} with list of properties.
 A property is a "key: value pair, where key is a string (also called a "property name"), and value
can be anything.

D] Creating a JavaScript Object


With JavaScript, you can define and create your own objects. There are different ways to create new
objects:

 Define and create a single object, using an object literal.


 Define and create a single object, with the keyword new. (By creating instance of Object)
 Define an object constructor, and then create objects of the constructed type.

1. Using an Object Literal


This is the easiest way to create a JavaScript Object. Using an object literal, you both define and
create an object in one statement. An object literal is a list of name:value pairs inside curly
braces {}.

The following example creates a new JavaScript object with four properties:
syntax :

Client Side Scripting (Unit 1) Arrow Computer Academy


object={property1:value1 , property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
Example:
<script>
emp={id:102, name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Spaces and line breaks are not important. An object definition can span multiple lines:
<script>
emp= {
id:102,
name:"Shyam Kumar",
salary:40000
}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

2. Define and create a single object, with the keyword new. (By creating instance of Object)
Syntax:
var objectname=new Object();
Here, new keyword is used to create object.
Example:
<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.
Example:
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Akshay",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

Client Side Scripting (Unit 1) Arrow Computer Academy


/* Program to Create objects in three ways */

<!DOCTYPE html>
<html>
<head>
<title>Creating Object</title>
</head>
<body>
<script type="text/javascript">
/*Using Object Literal*/
emp = {name:"Akshay",id:17,salary:50000};
document.write("Name is "+emp.name+"<br>");
document.write("Id is "+emp.id+"<br>");
document.write("Salary is "+emp.salary+"<br>");

/*Using new Keyword , create instance of Object*/

var teacher=new Object();


teacher.name="Patil";
teacher.designation="Lecturer";
teacher.salary=150000;

document.write("Name is "+teacher.name+"<br>");
document.write("Designation is "+teacher.designation+"<br>");
document.write("Salary is "+teacher.salary+"<br>");

/* Using object constructor*/

function student(name,roll,marks)
{
this.name=name;
this.roll=roll;
this.marks= marks;
}

s1= new student("Amol",98,96);


document.write("Name is "+s1.name+"<br>");
document.write("Roll number is "+s1.roll+"<br>");
document.write("Marks are "+s1.marks);
</script>
</body>
</html>

Client Side Scripting (Unit 1) Arrow Computer Academy


E] Dot Syntax:
 The properties & methods associated with any object can be accessed by using the object
name with dot syntax.
 E.g. user.fname, user.lname & user.fullName( ).
In the following code user object is created with two properties:
1 The first property has the name fname and the value "Computer"
2. The second one has the name lname and the value "Engineering".

You can access the object properties in following two ways:


1. user.fname;
2. user[“fname”]

Example 1:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
fname: " Computer ",
lname: " Engineering”
};
document.write(“User =” + user.fname +” “+ user. lname);
</script>
</body>
</html>
Output:
User – Computer Engineering

Example 2:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
fname: " Computer ",
lname: " Engineering”
};
document.write(“User =” + user[“fname”] +” “+ user[“ lname”]);
</script>
</body>
</html>
Output:
User – Computer Engineering

Client Side Scripting (Unit 1) Arrow Computer Academy


F] Method
We can define method in JavaScript object. In an object method, “this” refers to the object.
Example:
<script>
var person = {
firstName: "Arrow",
lastName : "Academy",
fullName : function()
{
return this.firstName + " " + this.lastName;
}
};
document.write(“User Name is:” + person.fullname());
</script>

The this Keyword


In JavaScript, this keyword refers to the object that is currently executing a function or method.
In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.

Eg: Creating Object with properties, Method, array and object in it.
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
fname: "Arrow",
lname: "Academy",
age:25,
email:"arrowacademy@gmail.com",
fullname:function()
{
return this.fname+this.lname;
},
favmovies:["Dhoom","Sholay","3 Idiots"],
address:{city:"Ahmednagar", state:"Maharashtra"}
};
document.write("First Name is =" +user.fname+"<br>");
document.write("Last Name is =" +user.lname+"<br>");
document.write("Age is =" +user.age+"<br>");
document.write("Email is =" +user.email+"<br>");
document.write("Favaourite Movies are =" +user.favmovies[1]+"<br>");
document.write("Address is "+user.address.city+" "+user.address.state+"<br>");
document.write("Full Name is =" +user.fullname()+"<br>");
</script>
</body>
</html>

Client Side Scripting (Unit 1) Arrow Computer Academy


Input from Use:

In JavaScript, we use the prompt() function to ask the user for input.
As a parameter, we input the text we want to display to the user.
Once the user presses “ok,” the input value is returned.
prompt returns the user input as a string, but if you want the user input to return a number instead
of a string, you can convert the string to an integer using parseInt()
<html>
<head>
</head>
<body>
<script type = "text/javascript">
var name = prompt("What is your name?");
var num1 = parseInt(prompt("Enter First Number"));
var num2 = parseInt(prompt("Enter Second Number"));
var sum = num1 + num2
document.write("Name is "+name);
document.write("Your Favourite Number is "+sum);
</script>
</body>
</html>

Client Side Scripting (Unit 1) Arrow Computer Academy


1.5 JavaScript Operator
JavaScript operators are symbols that are used to perform operations on operands.
JavaScript supports the following types of operators.

 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Lets have a look on all operators one by one.

1) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
Assume variable A holds 10 and variable B holds 20, then −
Sr. Operator & Description Example

1 + (Addition): Adds two operands Ex: A + B will give 30

2 - (Subtraction): Subtracts the second operand from the first Ex: A - B will give -10

3 * (Multiplication): Multiply both operands Ex: A * B will give 200

4 / (Division): Divide the numerator by the denominator Ex: B / A will give 2

5 % (Modulus): Outputs the remainder of an integer division Ex: B % A will give 0

6 ++ (Increment): Increases an integer value by one Ex: A++ will give 11

7 -- (Decrement): Decreases an integer value by one Ex: A-- will give 9

Ex. A**B will give A


8 ** (Exponentiation)
raised to power B

Example:-

<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operators</title>
</head>
<body>
<script type="text/javascript">
var a=10,b=2;
var add=a+b
var sub=a-b
var mul=a*b

Client Side Scripting (Unit 1) Arrow Computer Academy


var div=a/b
var rem=a%b
var exp=a**b

document.write("Addition is"+add+"<br>");
document.write("Subtraction is",sub+"<br>");
document.write("Multiplication is",mul+"<br>");
document.write("Division is",div+"<br>");
document.write("Remainder is",rem+"<br>");
document.write("Exponent is",exp+"<br>");

</script>
</body>
</html>

2) Assignment Operators
JavaScript supports the following assignment operators −
Sr. Operator & Description Example

= (Simple Assignment )
Ex: C = A + B will assign the
1 Assigns values from the right side operand to the left side
value of A + B into C
operand

+= (Add and Assignment)


Ex: C += A is equivalent to C
2 It adds the right operand to the left operand and assigns the
=C+A
result to the left operand.

−= (Subtract and Assignment)


Ex: C -= A is equivalent to C
3 It subtracts the right operand from the left operand and
=C-A
assigns the result to the left operand.

*= (Multiply and Assignment)


Ex: C *= A is equivalent to C
4 It multiplies the right operand with the left operand and
=C*A
assigns the result to the left operand.

/= (Divide and Assignment)


Ex: C /= A is equivalent to C
5 It divides the left operand with the right operand and assigns
=C/A
the result to the left operand.

%= (Modules and Assignment)


Ex: C %= A is equivalent to
6 It takes modulus using two operands and assigns the result to
C=C%A
the left operand.

Ex. C**=A is equivalent to


7 **=
C=C**A

Client Side Scripting (Unit 1) Arrow Computer Academy


Example of Assignment Operator:
<html>
<head>
<title>Assignment Operators</title>
</head>
<body>
<script type="text/javascript">
var a=10,b=2;
a+=b
a-=b
a*=b
a/=b
a%=b
a**=b
document.write("Addition is"+a+"<br>");
document.write("Subtraction is"+b+"<br>");
document.write("Multiplication is"+m+"<br>");
document.write("Division is"+div+"<br>");
document.write("Remainder is"+rem+"<br>");
document.write("Exponent is",exp+"<br>");
</script>
</body>
</html>

3) Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr. Operator & Description Example

= = (Equal)
1 Ex: (A == B) is not
Checks if the value of two operands are equal or not, if yes, then the
true.
condition becomes true.

!= (Not Equal)
2 Checks if the value of two operands are equal or not, if the values Ex: (A != B) is true.
are not equal, then the condition becomes true.

> (Greater than)


Ex: (A > B) is not
3 Checks if the value of the left operand is greater than the value of
true.
the right operand, if yes, then the condition becomes true.

< (Less than)


4 Checks if the value of the left operand is less than the value of the Ex: (A < B) is true.
right operand, if yes, then the condition becomes true.

>= (Greater than or Equal to)


Ex: (A >= B) is not
5 Checks if the value of the left operand is greater than or equal to the
true.
value of the right operand, if yes, then the condition becomes true.

Client Side Scripting (Unit 1) Arrow Computer Academy


<= (Less than or Equal to)
6 Checks if the value of the left operand is less than or equal to the Ex: (A <= B) is true.
value of the right operand, if yes, then the condition becomes true.

Ex: A=5 and B=”5”


7 === (equal value and equal type)
Then A ===B is False

Ex: A=5 and B=”5”


8 !== (Not equal value or Not equal type)
Then A !==B is True

4) Logical Operators
Assume variable A holds 10, variable B holds 20, variable C holds 30, then −
Sr. Operator & Description Example

&& (Logical AND)


Ex: (A<B && B < C) is
1 If both the operands are true, then the condition becomes
true.
true, otherwise it returns false.

|| (Logical OR)
2 If any of its arguments are true, it returns true, otherwise it Ex: (A>B || B < C) is false.
returns false.

! (Logical NOT)
3 If a condition is true, then the Logical NOT operator will Ex: ! (A && B) is false.
make it false and vice versa.

5) Bitwise Operators
Assume variable A holds 2 and variable B holds 3, then −
Sr. Operator & Description Example

& (Bitwise AND)


1 It performs a Boolean AND operation on each bit of its integer Ex: (A & B) is 2.
arguments.

| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer Ex: (A | B) is 3.
arguments.

^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its integer
3 Ex: (A ^ B) is 1.
arguments. Exclusive OR means that either operand one is true or
operand two is true, but not both.

~ (Bitwise Not)
4 Ex: (~B) is -4.
It is a unary operator and operates by reversing all the bits in the

Client Side Scripting (Unit 1) Arrow Computer Academy


operand.

<< (Left Shift)


It moves all the bits in its first operand to the left by the number of
5 places specified in the second operand. New bits are filled with zeros. Ex: (A << 1) is 4.
Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on.

>> (Right Shift)


6 Binary Right Shift Operator. The left operand’s value is moved right by Ex: (A >> 1) is 1.
the number of bits specified by the right operand.

A B A&B A|B A^B ~A


0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

Example: A=17, B=25


1. And
16 8 4 2 1
A=10001
B=11001
---------------
10001 (17)

2. Or
A=10001
B=11001
-------------------
1 1 0 0 1 (25)

3. XOR
A=10001
B=11001
---------------------
= 01000 (8)

Client Side Scripting (Unit 1) Arrow Computer Academy


4. Not (~A)
A=10001
-------------------
0 1 1 1 0 ( -18 )

Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">

var A = 17,B=25;
document.write("Result of AND operation is "+(A&B));
document.write("<br>");
document.write("Result of OR operation is "+(A|B));
document.write("<br>");
document.write("Result of XOR operation is "+(A^B));
document.write("<br>");
document.write("Result of NOT operation is "+(~A));
document.write("<br>");
document.write("Result of Leftshift operation is "+(A<<2));
document.write("<br>");
document.write("Result of Rightshift operation is "+(A>>2));

</script>
</body>
</html>

6) Ternary Operator
JavaScript includes special operator called ternary operator ?: that assigns a value to a variable
based on some condition. This is like short form of if-else condition.
Syntax:
<condition> ? <value1> : <value2>;
Ternary operator starts with conditional expression followed by ? operator. Second part (after ? and
before : operator) will be executed if condition turns out to be true. If condition becomes false then
third part (after :) will be executed.
Example:
var a=10,b=25;
large=a>b?a:b;
document.write("Largest Number is ",large);

Output: Largest Number is 25

Client Side Scripting (Unit 1) Arrow Computer Academy


Conditional Statements
While writing a program, there may be a situation when you need to adopt one out of a given set of
paths. In such cases, you need to use conditional statements that allow your program to make
correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on
different conditions.

A] if..else statement
Flow Chart of if-else

JavaScript supports the following forms of if..else statement −


 if statement
 if...else statement
 if...else if... statement.

1) if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.

Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be executed. Most of the times, you
will use comparison operators while making decisions.

Client Side Scripting (Unit 1) Arrow Computer Academy


Example
Try the following example to understand how the if statement works.

<html>
<body>
<script type = "text/javascript">
var age = 20;
if( age > 18 )
{
document.write("Qualifies for driving ");
}
</script>
</body>
</html>

Output
Qualifies for driving

2) if...else statement

Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the
‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are
executed.

Example

Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
var age = 15;

if( age > 18 )


{
document.write("<b>Qualifies for driving</b>");
}
else
{
document.write("<b>Does not qualify for driving</b>");
}

Client Side Scripting (Unit 1) Arrow Computer Academy


</script>
</body>
</html>

Output
Does not qualify for driving

3) 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.

Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
It is just a series of if statements, where each if is a part of the else clause of the previous statement.
Statement(s) are executed based on the true condition, if none of the conditions is true, then
the else block is executed.

Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<script type="text/javascript">

var m1=65,m2=60,m3=35,tot,per;

tot = m1+m2+m3;
per=tot/3;

if(per>=75 && m1>=40 && m2>=40 && m3>=40)


{
document.write("Distinction");
}
else if(per>=60 && m1>=40 && m2>=40 && m3>=40)

Client Side Scripting (Unit 1) Arrow Computer Academy


{
document.write("First Class");
}

else if(per>=50 && m1>=40 && m2>=40 && m3>=40)


{
document.write("Second Class");
}

else if(per>=40 && m1>=40 && m2>=40 && m3>=40)


{
document.write("Pass Class");
}
else
{
document.write("Ghode");
}

</script>

4) nested if else statement


Nested if statements mean if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example:
<!DOCTYPE html>
<html>
<head>
<title>Nested If Else</title>
<script type="text/javascript">
var a=10,b=40,c=30;
if(a>b)
{
if(a>c)
{
document.write("Largest number is "+a)
}
else
{
document.write("largest number is "+c)

Client Side Scripting (Unit 1) Arrow Computer Academy


}
}
else
{
if(b>c)
{
document.write("Largest number is "+b)
}
else
{
document.write("Largest number is "+c)
}
}
</script>
</head>
<body>
</body>
</html>

B) switch statement
The JavaScript switch statement is used in decision making.
The switch statement evaluates an expression and executes the corresponding body that matches
the expression's result.
Syntax:
switch (variable/expression)
{
case value1:
// body of case 1
break;
case value2:
// body of case 2
break;
case valueN:
// body of case N
break;
default:
// body of default
}

The switch statement evaluates a variable/expression inside parentheses ().


 If the result of the expression is equal to value1, its body is executed.
 If the result of the expression is equal to value2, its body is executed.
 This process goes on. If there is no matching case, the default body executes.

Notes:

Client Side Scripting (Unit 1) Arrow Computer Academy


 The break statement is optional. If the break statement is encountered, the switch statement ends.
 If the break statement is not used, the cases after the matching case are also executed.
 The default clause is also optional.

Flowchart:

Client Side Scripting (Unit 1) Arrow Computer Academy


Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type = "text/javascript">
var grade = 'C';
document.write("Entering switch block <br>");
switch (grade)
{
case 'A': document.write("Distinction <br>");
break;
case 'B': document.write("First Class<br>");
break;
case 'C': document.write("Second Class <br>");
break;
case 'D': document.write("Pass Class <br>");
break;
case 'E': document.write("Failed <br>");
break;
default: document.write("Unknown grade <br>")
}
document.write("Exiting switch block");
</script>

</body>
</html>

Output
Entering switch block
Second Class
Exiting switch block

Example 2
<!DOCTYPE html>
<html>
<head>
<title>Switch</title>
<script type = "text/javascript">

var operator = '+';


var number1=23,number2=10,result;
document.write("Entering switch block<br />");
switch(operator)
{

Client Side Scripting (Unit 1) Arrow Computer Academy


case '+':
result = number1 + number2;
document.write(result)
break;
case '-':
result = number1 - number2;
document.write(result)
break;
case '*':
result = number1 * number2;
document.write(result)
break;
case '/':
result = number1 / number2;
document.write(result)
break;
case '%':
result = number1 % number2;
document.write(result)
break;

default:
document.write("Wrong Arithmetic Operator")
break;
}

</script>
</head>
<body>
</body>
</html>

Loop in JavaScript
While writing a program, you may encounter a situation where you need to perform an action over
and over again. In such situations, you would need to write loop statements to reduce the number
of lines.

1) The while Loop


The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.
Syntax:

while (expression)
{
Statement(s) to be executed if expression is true

Client Side Scripting (Unit 1) Arrow Computer Academy


}

 A while loop evaluates the condition inside the parenthesis ().


 If the condition evaluates to true, the code inside the while loop is executed.
 The condition is evaluated again.
 This process continues until the condition is false.
 When the condition evaluates to false, the loop stops.

Flow Chart

Example:

<html>
<body>

<script type = "text/javascript">


var count = 0;
document.write("Starting Loop ");

while (count < 10) {


document.write("Current Count : " + count + "<br />");
count++;
}

document.write("Loop stopped!");

Client Side Scripting (Unit 1) Arrow Computer Academy


</script>

<p>Set the variable to different value and then try...</p>


</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

2) The do...while Loop


The do...while loop is similar to the while loop except that the condition check happens at the end of
the loop. This means that the loop will always be executed at least once, even if the condition
is false.
Flow Chart

Syntax
do
{
Statement(s) to be executed;
} while (expression);

Client Side Scripting (Unit 1) Arrow Computer Academy


Note − Don’t miss the semicolon used at the end of the do...while loop.
Example:
Try the following example to learn how to implement a do-while loop in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do {
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...

3) The 'for' loop


The 'for' loop is the most compact form of looping. It includes the following three important parts −
 The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If the condition is true,
then the code given inside the loop will be executed, otherwise the control will come out of
the loop.
 The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.

Client Side Scripting (Unit 1) Arrow Computer Academy


Flow Chart

Syntax
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
Example

<html>
<body>
<script type = "text/javascript">
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++)


{
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop stopped!");
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>

Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4

Client Side Scripting (Unit 1) Arrow Computer Academy


Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

break statement
The break statement is used to terminate from the loop immediately. When a break statement is
encountered inside a loop, the loop iteration stops there, and control returns from the loop
immediately to the first statement after the loop.
Example:
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{
if(count==5)
{
break
}
document.write("Current Count : " + count );
document.write("<br />");
}
</script>

Output:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4

continue statement
The continue statement in Java is used to skip the current iteration of a loop.

<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++)


{
if(count==5)

Client Side Scripting (Unit 1) Arrow Computer Academy


{
continue
}
document.write("Current Count : " + count );
document.write("<br />");

}
</script>
Output:
Starting Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Current Count: 6
Current Count: 7
Current Count: 8
Current Count: 9

JavaScript Values or Literals:


JavaScript Literals are constant values that can be assigned to the variables.

1. Array literals
In Javascript, an array literal is a list of expressions, each of which represents an array element,
enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is
initialized with the specified values as its elements, and its length is set to the number of arguments
specified. If no value is supplied it creates an empty array with zero length.

Creating an empty array :


var fruits = [ ];
Creating an array with four elements.
var fruits = ["Orange", "Apple", "Banana", "Mango"]

2. Integers literals
An integer must have at least one digit (0-9).
No comma or blanks are allowed within an integer.
It does not contain any fractional part.
It can be either positive or negative if no sign precedes it is assumed to be positive.
In JavaScript, integers can be expressed in three different bases.

1. Decimal ( base 10)

Client Side Scripting (Unit 1) Arrow Computer Academy


Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no leading
zeros.
Example: 123

2. Hexadecimal ( base 16)


Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, E, F
or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal.
Example: 0x123

3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number is
octal.
Example: 0123

3. Floating number literals


A floating number has the following parts.
 A decimal integer.
 A decimal point ('.').
 A fraction.
Example:
8.2935
-14.72

4. Boolean literals
The Boolean type has two literal values: true and false

5. Object literals
An object literal is zero or more pairs of comma-separated list of property names and associated
values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:

1. An object literal without properties:


var student = { }

2. An object literal with a few properties :


var student =
{
First-name : "Akshay",
Last-name : "Rayy",
Roll-No : 12
};

Syntax Rules
There is a colon (:) between property name and value.
A comma separates each property name/value from the next.
There will be no comma after the last property name/value pair.

Client Side Scripting (Unit 1) Arrow Computer Academy


6. String literals

A string literal is zero or more characters, either enclosed in single quotation (') marks or double
quotation (") marks.
You can also use + operator to join strings.
The following are the examples of string literals :

string1 = "computer"
string1 = 'engineering.com'
string1 = "1000"
string1 = "google" + ".com"

prompt()
The Javascript window.prompt() method is used to display a dialog box with an optional
message prompting the user to input some text.
It is often used if the user wants to input a value before entering a page. It returns a string
containing the text entered by the user, or null.
Syntax:
prompt(message, default)
 message argument is optional and specifies the text to display in the dialog box.
 default argument is also optional and specifies the default input text.
 Return value: The input value is returned if the user clicks the ‘OK’ button. If not so
then null is returned.
Example:
var name = prompt("Please enter your name", "Arrow");
document.write("Name is "+name);

parseInt
The parseInt method parses a value as a string and returns the integer.
Syntax
parseInt(string, radix)
Parameters

Parameter Description

string Required.
The value to be parsed.

radix Optional. Default is 10.


A number (2 to 36) specifying the number system.

A radix parameter specifies the number system to use:


2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.

Client Side Scripting (Unit 1) Arrow Computer Academy


If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes
radix 16.
Notes
If the first character cannot be converted, NaN is returned.
Leading and trailing spaces are ignored.
Only the first integer found is returned.

parseFloat function
The parseFloat() function is used to accept a string and convert it into a floating-point number. If the
input string does not contain a numeral value or If the first character of the string is not a number
then it returns NaN i.e, not a number.

Program 1: add 2 Numbers


<script type="text/javascript">
var num1 = parseInt(prompt('Enter the first number '));
var num2 = parseInt(prompt('Enter the second number '));
//add two numbers
var sum = num1 + num2;
// display the sum
document.write("The sum of "+num1 + " and " + num2 + " is ",sum);
</script>

Program 2:- Even Odd


<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<script type="text/javascript">

var number = parseInt(prompt("Enter a number: "));

//check if the number is even


if(number % 2 == 0) {
document.write("The number is even.");
}

// if the number is odd


else {
document.write("The number is odd.");
}
</script>

Client Side Scripting (Unit 1) Arrow Computer Academy


</body>
</html>

Program: Factorial of Number

<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<script type="text/javascript">
var number = parseInt(prompt('Enter a positive integer: '));
if (number < 0) {
document.write('Error! Factorial for negative number does not exist.');
}
// if number is 0
else if (number === 0) {
document.write("The factorial is 1 ");
}

// if number is positive
else {
var fact = 1;
for (i = 1; i <= number; i++) {
fact *= i;
}
document.write("The factorial is "+fact);
}
</script>

</body>
</html>

01

Program: to generate fibonacci series up to n terms


var number = parseInt(prompt('Enter the number of terms: '));
var n1 = 0, n2 = 1, nextTerm;
document.write('Fibonacci Series:');
for (var i = 1; i <= number; i++)
{

Client Side Scripting (Unit 1) Arrow Computer Academy


document.write(n1+" ");
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}

Program:- To check whether Number is prime or Not


<script type="text/javascript">
var n,i,flag = true;
n = parseInt(prompt("Enter the Number"));
for(i = 2; i <= n/2; i++)
if (n % i == 0)
{
flag = false;
break;
}
if (flag == true)
alert(n + " is prime");
else
alert(n + " is not prime");
</script>

Program: Sum of Digits of a Number


<script type="text/javascript">
var n= parseInt(prompt("Enter Number"));
var remainder, sum = 0;
while(n)
{
remainder = n % 10;
sum = sum + remainder;
n = Math.floor(n/10);
}
document.write(sum);
</script>

Querying and Setting Properties


A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.

Accessing JavaScript Properties


Syntax
objectName.property // emp.name
or

Client Side Scripting (Unit 1) Arrow Computer Academy


objectName["property"] // emp["name"]

Example 1
var emp = {name:"Akshay",id:17,salary:50000};
document.write("Name is "+emp.name+"<br>");
document.write("Id is "+emp.id+"<br>");
document.write("Salary is "+emp.salary+"<br>");

Example 2
var emp = {name:"Akshay",id:17,salary:50000};
document.write("Name is "+emp["name"]+"<br>");
document.write("Id is "+emp["id"]+"<br>");
document.write("Salary is "+emp["salary"]+"<br>");

JavaScript for...in Loop


The JavaScript for...in statement loops through the properties of an object.
Syntax
for (var variable in object)
{
// code to be executed
}
The block of code inside of the for...in loop will be executed once for each property.
Looping through the properties of an object:
Example
<script type="text/javascript">
var person = {fname:"Arrow", lname:"Academy", age:25};
var text ="";
for (let x in person)
{
text += person[x] + " ";
}
document.write(text);
</script>

Example Explained

The for in loop iterates over a person object

In each iteration key is assigned to variable x.

These keys are used to access the value of the key.

The value of the key is person[x]

Adding New Properties


You can add new properties to an existing object by simply giving it a value.
Assume that the person object already exists - you can then give it new properties:

Client Side Scripting (Unit 1) Arrow Computer Academy


Example :-
person.nationality = "Indian";

Program:-
<script type="text/javascript">
var person = {fname:"Arrow", lname:"Academy", age:25};
person.nationality = "Indian";
var text ="";
for (var x in person)
{
text += person[x] + " ";
}
document.write(text);
</script>

Deleting Properties
The delete keyword deletes a property from an object:
delete person.lname
or
delete person["age"];
Program:-
<script type="text/javascript">
var person = {fname:"Arrow", lname:"Academy", age:25};
delete person.lname
var text ="";
for (let x in person)
{
text += person[x] + " ";
}
document.write(text);
</script>

The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables or
functions.
The delete operator should not be used on predefined JavaScript object properties. It can crash your
application.
JavaScript Getter and Setter
In JavaScript, there are two kinds of object properties:
 Data properties
 Accessor properties

1. Data Property
Here's an example of data property that that is used to assign some data to object
var student =
{
// data property

Client Side Scripting (Unit 1) Arrow Computer Academy


firstName: “Arrow”;
};

2. Accessor Property
In JavaScript, accessor properties are methods that get or set the value of an object.
For that, we use these two keywords:
 get- to define a getter method to get the property value
 set - to define a setter method to set the property value

JavaScript Getter
In JavaScript, getter methods are used to access the properties of an object.
get keyword is used to define a getter method to get the property value

For example,
<script type="text/javascript">
var student = {
fname: "Arrow",
lname: "Academy",

// accessor property(getter)
get getName()
{
return this.fname + " "+ this.lname;
}
};

document.write("First Name is "+ student.fname+"<br>");


document.write("last Name is "+ student.lname+"<br>");

// accessing getter methods


document.write(student.getName);

// trying to access as a method


document.write(student.getName()); // error
</script>

 In the above program, a getter method getName() is created to access the property of an object.
 To create a getter method, the get keyword is used.
 And also when accessing the value, we access the value as a property.
student.getName;
 When you try to access the value as a method, an error occurs.
document.write(student.getName()); // error

JavaScript Setter
In JavaScript, setter methods are used to change the values of an object.

Client Side Scripting (Unit 1) Arrow Computer Academy


set keyword is used to define a setter method to change the property value.

For example,
<script type="text/javascript">
var student =
{
fname: "Arrow",

//accessor property(setter)
set changeName(newName)
{
this.fname = newName;
}
};

document.write(student.fname); // Arrow

// change(set) object property using a setter


student.changeName = "Akshay";

document.write(student.fname); // Akshay
</script>

In the above example, the setter method is used to change the value of an object.
To create a setter method, the set keyword is used.
As shown in the above program, the value of fname is Arrow.
Then the value is changed to Akshay.
student.changeName = “Akshay”;
Note: Setter must have exactly one formal parameter.

Client Side Scripting (Unit 1) Arrow Computer Academy

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy