Basics of Javascript
Basics of Javascript
Unit 1
Course Outcome: Create interactive web pages using program flow control structure.
Unit Outcome:
2) Develop javascript to implement the switch-case statement for the given problem.
3) Develop javascript to implement loop for solving the given iterative problem.
5) Develop program using basic features of javascript to solve the given problem.
1
Client-Side Scripting (Semester-V)
Introduction:
The scripts can be written in two forms, at the server end (back end) or at the client end
(server end). The main difference between server-side scripting and client-side scripting
is that the server-side scripting involves server for its processing. On the other hand,
client-side scripting requires browsers to run the scripts on the client machine but does
not interact with the server while processing the client-side scripts.
Source: https://techdifferences.com/difference-between-server-side-scripting-and-client-
side-scripting.html
Server-side scripting is a technique of programming for producing the code which can
run software on the server side, in simple words any scripting or programming that can
run on the web server is known as server-side scripting.
The operations like customization of a website, dynamic change in the website content,
response generation to the user’s queries, accessing the database, and so on are
performed at the server end.
The server-side scripting constructs a communication link between a server and a client
(user). Earlier the server-side scripting is implemented by the CGI (Common Gateway
Interface) scripts. The CGI was devised to execute the scripts from programming
languages such as C++ or Perl on the websites.
2
Client-Side Scripting (Semester-V)
The server-side involves four parts: server, database, API’s and back-end web software
developed by the server-side scripting language. When a browser sends a request to the
server for a webpage consisting of server-side scripting, the web server processes the
script prior to serving the page to the browser. Here the processing of a script could
include extracting information from a database, making simple calculations, or choosing
the appropriate content that is to be displayed in the client end. The script is being
processed and the output is sent to the browser. The web server abstracts the scripts from
the end user until serving the content, which makes the data and source code more
secure.
The Programming languages for server-side programming are:
1) PHP
2) C++
3) Java and JSP
4) Python
5) Ruby
Client-side scripting is performed to generate a code that can run on the client end
(browser) without needing the server-side processing.
Basically, these types of scripts are placed inside an HTML document. The client-side
scripting can be used to examine the user’s form for the errors before submitting it and
for changing the content according to the user input.
In Client-side scripting, the web requires three elements for its functioning which are,
client, database and server.
The effective client-side scripting can significantly reduce the server load. It is designed
to run as a scripting language utilizing a web browser as a host program. For example,
when a user makes a request via browser for a webpage to the server, it just sent the
HTML and CSS as plain text, and the browser interprets and renders the web content in
the client end.
3
Client-Side Scripting (Semester-V)
BASIS FOR
SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING
COMPARISON
Basic Works in the back end which Works at the front end and script
could not be visible at the client are visible among the users.
end.
Affect Could effectively customize the Can reduce the load to the
web pages and provide dynamic server.
websites.
Using HTML, we can only design a web page but you cannot run any logic on web
browser like addition of two numbers, check any condition, looping statements (for,
while), decision making statement (if-else) at client side. All these are not possible using
HTML So for perform all these tasks at client side you need to use JavaScript.
There are too many web applications running on the web that are using JavaScript
technology like Gmail, Facebook, twitter, google map, YouTube etc.
4
Client-Side Scripting (Semester-V)
JavaScript is a client-side technology, it is mainly used for gives client-side validation, but
it has lot of features which are given below;
• JavaScript is an object-based scripting language.
• Giving the user more control over the browser.
• It Handling dates and time.
• It Detecting the user's browser and OS,
• It is light weighted.
• JavaScript is a scripting language and it is not java.
• JavaScript is interpreter-based scripting language.
• JavaScript is case sensitive.
• JavaScript is object-based language as it provides predefined objects.
• Every statement in JavaScript must be terminated with semicolon (;).
• Most of the JavaScript control statements syntax is same as syntax of control
statements in C language.
• An important part of JavaScript is the ability to create new functions within scripts.
Declare a function in JavaScript using function keyword.
• The concept of class and OOPs has been more refined. Also, in JavaScript, two
important principles with OOP in JavaScript are Object Creation patterns
5
Client-Side Scripting (Semester-V)
Advantages of JavaScript:
• Speed: Client-side JavaScript is very fast because it can be run immediately within
the client-side browser. Unless outside resources are required, JavaScript is
unhindered by network calls to a backend server.
• 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.
6
Client-Side Scripting (Semester-V)
Disadvantages of JavaScript:
• Security: As the code executes the user’s computer, in some cases it can be
exploited for malicious purpose.
• Javascript done not read and write the files.
• Javascript can not be used for networking applications.
• Javascript does not have multi-threading and multi-processing capabilities.
• Javascript does not support overloading and overriding.
Object Name:
Each object is uniquely identified by a name or ID.
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
7
Client-Side Scripting (Semester-V)
var person = {
firstName: “Hhh",
lastName: “Bbb",
age: 10
};
In above example, person is an object and firstName , lastName and age are three
properties.
“Hhh” , “Bbb” and 10 these are values associated with properties.
Code:
<html>
<body>
<script>
emp={id:"VP-179",name:"Aaa Bbb",salary:50000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output: VP-179 Aaa Bbb 50000
B. Define and create a single object, with the keyword “new” OR by creating instance
of Object
new keyword is used to create object.
Syntax: var objectname=new Object();
Example:
var person = new Object();
person.firstName = “Hhh";
person.age = 10;
Code:
<html>
<body>
<script>
var emp=new Object();
8
Client-Side Scripting (Semester-V)
emp.id="VP-179";
emp.name="Aaa ";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
Output: VP-179 Aaa 50000
C. Define an object constructor, and then create objects of the constructed type.
Code:
<html>
<body>
<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
9
Client-Side Scripting (Semester-V)
}
e=new emp("VP-179","Aaa ",50000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
Output: VP-179 Aaa 50000
Types of Objects:
• Native Objects/ Built-in Objects: are those objects supplied by JavaScript.
Examples of these are Math, Date, String, Number, Array, Image, etc.
1) Math:
Math Properties
Math Description
Property
SQRT2 Returns square root of 2.
PI Returns Π value.
E Returns Euler's Constant.
LN2 Returns natural logarithm of 2.
LN10 Returns natural logarithm of 10.
Code:
<html>
<head>
<title>JavaScript Math Object Properties</title>
</head>
<body>
<script type="text/javascript">
var value1 = Math.E;
document.write("E Value is :" + value1 + "<br>");
var value3 = Math.LN10;
10
Client-Side Scripting (Semester-V)
11
Client-Side Scripting (Semester-V)
Output:
ABS Value: 20
TAN Value : -3.380515006246586
2) 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:
Date Methods Description
12
Client-Side Scripting (Semester-V)
Code:
<html>
<body>
<h2>Date Methods</h2>
<script type="text/javascript">
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>
13
Client-Side Scripting (Semester-V)
3) 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);
String Properties:
String properties Description
14
Client-Side Scripting (Semester-V)
<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>
</body> </html>
Output:
Char At: v
CharCode At: 65
Index of: 10
Lower Case: a javascript
Upper Case: A JAVASCRIPT
• Host Objects: are objects that are supplied to JavaScript by the browser environment.
Examples of these are window, document, forms, etc.
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.
Window Methods:
Window Description
methods
15
Client-Side Scripting (Semester-V)
Output:
• User-Defined Objects: are those that are defined by you, the programmer.
Property:
▪ Properties are the values associated with a JavaScript object.
▪ A JavaScript object is a collection of unordered properties.
16
Client-Side Scripting (Semester-V)
▪ 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"]
objectName[expression] // x = "age"; person[x]
Dot Operator:
The properties and methods associated with any object can be accessed by using
dot(.) Operator.
Example, emp.id or op.add();
Dot operator is used to how to interact with objects, methods, events and
properties.
Dot operator is also used to add new property.
Example, emp.designation=“Lecturer”;
Code:
<html>
<body>
<script>
var person =
{
firstname:"Hhh",
age:10
};
person.std = "Fifth"; //adding new property as “std”
document.write(person.firstname+" "+"is in "+person.std+" standard"); //Accessing
properties with dot
</script>
</body> </html>
Output:
Hhh is in Fifth standard
Methods:
JavaScript methods are actions that can be performed on objects.
A JavaScript function is a block of code designed to perform a particular task.
17
Client-Side Scripting (Semester-V)
18
Client-Side Scripting (Semester-V)
lastname:"Bbb",
Fullname:function() // define a function as a property
{
return this.firstname+" "+this.lastname;
}
};
document.write("Person Detail is="+person.Fullname());
</script>
Output:
Person Detail is=Hhh Bbb
Main Event:
Event Description
Code:
<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello IF5I students");
}
</script>
</head>
<body>
<center>
<p><h1>Welcome to Client-side scripting</h1></p>
<form>
<input type="button" value="click" onclick ="msg()"/> // onclick event
</form>
</body>
</html>
Output:
20
Client-Side Scripting (Semester-V)
The getElementById() method returns the elements that has given ID which is passed to
the function.
This function is widely used in web designing to change the value of any particular
element or get a particular element.
Syntax: document. getElementById(element_id) ;
Parameter: This function accepts single parameter element_id which is used to hold the
ID of element.
Return Value: It returns the object of given ID. If no element exists with given ID then it
returns null.
Code:
<html>
<body>
<p id="demo">Click the button to change the color of this paragraph.</p>
<button onclick="myFunction()">change color</button>
<script>
function myFunction()
{
var x = document.getElementById("demo");
21
Client-Side Scripting (Semester-V)
x.style.color = "red";
}
</script>
</body>
</html>
Output:
We can say that variable is a container that can be used to store value and you need
to declare a variable before using it.
In JavaScript, the var keyword is used to declare a variable. Also, starting from ES6 we can
also declare variables using the let keyword.
JavaScript Syntax for Declaring a Variable
Following is the syntax for declaring a variable and assigning values to it.
var varible-name;
or
let varible-name;
22
Client-Side Scripting (Semester-V)
We can also define a variable without using the semicolon too. Also, when we have to
define multiple variables, we can do it like this:
var x,y,z;
or
var x,y,z
Now let's take a simple example where we will declare a variable and then assign it a
value.
var emp_name;
var emp_name=”dhavan”;
JavaScript Local variable is a variable that is declared inside a code block or a function
body or inside a loop body and it has scope within the code block or the function. In
simple words, the scope of a local variable is between the opening and closing curly
braces { }, when declared and defined inside a code block or a function body.
Starting from ES6 it is recommended to use the let keyword while declaring local
variables.
A JavaScript local variable is declared inside block or function.
For example:
<script>
function abc()
{
var x=10; //x is a local variable
23
Client-Side Scripting (Semester-V)
}
</script>
A variable i.e. declared outside the function or declared with window object is known
as global variable.
Code:
<html>
<body>
<script>
var data=200; //gloabal variable
function a()
{
document.write(data);
}
function b()
{
document.write(data);
}
a(); //calling JavaScript function
b();
</script>
</body>
</html>
Output:
200 200
24
Client-Side Scripting (Semester-V)
25
Client-Side Scripting (Semester-V)
In JavaScript, let is a keyword which is used to declare a local variable with block scope.
Unlike var keyword which declares global scope variables, with ECMAScript2016(ES6)
the let keyword was introduced to define local scope variables as defining all the variables
in global scope leads to a lot of problems while writing large JavaScript applications.
It allows you to declare limited scope variables that cannot be accessible outside of the
scope.
Let's take an example to understand the need of let keyword when we already
had var keyword to create variables in JavaScript. Suppose you are writing a big JavaScript
code which involves multiple loops, functions, and variables, as usual in all the loops you
used the same variable name for the counter which is i, and you used the var keyword to
define the variable i, now what will happen is, the variable i will carry on its changed value
throughout the whole script as it is a global variable and if you forget to re-initialize it to
zero anywhere, it will cause an error and your code will break. And you will have to put in
extra efforts to look for the error.
Whereas, if you define the counter variable i using the let keyword, its scope will be
limited to the loop only and when the first loop will end so will the counter variable. This
way, using let keyword makes more sense because we use very few global variables and
many local variables in general programming practice.
let does not create properties of the window object when declared globally.
The syntax for using the let keyword for defining a variable is the same as that of
the var keyword.
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN];
As shown in the syntax above, yes, we can use a single let keyword to define multiple
variables, but this is not new, we can do so using the var keyword too.
Let's see a few examples to see how this let keyword is used and how it works.
Use let inside a code block:
JavaScript variable declared inside a block { } cannot be accessed from outside the block,
if we have defined the variable using the let keyword. See the below example:
{
let x = 2;
}
alert(x) // not accessible
26
Client-Side Scripting (Semester-V)
Output:
{
let x = 2;
alert(x) // accessible
}
Output:
let i = 5;
for(let i = 0; i < 10; i++) {
// code
}
alert(i); // print 5
Output:
5
As you can see in the output it shows 5, even though the loop incremented the value
of i variable up to 10, that is because of the scope of the local variable i in the for loop
ending with the loop itself, hence it is not accessible outside the loop.
function show()
{
27
Client-Side Scripting (Semester-V)
{
let amount = 2500; // block Scope
var withdraw = 2000; // global scope
}
document.write(withdraw) // accessible
document.write(amount) // not accessible
Output:
2000
Uncaught ReferenceError: amount is not defined
JavaScript const keyword is used to define constant values that cannot changed once a
value is set. The value of a constant can't be changed through reassignment, and it can't
be redeclared.
The scope of const is block-scoped it means it cannot be accessed from outside of block.
In case of scope, it is much like variables defined using the let statement.
Constants can be either global or local to the block in which it is declared. Global constants
do not become properties of the window object, unlike var variables.
Syntax
28
Client-Side Scripting (Semester-V)
We don't have to use var or let keyword while using the const keyword. Also, we
can define a list or a simple value or a string etc as a constant.
Lets understand, how to create constant in JavaScript program. See the below example:
{
const Pi = 3.14;
alert(Pi);
Output:
3.14
Let's try another example where we will try changing the value of the constant and see if
we allowed to reassign value or not.
{
const Pi = 3.14;
alert(Pi);
// Reassign value
Pi = 3.143;
alert(Pi);
}
Output:
3.14
Uncaught TypeError: Assignment to constant variable.
The scope of the variable defined using const keyword is same as that of a variable
declared using the let keyword. So, constant declared inside a block will not accessible
outside of that block. Let's take an example and see:
{
const Pi = 3.14;
alert(Pi);
}
// outside block
alert(Pi); // error
Output:
3.14
Uncaught ReferenceError: Pi is not defined
29
Client-Side Scripting (Semester-V)
Data Types
• JavaScript provides different data types to hold different types of values.
• There are two types of data types in JavaScript:
o Primitive data type
o Non-primitive (reference) data type/ Composit Data
Types
• JavaScript is a dynamic type language; means you don't need to specify type of
the variable.
• 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=“Info Technology”//holding string
30
Client-Side Scripting (Semester-V)
✓ The undefined data type can only have one value-the special value “undefined”.
✓ If a variable has been declared, but has not been assigned a value, has the
value ”undefined”.
✓ Example,
var a;
var b = “Welcome”;
alert(a) // Output: undefined
alert(b) // Output: Welcome
31
Client-Side Scripting (Semester-V)
✓ An array is a type of object used for storing multiple values in single variable.
✓ Each value (also called an element) in an array has a numeric position, known as
its index, and it may contain data of any data type-numbers, strings, Booleans,
functions, objects, and even other arrays.
✓ The array index starts from 0, so that the first array element is arr [0].
✓ The simplest way to create an array is by specifying the array elements as a
comma-separated list enclosed by square brackets, as shown in the example
below:
✓ var cities = ["London", "Paris", "New York"];
✓ alert(cities[2]); // Output: New York
✓ var a = ["London", 500, ”aa56”, 5.6];
Code:
<html>
<body>
<h1>JavaScript Array</h1>
32
Client-Side Scripting (Semester-V)
<script>
var stringArray = ["one", "two", "three"];
var mixedArray = [1, "two", "three", 4];
document.write(stringArray+"<br>"); JavaScript Array
document.write( mixedArray); one,two,three
</script> 1,two,three,4
</body>
</html>
Output:
Values/Literals
They are types that can be assigned a single literal value such as the number 5.7, or
a string of characters such as "hello".
Types of Literals:
• Array Literal
• Integer Literal
• Floating number Literal
• Boolean Literal (include True and False)
• Object Literal
• String Literal
Array Literal:
• 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.
• Creating an empty array :
var tv = [ ];
Creating an array with four elements.
var tv = [“LG", “Samsung", “Sony", “Panasonic"]
✓ Comma in array literals:
• In the following example, the length of the array is four, and tv[0] and tv[2] are
undefined.
• var tv = [ , “Samsung“, , “Panasonic"]
• This array has one empty element in the middle and two elements with values.
33
Client-Side Scripting (Semester-V)
Integer Literal:
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)
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, -20, 12345
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: 7b, -14, 3039
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: 0173, -24, 30071
34
Client-Side Scripting (Semester-V)
Object Literal:
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:
var userObject = { }
String Literal:
• JavaScript has its own way to deal with 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 = "w3resource.com"
string1 = 'w3resource.com’
➢ string1 = "1000“
• In addition to ordinary characters, you can include special characters in strings, as
shown in the following.
➢ string1 = "First line. \n Second line."
character Description
\’ Single quote
\” Double quote
\\ Backslash
35
Client-Side Scripting (Semester-V)
\b Backspace
\f Form Feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
Comments in JavaScript:
36
Client-Side Scripting (Semester-V)
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
+ 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++;
-- Decrement Now a = 11
var a=10; a--;
Now a = 9
Code:
<html>
<body>
<script type = "text/javascript">
var a = 33;
var b = 10;
var c = "Test";
document.write("a + b = ");
result = a + b;
document.write(result+"<br>");
37
Client-Side Scripting (Semester-V)
document.write("a - b = ");
result = a - b;
document.write(result+"<br>");
document.write("a / b = ");
result = a / b;
document.write(result+"<br>");
document.write("a % b = ");
result = a % b;
document.write(result+"<br>");
document.write("a + b + c = ");
result = a + b + c;
document.write(result+"<br>");
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result+"<br>");
b = --b;
document.write("--b = ");
result = --b;
document.write(result+"<br>");
</script>
</body>
</html>
Output:
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8 38
Client-Side Scripting (Semester-V)
Code:
<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = 20;
39
Client-Side Scripting (Semester-V)
| Bitwise OR (10==20 |
20==33) = false
40
Client-Side Scripting (Semester-V)
Code:
<html>
<body>
<script type="text/javascript">
41
Client-Side Scripting (Semester-V)
Output:
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
4) Logical Operator:
Code:
<html>
<body>
<script type = "text/javascript">
var a = true;
var b = false;
42
Client-Side Scripting (Semester-V)
document.write(result+"<br>");
43
Client-Side Scripting (Semester-V)
5) Assignment Operator:
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
Code:
<html>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
44
Client-Side Scripting (Semester-V)
Output:
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
45
Client-Side Scripting (Semester-V)
6) Special Operator:
Operator Description
<html>
<body>
<script type = "text/javascript">
var a = 10;
var b = "Information";
var c= function(x)
{
return x*x;
}
46
Client-Side Scripting (Semester-V)
</script>
</body>
</html>
Output:
number
string
function
16
Operator precedence determines the order in which operators are evaluated. Operators
with higher precedence are evaluated first. For example, the expression (3+4*5),
returns 23, because of multiplication operator(*) having higher precedence than
addition(+). Thus * must be evaluated first.
Operator associativity determines the order in which operators of the same precedence
are processed. For example, assignment operators are right-associative, so you can
write a=b=5, and with this statement, a and b are assigned the value 5.
The below table shows the precedence and associativity of operators. In this table,
precedence is from bottom to top i.e items at the bottom having low precedence and
precedence increases as we move to the top of the table.
47
Client-Side Scripting (Semester-V)
. left-to-right
member
[]
increment ++
decrement --
logical-not ! right-to-left
unary + + right-to-left
48
Client-Side Scripting (Semester-V)
in in left to right
49
Client-Side Scripting (Semester-V)
Expression:
50
Client-Side Scripting (Semester-V)
Since expressions produce values, they can appear anywhere in a program where
JavaScript expects a value such as the arguments of a function invocation.
Types of Expression:
1. Primary Expression:
Primary expressions refer to stand alone expressions such as literal values, certain
keywords and variable values.
'hello world'; // A string literal
23; // A numeric literal
true; // Boolean value true
sum; // Value of variable sum
this; // A keyword that evaluates to the current object.
Object and array initializers are expressions whose value is a newly created object
or array.
Object initializer expressions uses curly brackets, and each subexpression is
prefixed with a property name and a colon.
Example, var emp={ name:”Aaa”, branch:“IF”};
OR
var person={ };
person.name=“Aaa”;
person.branch=“IF”;
An array initializer is a comma-separated list of expressions surrounded with a
square bracket.
Example, var tv=[“LG”, ”Samsung”];
Example:
emp.firstName;
emp[lastName];
51
Client-Side Scripting (Semester-V)
5. Invocation Expression
Example,
52
Client-Side Scripting (Semester-V)
{ return a + b; }
};alert(obj.add(4,5));delete obj.add;alert(obj.add(9,5)); </script>
1) if statement:
Syntax:
if (condition)
{
//block of code to be executed if the condition is
true
}
Example:
<html>
<body>
<script>
if (new Date().getHours() < 18)
{
document.write("Good day!");
}
</script>
</body>
</html> 53
Client-Side Scripting (Semester-V)
54
Client-Side Scripting (Semester-V)
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
}
Example:
<html>
<body>
<script>
if (new Date().getHours() < 18)
{
document.write("Good day!");
}
else
{
document.write("Good Evening!");
}
</script>
</body>
</html>
Use else if statement to specify a new condition if the first condition is false.
55
Client-Side Scripting (Semester-V)
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
}
Example:
<html>
<body>
<script>
var greeting;
var time = new Date().getHours();
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
document.write(greeting);
</script>
</body>
</html>
56
Client-Side Scripting (Semester-V)
switch(expression)
{
case x: This is how it works:
// code block
• The switch expression is evaluated once.
break;
• The value of the expression is compared with the values of
case y:
each case.
// code block
• If there is a match, the associated block of code is executed.
break;
• If there is no match, the default code block is executed.
default:
// code block
}
Example:
<html>
<body>
<script>
var day;
switch (new Date().getDay())
{
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
57
Client-Side Scripting (Semester-V)
break;
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.write("Today is " + day);
</script>
</body>
</html>
default keyword:
If today is neither Saturday (6) nor Sunday (0), write a default message.
Example:
{
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
Example:
<html>
58
Client-Side Scripting (Semester-V)
<body>
<script>
// program for a simple calculator
var result;
switch(operator)
{
case '+':
result = number1 + number2;
document.write(`${number1} + ${number2} = ${result}`);
break;
case '-':
result = number1 - number2;
document.write(`${number1} - ${number2} = ${result}`);
break;
case '*':
result = number1 * number2;
document.write(`${number1} * ${number2} = ${result}`);
break;
case '/':
result = number1 / number2;
document.write(`${number1} / ${number2} = ${result}`);
break;
59
Client-Side Scripting (Semester-V)
default:
document.write('Invalid operator');
break;
}
</script>
</body>
</html>
Output:
60
Client-Side Scripting (Semester-V)
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1) 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:
Example:
<script>
for (i=0; i<=10; i=i+2)
{
document.write(i + "<br/>")
}
</script>
2) do while Loop
61
Client-Side Scripting (Semester-V)
before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
Syntax:
do
{
code to be executed
}
while (condition);
Example:
<script>
var i=21;
do{
document.write(i +"<br/>");
i++;
}while (i<=25);
</script>
3) while loop
The JavaScript while loop loops through a block of code as long as a specified
condition is true.
Example:
<script>
var i=11;
while (i<=20)
{
document.write(i + "<br/>");
62
Client-Side Scripting (Semester-V)
i++;
}
</script>
4) for-in loop
The block of code inside the loop will be executed once for each property.
Syntax:
Example:
63
Client-Side Scripting (Semester-V)
In while loop, first it checks the condition In Do – While loop, first it executes the
and then executes the program. program and then checks the condition.
The condition will come before the body. The condition will come after the body.
If the condition is false, then it terminates It runs at least once, even though the
the loop. conditional is false.
break statement
break statement breaks the loop and continues executing the code after the loop.
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:
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 5
The number is 6
65
Client-Side Scripting (Semester-V)
To create or set a property, use a dot or square brackets as you would to query the
property, but put them on the left-hand side of an assignment expression:
Example,
book.price=250; //create or set a property of price
book[“main title”]=“JavaScript” //set the “main title” property
Deleting properties:
<html>
<body>
<script>
var a={name:"Priti",age:35};
document.write(a.name+" "+a.age+"<br>");
delete a.age; //delete property
document.write(a.name+" "+a.age);
</script>
</body>
</html>
Output:
Priti 35
Priti undefined
66
Client-Side Scripting (Semester-V)
67
Client-Side Scripting (Semester-V)
Code: Getters and setters allow you to get and set properties via methods.
<script>
var person = {
firstName: 'Chirag',
lastName: 'Shetty',
get fullName()
{
return this.firstName + ' ' + this.lastName;
},
set fullName (name) Output:
{
var words = name.split(' '); Chirag Shetty
this.firstName = words[0]; before using set fullname()
this.firstName = words[0].toUpperCase(); YASH Desai
this.lastName = words[1];
}
}
document.write(person.fullName); //Getters and setters allow you to get and set
properties via methods.
document.write("<br>"+"before using set fullname()"+"<br>");
person.fullName = 'Yash Desai'; //Set a property using set
document.writeln(person.firstName); // Yash
document.write(person.lastName); // Desai
</script>
68