Unit 1 Client Side Scripting Final
Unit 1 Client Side Scripting Final
Unit 1 Client Side Scripting Final
BCA-IV Semester
Binary system:
Transistor 0=off, 1=on; 6 billion transistors in pc,
Compiler: converts programming language to machine code and vice versa
-creates .exe file,
-Each programming language has its own compiler
Interpreter: translate language into machine code line by line
-Interpreter translates the scripting language
What is programming Language?
-A programming language is a vocabulary and set of grammatical rules for
instructing a computer or computing device to perform specific tasks.
-It is written in a high-level language
-Each programming language has its own compiler
-Programming language has both a compiler and an interpreter
Ex: Java,
What is Scripting Language?
-A scripting language is a programming
language that executes tasks within a
special run-time environment by an Example: We can write html
interpreter instead of a compiler. and php code inside scripting
-A scripting language can be a language.
programming language but a
programming language can not be a
scripting language.
Scripting Language
-Scripting language does not need a compiler, it compiles in the browser automatically.
There are many scripting languages some of which are discussed below:
Node js: It is a framework to write network applications using JavaScript.
Ruby: It is a scripting language that is great for web development.
Python: It is easy, free, and open source. It supports procedure-oriented
programming and object-oriented programming.
JavaScript: Most used Scripting language
Scripting Language
Scripting languages are often used for tasks such as:
• Automating repetitive tasks: Scripting languages can be used to automate tasks
such as file backups, data processing, and system administration tasks.
• Adding functionality to applications: Scripting languages can be used to add new
features or extend the functionality of existing applications.
• Web development: Scripting languages such as JavaScript are used extensively in
web development to add interactivity and dynamic content to web pages.
What is markup language?
-Markup language is metadata for annotating a document (i.e. webpage), which
is visually distinguishable from how the user typically sees the document. It is used
only for formatting the text, thus when the document is rendered for display, the
markup language doesn't appear.
-It is just used for the design or structure of data (Buttons, Menu)
-No logic in the scripting language
EX: HTML, XML
XML (Extensible Markup language) used for UI design in Android
Programming language vs Scripting Language
Programming Language Scripting Language
• Set of instructions to produce various • Set of instructions to combine the outputs
types of outputs to automate a certain task. with different outputs to perform a task.
• Compilation is necessary. • No need for compilation.
• Not interpreted. • Interpretation is required.
• Full-length code. • Small chunks of code.
• Self-executable, no host is required. • Dependent on some other platform, host is
required.
Programming language vs Scripting Language
Programming Language Scripting Language
• Easy learning: The user can learn to code in scripting languages quickly, not
much knowledge of web technology is required.
• Fast editing: It is highly efficient with a limited number of data structures and
variables to use.
• Interactivity: It helps in adding visualization interfaces and combinations in web
pages.
• Functionality: There are different libraries that are part of different scripting
languages.
JavaScript
Introduction: JavaScript is a
programming/Scripting
language used both on the
client-side and server-side
that allows you to make web
pages interactive.
Client side scripting
A client-side script is a program that is processed within the
client browser. These kinds of scripts are small programs that
are downloaded, compiled, and run by the browser. JavaScript is
an important client-side scripting language and is widely used in
dynamic websites. The script can be embedded within
the HTML or stored in an external file.
Server side scripting
-The term server-side scripting language refers to those that run off a web server.
Since it performs from the back-end side, the script is not visible to the visitor.
A server-side script is processed on the web server when the user requests
information. These kinds of scripts can run before a web page is loaded. They are
needed for anything that requires dynamic data, such as storing user login details. Some
common server-side languages include PHP, Python, Ruby, and Java. These execute
like programming languages on the server.
Java vs JavaScript
Java vs JavaScript
Java vs JavaScript
Why JavaScript?
-It is top used language
-jQuery: 100 lines of code can replace the short line of code
-Node.JS: Can do server work from JavaScript
-Skype is made with JavaScript
-Angular (Angular is a platform for building mobile and desktop web applications)
-React (JavaScript Library for building user interface): developed by Facebook, you
can make the website
-JavaScript is popularly used in machine learning
Why JavaScript?
Where does JavaScript code run?
-Browser: Every browser with a JavaScript engine executes
JavaScript code. Example JavaScript engine in Chrome, Mozilla, etc.
Ex: console.log(‘hello world’)
-Node: Node is a C++ program that includes Google’s v8
JavaScript engines. With this, we can run JavaScript code outside of
the browser.
Visual studio code installation
<html>
<head>
<script>…..</script>
<body>
<script>…..</script>
<body>
</html>
Example
var firstName = "ram";
var lastName = "sita";
var price =19.90;
var tax =0.20;
fullPrice = price + (price * tax);
document.write(fullPrice);
Spaces Around Operators
Always put spaces around operators ( = + - * / ), and after commas:
Example:
let x = y + z;
Code Indentation: Always use 2 spaces for the indentation of code blocks:
function toCelsius (fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Statement Rules
General rules for simple
const cars = ["Volvo", "Saab", "Fiat"]; statements:
Always end a simple statement
const person = {
with a semicolon.
firstName: “Ram",
lastName: “Bahadur",
age: 50,
eyeColor: "blue"
};
General rules for complex
(compound) statements: • Put the opening bracket at the end
of the first line.
function toCelsius(fahrenheit) { • Use one space before the opening
return (5 / 9) * (fahrenheit - 32); bracket.
}
• Put the closing bracket on a new
line, without leading spaces.
Object Rules • General rules for object definitions:
const person = { • Place the opening bracket on the same line as
firstName: "John", the object name.
lastName: "Doe", • Use a colon plus one space between each
age: 50, property and its value.
eyeColor: "blue" • Use quotes around string values, not around
}; numeric values.
-Short objects can be written compressed, • Do not add a comma after the last property-
on one line, using spaces only between value pair.
properties, like this: • Place the closing bracket on a new line,
without leading spaces.
const person = {firstName:"John",
lastName:"Doe", age:50, • Always end an object definition with a
semicolon.
eyeColor:"blue"};
Line Length < 80
• For readability, avoid lines longer
than 80 characters.
document.write("Hello Class”); • If a JavaScript statement does not
fit on one line, the best place to
break it, is after an operator or a
comma.
Naming Conventions
• Always use the same naming convention for all your code. For
example:
• Variable and function names are written as camelCase
• Global variables written in UPPERCASE (We don't, but it's quite
common)
• Constants (like PI) written in UPPERCASE
File Extensions
• HTML files should have a .html extension (.htm is allowed).
• CSS files should have a .css extension.
• JavaScript files should have a .js extension.
• File names must be all lowercase and may include underscores (_)
or dashes (-), but no additional punctuation. Follow the
convention that your project uses. Filenames’ extension must
be .js
Use Lower Case File Names
• Most web servers (Apache, Unix) are case-sensitive about file names:
• london.jpg cannot be accessed as London.jpg.
• Other web servers (Microsoft, IIS) are not case-sensitive:
• london.jpg can be accessed as London.jpg or london.jpg.
• If you use a mix of upper and lower case, you have to be extremely consistent.
• If you move from a case-insensitive to a case-sensitive server, even small errors can
break your website.
Embedding JavaScript in HTML
• The script Tag
• The script is an HTML element. Html script element is used to enclose
client-side scripts like JavaScript within an HTML document.
Syntax:
• <script>
• JavaScript statements.......
• </script>
JavaScript in HTML document
• There are two general areas in the HTML document where JavaScript can
be placed. First is between <head>......</head> section, another is a
specific location in <body>......</body> section. If you want to display the
message 'Good Morning' (through the JavaScript alert command) at the time
of page loading then you must place the script at the <head>......</head>
section. In the following examples, you will see the different locations of
<script>.....</script> tags in an HTML document.
Script in the Head
• <!DOCTYPE html> • JavaScript statements.......
• <head> • </script>
• <meta charset="utf-8" /> • </head>
• <title> Script in head section • <body>
</title> • </body>
• <script type = "text/javascript"> • </html>
Script in the Body
• <!DOCTYPE html> • JavaScript statements.......
• <head> • </script>
• <title> Script in the Body </title> • </body>
• </head> • </html>
• <body>
• <script type = "text/javascript">
Attributes in script element:
1. language
The language attribute is used to specify the scripting language and its version for
the enclosed code. In the following example, the JavaScript version is 1.2. If a specific
browser does not support the said JavaScript version, the code is ignored. If you do
not specify a language attribute, the default behavior depends on the browser version.
<script language = "JavaScript1.2">
JavaScript statements.......
</script>
Attributes in script element
2. src
This attribute specifies the location of an external script. This attribute is useful
for sharing functions among many different pages. Note that external JavaScript
files contain only JavaScript statements and files must have the extension .js.
Syntax:
<script src = "common.js">
JavaScript statements.......
</script>
Attributes in script element:
4. type
This attribute specifies the scripting language. The scripting language is specified as a
content type (e.g., "text/JavaScript" ). The attribute is supported by all modern
browsers.
Syntax:
<script type="text/javascript">
JavaScript statements.......
</script>
JavaScript Variables
Variables are containers for storing data (values).
Using var
Using let
Using Const
Example
Block Scope
• ES6 introduced two important new
JavaScript keywords: let and const.
{ • These two keywords provide Block
let x = 2; Scope in JavaScript.
} • Variables declared inside a { } block
// x can NOT be used here cannot be accessed from outside the
block:
Block • Variables declared with the var keyword
can NOT have block scope.
{
var x = 2; • Variables declared inside a { } block can
} be accessed from outside the block.
// x CAN be used here
JavaScript Const
2. X^7+Y^3+Z*3
JavaScript Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
JavaScript String Operators
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
|| logical or
! logical not
JavaScript Bitwise Operators
• Bit operators work on 32 bits numbers.
• Any numeric operand in the operation is converted into a 32 bit number.
The result is converted back to a JavaScript number.
JavaScript Bitwise Operators
Operator Description Example Same as Result
}
The else if Statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
The else if Statement (example)
let time = 30;
if (time < 10) {
document.write(‘Good morning’);
} else if (time < 20) {
document.write(‘Good day’);
} else {
document.write(‘Good evening’);
}
Switch
The switch statement is used to perform How switch works:
different actions based on different • The switch expression is evaluated once.
conditions. • The value of the expression is compared with the values
of each case.
switch(expression) { • If there is a match, the associated block of code is
case x: executed.
// code block • If there is no match, the default code block is executed.
break; • When JavaScript reaches a break keyword, it breaks out
of the switch block.
case y:
• This will stop the execution inside the switch block.
// code block • It is not necessary to break the last case in a switch
break; block. The block breaks (ends) there anyway.
default:
// code block
}
<script type="text/javascript">
Switch
var grade='A’;
switch (grade) {
case 'A': document.write("Good job<br/>");
break;
case 'B': document.write("Pretty good<br/>");
break;
default: document.write("Unknown grade<br/>")
}
document.write("Exiting switch block");
</script>
Ternary Operator
Ternary Operator: The “Question mark” or “conditional” operator in
JavaScript is a ternary operator that has three operands. It is the simplified
operator of if/else.
Syntax:
condition ? value if true : value if false
Example:
let a = 5;
document.write(a<18? "not drive" : "drive");
Practice
1. Use logical operator to find whether the age of person lies between 25
and 50.
2. Demonstrate the use of switch case in JS
3. Write the js program to check given number is divisible by 2 and 3 or
not?
4. Print you are pass or fail based on pass mark 40 using ternary operator
Loops:
A loop statement is a series of steps or sequence of statements executed
repeatedly zero or more times satisfying the given condition is satisfied.
JavaScript supports different kinds of loops:
Example 1 Example 2
class user { class user {
{ constructor(name, age)
let john = new user() {
-user is class this.name=name;
-john is object of user class this.age=age;
Whenever we create class and object of the class, the }
object automatically called by class. However, we use
constructor () method which call the object. let user1 = new user(hari’, 10);
Class: Prototype Method
class hello { let b = new hello();
message(){ a.message();
document.write('hello world'); a.sorry();
} b.sorry();
sorry(){
document.write('I am busy');
}
}
let a = new hello();
Class: Example
class rectangle{ let rectangle1 = new rectangle (2, 3);
constructor(_width, _height){ let rectangle2 = new rectangle (5,6);
this.width=_width; document.write('area of rectangle 1 is '
this.height=_height +rectangle1.getarea() + '<br>');
Function Objects
-A function is a block of code to performs a particular task. -Real time entity having property and method
-Function can create using function keyword followed by -Object can create in different ways (using literal, using new
function name keyword, using constructor function
-You can access object properties in two ways (using .
-A function is executed when invokes it (calls it). operator and using [])
-The () Operator Invokes the Function Example: objectName.propertyName or objectName["propertyName"]
-Variables declared within a function, become LOCAL to the -Objects can also have methods.
function.
-this keyword is used to represents the object that is executing
-We can pass parameters within the function the current function.
-Define the code once, and use it many times.
Let’s Summarize
Method Class
-methods are actions that can be -Class is blueprint of object
performed on objects. -Class is used to create one or more objects
-You access an object method with -Use the keyword class to create a class.
the syntax objectName.methodName() -Always add a method called constructor()
-constructor is where you can initialize the
properties of an instance.
Practice Set
1. Write JS program to calculate area of rectangle
2. Write JS program to calculate volume of cylinder (formula = PI* R*R)
3. Write JS program to Convert temperatures to and from Celsius, Fahrenheit
Formula: Fahrenheit to Celsius : (°F − 32) ÷ 1.8 = °C
Celsius to Fahrenheit : (°C × 1.8) + 32 = °F
4. Write JS program to print maximum and minimum number from array
Built in objects
-Array Object
-String objects
-Date Objects
-Math
Array Object
-An array is a special variable, which can hold more than one value:
Syntax:
let a = [10, 3, 4, 1, 6, 'BCA’];
Why array?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Creating array
const a = [10, 3, 4, 1, 6, 'BCA’];
You can also create an array, and then provide the elements:
const A = [];
A[0]= 10;
A[1]= “Ram";
A[2]= “Mohan";
You can also create an array, and then provide the elements:
const A = [];
A[0]= 10;
A[1]= “Ram";
A[2]= “Mohan";
Example:
Let a = “hello”;
Or
Let a = ‘hello’;
String
let a = "hello"; //string can warp in single and double quote
The backslash (\) escape character turns special characters into string characters:
Escape sequence character
Code Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash
let text = "hello guys "Ramesh" is absent today" //this is not possible to write inner
quotation
let text1 = "hello guys \”Ramesh\” is absent today"; //we can use \' for single
quotation
document.write(text);
document.write(text1);
Escape sequence character
let text3 = "hello guys \"Ramesh\" is absent today"; /we can use (\’ )for single
quotation and (\\”) for double quotation
document.write(text3);
• You can use different Date constructors to create date object. It provides
methods to get and set day, month, year, hour, minute and seconds.
Creating Date Object
• Date objects are created with the New Date () constructor.
There are 9 ways to create a new date object:
new Date()
new Date(date string)
new Date(year, month)
new Date(year, month, day)
Creating Date Object
new Date(year, month, day, hours)
new Date(year, month, day, hours, minutes)
new Date(year, month, day, hours, minutes, seconds)
new Date(year, month, day, hours, minutes, seconds, ms)
new Date(milliseconds)
Date object methods
Date Object
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
change onchange When the user modifies or changes the value of a form element
Window/Document events
Event Performed Event Handler Description
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser unloads it
resize onresize When the visitor resizes the window of the browser
Forms and Form
Validations
-Forms are something where you give input.
-Forms has validation
-HTML form validation can be done by JavaScript.
-Data validation is the process of ensuring that user input
is clean, correct, and useful.
-Validation can be defined by many different methods, and
deployed in many different ways.
Example:
A Simple HTML form
<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Javascript function to perform operation in form:
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false; //During form submission, if entry is unfilled, return false is used to prevent the submission of form.
}}
document.forms is forms read-only property of the Document interface returns an HTMLCollection listing all the
<form> elements contained in the document.
Cookie
When you browser website,
you may see this types screen
requesting to accept cookie.
Cookie
-Cookie is formally called http cookie, it let you store user information in web pages.
What are Cookies?
-Cookies are piece of data from specific website, that stored in small text files, on user’s computer while
they are browsing the web.
Why cookie?
-When a web server has sent a web page to a browser, the connection is shut down, and the server forgets
everything about the user.
-Cookies were invented to solve the problem "how to remember information about the user":
-When a user visits a web page, his/her name can be stored in a cookie.
-Next time the user visits the page, the cookie "remembers" his/her name.
Cookie
alert(document.cookie); //can view cookie of specific page
document.cookie = "name = ABC";
document.cookie = "age = 30";
document.cookie = "name = DEF"; //if we set ckkine of same name it will overwrite
alert(document.cookie);
Cookie
assign cookie using user input
let key = prompt("enter your cookie name");
let value = prompt("enter your cookie value"); //when we enter some symbol it does
not work
document.cookie = `${key} = ${value}`
alert(document.cookie);
Cookie
Modifier Description
g Perform a global match (find all matches rather than stopping after the
first match)
i Perform case-insensitive matching
m Perform multiline matching
Example: Use of g
-If we write /is/g, here “g” performs a global match that will find all matches
rather than stopping after the first match.
<script>
let text = "Is this all there is?";
let pattern = /is/g;
let result = text.match(pattern);
document.write(‘result’);
</script>
Example: Use of i
let text = "Hello CLASS";
let pattern = /class/i;
let result = text.match(pattern);
document.write(result);
Here we search for class (lowercase) but in the text, there is CLASS
(uppercase). But it finds the class because we are using i to search case
insensitive.
Regular Expressions Methods
Regular expressions are used with the methods like test() and exec() and with the
string methods match() , replace() , search() , and split()
1. exec() : It searches a string for a specified pattern, and returns the found text as an
object. If no match is found, it returns an empty (null) object.
Syntax: RegExpObject.exec(string);
Example:
let text = "Is this all there is?";
let obj = /this/.exec(text);
document.write('found ' + obj + " in the text " + text);
Regular Expressions Methods
2. test()
Syntax: RegExpObject.test(string)
This method tests for a match in a string. If matches it returns true if not match it
returns false.
Example:
let text = "Is this all there is?";
let obj = /this/.test(text);
document.write(obj);
Regular Expressions Methods
3. search()
searches a string for a value and returns the position of the first match. It
returns the position of the match, or -1 if the search fails
let text = "Mr. Blue has a blue house"
let position = text.search("Blue");
document.write(position);
O/p: 4 (B is in 4th position)
Regular Expressions Methods
5. split()
This method uses a regular expression or a fixed string to break a string into an array
of substrings.
string.split(separator, limit)
Example:
let text = "How are you doing today?";
const myArray = text.split(" "); //we can also use split parameter (“ “, 2);
document.write(myArray);
Regular Expressions Methods
6. replace()
This method will executes a search for a match in a string, and replaces the
matched substring with a replacement substring.
Syntax: string.replace(searchValue, newValue);
Example:
let text = "Hello semester4?";
document.write(text.replace("semester4", "semester6"));
Regular Expressions Patterns
Brackets are used to find a range of characters:
[abc] //Find any of the characters between the brackets
let text = "How are you doing today";
let result = text.match(/[d]/g);
document.write(result);
Regular Expressions Patterns
[^abc] //Find any of the characters not between the brackets
let text = "How 23 are you doing today";
let result = text.match(/[^a]/ig);
let result = text.match(/[^A-Z]/ig);
let result = text.match(/[^a-z]/ig);
let result = text.match(/[^A-z]/ig);
document.write(result);
Regular Expressions Patterns
[0-9] //Find any of the digits between the brackets
let text = "0123456789";
let result = text.match(/[2-6]/g);
document.write(result);
Regular Expressions Patterns
[^0-9] //is used to find any character that is NOT a digit.
1. Generate regular expressions to test if the first letter is a capital letter in the given string
^ - The caret symbol at the beginning of the pattern represents the start of the string. It ensures that
the pattern should match the first character.
1. Generate regular expressions to validate the phone Number with the following condition.
(Start with 9, the only number allowed, only 10 digits allowed)