Unit 1 Client Side Scripting Final

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

Scripting Language

BCA-IV Semester

Er. Santosh Bhandari


What we do?
• We do a little bit of theory
• Lab
• Discuss problems that come on the way:
• We make a group, we learn and share our experiences
• Presentation by students
• Group work
• We develop website using CMS
Why this subject?

Scripting languages are used in many areas:


• Scripting languages are used in web applications. It is used on the server side as well
as the client side. Server-side scripting languages are: JavaScript, PHP, Perl, etc. and
client-side scripting languages are: JavaScript, AJAX, jQuery, etc.
• Scripting languages are used in system administration. For example Shell, Perl,
Python scripts, etc.
• It is used in Games applications and Multimedia.
• It is used to create plugins and extensions for existing applications.
Fundamental

Let’s learn some


fundamental
What is language?

Language: The principal method of human


communication, consisting of words used in a structured
and conventional way and conveyed by speech, writing, or
gesture.
What is Computer Language?
High-level language (HLL):
A high-level language is any programming language that enables the
development of a program in a much more user-friendly programming
context.
Examples: Python, Visual Basic, Perl, PHP, Ruby, C#, Java, etc.
Low-Level language (Machine Language)
Low-level languages are defined by the processor they are designed to run on; we can
describe these languages as machine-oriented.
How Computer Understand Your Input?

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

• Runs independently. • Needs to be embedded into existing parent


• Creates a .exe file. programs.

• Used in Application/Software • Does not create a .exe file


development. • Used in web development.
• Time taken is more because of the • Lesser time is taken because these are only
code being full-fledged. small pieces of code.
Advantages of scripting languages:

• 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

Visual studio code:


https://code.visualstudio.com/
NodeJs: https://nodejs.org/en/

(install a live server in visual studio code)


Formatting and coding convention
Coding conventions are style guidelines for programming. They typically cover:
• Naming and declaration rules for variables and functions.
• Rules for the use of white space, indentation, and comments.
• Programming practices and principles
Coding conventions secure quality:
• Improves code readability
• Make code maintenance easier
Set of rules
1. Single-line comment : //
Example: //this is a JavaScript class
2. Multiple line comment:
/*
………………
…………..
*/
Variable Names
Rules for naming variables:
-We use keywords var, let, and const to declare variables
-They should be meaningful
-They can not start with the number
-can not contain space or hyphen
-They can not be reserved keywords like if, else, let, etc.
Variable Names
-we use camelCase for identifier names (variables and functions).
-All names start with a letter.
-variables are case sensitive
Variable Names
How can we Implement JavaScript
Two ways:
1. External 2. Inpage

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

Three ways to declare variables

Using var
Using let
Using Const
Example

X, y, z are variables price1, price2, total are variables


var x = 5; var price1 = 5;
var y = 6; var price2 = 6;
var total = price1 + price2;
var z = x + y;
• Variables defined with let cannot be
Let keywords Redeclared.
• Variables defined with let must be
let x = "John Doe"; Declared before use.

let x = 0; • Variables defined with let have Block


Scope.
// SyntaxError: 'x' has
already been declared
• Before ES6 (2015), JavaScript had
only Global Scope and Function Scope.

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

• The const keyword was introduced in (2015).


• Variables defined with const cannot be Redeclared.
• Variables defined with const cannot be Reassigned.
• Variables defined with const have Block Scope.
Var/let/const
The NoScript tag
• If any browser does not support the JavaScript code the alternate content placed
within NoScript tag is being executed.
• Some users might have disabled JavaScript in the browser. In this situation, we use
NoScript to display messages about JavaScript being disabled.
• The noscript element can be used in both <head> and <body> section.
• Example:
<script>
Document.write(‘hello world”);
<noscript>... Your browser does not support JavaScript….</noscript>
JavaScript Operators
let x = 5; // assign the value 5 to x
1.The assignment operat let y = 2; // assign the value 2 to y
or (=) assigns a value to a let z = x + y; // assign the value 7 to z (5 + 2)
variable.
Operator Description
+ Addition
2. JavaScript Arithmetic - Subtraction
Operators
* Multiplication
let x = 5; ** Exponentiation
let y = 2; / Division
let z = x + y; % Modulus (Division Remainder)
++ Increment
-- Decrement
The addition assignment operator (+=) adds a
value to a variable.
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
The addition assignment operator (+=) adds a
value to a variable.
Perform the following arithmetic operation:
1. 5^2+2*10^3+9

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;

The + operator can also be used to add (concatenate) strings.


Output: John Doe
JavaScript Logical Operators
Operator Description

&& logical and

|| 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

& AND 5&1 0101 & 0001 0001

| OR 5|1 0101 | 0001 0101

~ NOT ~5 ~0101 1010


^ XOR 5^1 0101 ^ 0001 0100

<< Zero fill left shift 5 << 1 0101 << 1 1010


>> Signed right shift 5 >> 1 0101 >> 1 0010
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010
Java Script Datatypes
Two types: S-Symbol
1. Primitive datatypes S-String
-7 types (NNBBSSU) U-Undefined
N-Numeric 2. Non-Primitive datatypes
N-Null a. Object datatype
B-Booleans b. Array datatypes
B-BigInt
Java Script Datatypes
Primitive Data Types : fundamental datatypes
String: Can contain groups of character as single value. It is represented in double quotes or
single quote.
E.g. var x= “tutorial”.
Numbers: Contains the numbers with or without decimal.
E.g. var x=44, y=44.56;
Extra large or extra small numbers can be written with scientific (exponential) notation:
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Java Script Datatypes
Booleans:
Contain only two values either true or false.
E.g. var x=true, y= false.
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Java Script Datatypes
Undefined: Variable with no value is called Undefined.
E.g. var x;
Null: If we assign null to a variable, it becomes empty.
E.g. var x=null;
Java Script Datatypes
Symbol:
Symbols are immutable (cannot be changed) and are unique.
For example:
// two symbols with the same description
const value1 = Symbol('hello');
const value2 = Symbol('hello');
console.log(value1 === value2); // false
Java Script Datatypes
Non-Primitives Datatype:
Array:
Can contain groups of values of same type.
E.g. var x = {1,2,3,55};
const cars = ["Saab", "Volvo", "BMW"];
Objects:
Objects are stored in property and value pair.
E.g. var rectangle = { length: 5, breadth: 3};
Practice Questions
1. Create a variable of type string and try to add the number to it.
2. Use the type of operator to find the datatype of the string in the last
question.
3. Write a JS program to create a word meaning dictionary of 5 words.
JavaScript/Control structures
The control structures within JavaScript allow the program flow to
change within a unit of code or function. These statements can
determine whether or not given statements are executed - and
provide the basis for the repeated execution of a block of code.
Control structures
Conditional statement: (if, else, else if, switch) that perform different actions
depending on the value of an expression,
Loops: (while, do-while, for), that execute other statements repetitively,
Jumps: (break, continue) that cause a jump to another part of the program.
Conditional statement
In JavaScript we have the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is
true
• Use else to specify a block of code to be executed, if the same condition is
false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed
If Statement

• In ‘if' statement, if the condition is true a group of statement is executed.


And if the condition is false, the statement is skipped.
• Syntax
• if (condition) {
// block of code to be executed if the condition is true
}
*Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a
JavaScript error.
Example if statement:
Example1:
Example2:
let hour = 10; var age = 20;
if (hour < 18) { if( age > 18 ){
document.write(‘Good day’); document.write(“Qualifies for driving”);
} }
If – Else Statement
If – Else is a two-way decision statement.
• Use the 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
}
If – Else Example
let hour = 18;
if (hour < 18) {
document.write(‘Good day’);
} else {
document.write(‘Good evening’);

}
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:

for - loops through a block of code a number of times


for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
For loop
-If you already know the no of iteration.
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
• Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been executed.
For loop flow chat
Example for loop
let i = 0;
for(i=0; i < 5; i++) { //we know the loop repeats for 5 times
document.write("<br\>hello world");
}
Example for loop
const names = ["Ram", "Hari", "Shyam", "Rita", "Rohan", "Anisa"];
let text = "";
for (let i = 0; i < names.length; i++) {
text += names[i] + "<br>";
}
document.write(text);
for in loop
The JavaScript for in statement loops through the properties of an Object:
Syntax:
for (key in object) {
// code block to be executed
}
for in loop-example
const person = {fname:“Ram", lname:“Bahadur", age:25};

let text = "";


for (let x in person) {
text += person[x];
}
for of loop
• The JavaScript for of statement loops through the values of an iterable
object.
• It lets you loop over iterable data structures such as Arrays, Strings, and
more:
Syntax:
for (variable of iterable) {
// code block to be executed
}
for of loop-example
let language = "JavaScript";

let text = "";


for (let x of language) {
text += x + "<br>";
}
document.write(text);
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.
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
While loop flow chat
Example-while loop
var i = 1;
while(i <= 5) {
document.write("The number is " + i + );
i++;
}
Example-while loop
let n = prompt('enter the value of n');
n=Number.parseInt(n);
let i = 0;
while (i < n) {
document.write(i);
i++;
}
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.
This loop will execute the code block once, before checking if the condition is
true, then it will repeat the loop as long as the condition is true.
Flow chat (Do-while loop)
Do-while loop
Syntax:
do {
// code block to be executed
}
while (condition);
Do-while loop : Example
var a = 1;
do {
document.write("hello world <br/>");
a++;
}
while (a > 5);
Condition is not true so it prints only one statement. (Hello world). If the condition is while(a <=5), then it prints
hello world for 5 times
forEach loop
-forEach loop is method of array
-forEach loop is loop statement used for array.
-The forEach() method calls a function for each element in an array.
Syntax:
array.forEach(function(currentValue)
forEach loop example
//Array forEach loop
let a = ['ram', 'hari', 'shyam'];
a.forEach(function(name){
document.write(name + "</br>");
})
JavaScript Functions
• A JavaScript function is a block of code designed to perform a particular
task. Function calculates a value.
• A JavaScript function is executed when "something" invokes it (calls it).
• JavaScript has predefined function and user defined function.
• Predefined functions: function defined by JavaScript library.
• User defined function: function created by user (programmer)
JavaScript Function
• A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
• Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
• The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
• The code to be executed, by the function, is placed inside curly brackets: {}
JavaScript Function Syntax
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
• Function parameters are listed inside the parentheses () in the function
definition.
• Function parameters are the values received by the function when it is
invoked.
• Inside the function, the arguments (the parameters) behave as local variables.
Why Functions?
• You can reuse code: Define the code once, and use it many times.
• You can use the same code many times with different arguments, to produce
different results.
Creating Function
Syntax:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Creating function
Example 1: function without parameters
function greet() { //function is keyword, greet is function name
document.write('hello function'); //print statement inside function
}
greet(); //invoking function
Creating and invoking function
//function with parameters
function greet(name) { //Name is parameter we pass in function
document.write('hello ' + name); //we cocatenate string with +
}
greet('john'); //we pass argument for name
greet('Bob'); //we can access this function multiple times
Function Invocation
• The code inside the function will execute when "something" invokes (calls)
the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code Automatically (self invoked)
• The () Operator Invokes the Function
Predefined Function
• JavaScript has several "top-level" functions predefined in the language
parseInt, parseFloat, Date()
Function Return
When JavaScript reaches a return statement, the function will stop executing.
Example:
function square (number) {
return number * number;
}
let number = square(4);
Console.log(number);
Local and global Variables
Local Variables
• Variables declared within a JavaScript function, become LOCAL to the function.
• Local variables can only be accessed from within the function.
• Example: carName is local variable which can only be used within function.
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
Global Variables: example
var a = "welcome" //globally declared
function bca(){
document.write(a); //it printed inside the function and outside function
}
bca();
document.write(a);
Local Variables: example
function bca(){
var a = "welcome" //locally declared
document.write(a);
}
bca();
document.write(a); //can't print this statement
Practice set
-Write JavaScript program to print try again until user enter correct
number.
-Write JavaScript program to calculate average of the numbers in array
(use function and loop)
-Write JavaScript program to find the factorial of a given number, take
input from user.
-Write JavaScript program to perform arithmetic operation (addition,
subtract, multiple, division) using function.
Object
-Real world entity is an object
For example: human, laptop, car
-Object has properties and methods
Example: Human is an object
Property: leg, foot, ear, eye
Method: walk (), sleep (), eat ()
Objects in javaScript
All JavaScript values, except primitives, are objects.
JavaScript Primitives
• A primitive value is a value that has no properties or methods.
• JavaScript defines 5 types of primitive data types:
-(string, number, Boolean, null, undefined)
Object Methods
• Methods are actions that can be performed on objects.
• Method is a function that is associated with an object.
• An object method is an object property containing a function definition.
• Object properties can be both primitive values, other objects, and
functions.
Creating a JavaScript Object
• There are different ways to create new objects:
1. Create a single object, using an object literal.
2. Create a single object, with the keyword new.
4. Using object constructor function, and then create objects of the
constructed type.
5. Create an object using Object.create().
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 (like age:50) inside curly braces
{}.
• The following example creates a new JavaScript object with four properties.
Example: Using object literal
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
OR
let person = {
firstName: “Hari",
lastName: ”sharma”,
age: 50,
eyeColor: "blue“,
};
document.write(person.firstName); //we use dot (.) operator or [ ]to access value of object
documnt.write(person[‘firstName’]); //we also use [ ] to access value of object
Using keyword new.
We can create object in JavaScript using Keyword new. When a JavaScript
variable is declared with the keyword new the variable is created as an object:
let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
document.write(person.firstName);
Using Constructor function
A constructor is a function that creates an instance of a class which is typically
called an “object”. In JavaScript, a constructor gets called when you declare an
object using the new keyword.
Using Constructor
function

Let’s say there is an object, User, which has


two properties: firstname and lastname.
To initialize two instances with different
names, you will use the same constructor
function, as shown in the figure.
Using Constructor function: example
// Constructor function for Person objects let myFather = new Person("John", "Doe", 50,
"blue");
function Person(first, last, age, eye) {
let myMother = new Person("Sally", "Rally", 48,
this.firstName = first;
"green");
this.lastName = last;
this.age = age;
// Display age
this.eyeColor = eye;
document.write("My father is " + myFather.age + ".
} My mother is " + myMother.age + ".";
// Create two Person objects
JavaScript Object Properties
• Properties are the most important part of any JavaScript object.
• Properties are the values associated with a JavaScript object.
• A JavaScript object is a collection of unordered properties.
• Properties can usually be changed, added, and deleted, but some are read
only.
Accessing JavaScript Properties
-objectName.property // person.age
Or
objectName["property"] // person["age"]
Object Methods
• JavaScript methods are actions that can be performed on objects.
• A JavaScript method is a property containing a function definition.
Accessing Object Methods
Syntax:
objectName.methodName()
Example:
calculate(); is function call expression.
getArea(); is also function call expression, but
we have rectangle object associated with the
function so, this is called method call expression.
this keyword
-this represents the object that is executing
the current function.
-If the function is part of an object, then we
can call it as function.

rectangle and square are objects.


getArea() is function associated to those
objects.
In calculate() function we don’t have object
attached so we can’t use this keyword
Class
-Class is blueprint of object
-Class is used to create one or more objects
-A class is a user defined blueprint or prototype from which objects are created.
-It represents the set of properties or methods that are common to all objects of
one type.
-Use the keyword class to create a class.
-Always add a method named constructor()
Class
Class
Class
Class
Class
Class: Constructor method
Syntax:
class ClassName {
constructor() { ... }
}
-constructor is where you can initialize the properties of an instance.
-JavaScript automatically calls the constructor method when you create an
object of the class.
Example class: Constructor method
class Car {
constructor(name, year) {
this.carname = name;
this.caryear = year;
}
}
let ford = new Car("suzuki", 2020); //creating object ford of the class Car.
document.write('car name is' + ford.carname + 'year is' + ford.caryear);

Inside constructor we initialized properties as name and year.


We use this keyword to represent those properties are of the object ford of class Car.
Class: Constructor method

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>');

} document.write('area of rectangle 2 is '


+rectangle2.getarea());
getarea(){
return this.width * this.height;
}
}
Class: Static Method
-Static class methods are defined on the class itself.
-You cannot call a static method on an object, only on an object class.
-Static method is a method that is directly a member of a class rather than a part of
instance of class.
-Static method is attached with class but can’t attached with object.
Class: Static Method: Example
class A {
constructor(name) {
this.name = name;
}
static B() {
return "Hello!!";
}
}
let C = new A(“Ram");
A.B(); // You can call ‘B()' on the A Class:
// But NOT on a A Object:
C.A(); // this will raise an error.
Different use of this keyword

Usage (Context) Refers to


this refers to Owner of the Object(Which invoked
In a Method/Object
method)
Alone Global Object (which is window)
In a regular function Global Object (which is window)

In an event The element that received the event


this keyword in object/method

Without using this in object/method Using this in object/method


const person = { //we create person object const person = { //we create person object
firstName: “Shiva", firstName: “Shiva",
lastName : “Jee", lastName : “Jee",
fullName : function() {//FullName is method for object person.
fullName : function() { //FullName is method for document.write(this.firstName) }
person object. };
document.write(person.firstName); this refers to the person object.
}
}; Here we use this instead of objectname to access the object
parameter.
Here we use objectname.parameter to access object
The person object is the owner of the fullName method.
parameter.
Alone
-It returns the global object, which is window.
document.write(this); //this prints window objects
The window object is supported by all browsers. It represents the browser's
window.
All global JavaScript objects, functions, and variables automatically become
members of the window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
In a regular function
In a regular function this refers to the Global object.
function add() {
document.write(this);
}
add();
Let’s Summarize

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";

Using the JavaScript Keyword new


const A = new Array(10, 20, “Ram");
Accessing 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";

Using the JavaScript Keyword new


const A = new Array(10, 20, “Ram");
Array property and method
cars.length // Returns the number of elements
cars.sort() // Sorts the array
pop()-//removes last element from array
a.push("BBA"); //pushes the value to the array
shift()//remove first element
unshift() :- adds a new element to an array (at the beginning), and "unshifts" older
elements and returns new array length.
Array Object
Concat example
var country = [“Nepal", "Canada", "Egypt", "England"];
var city = [“Kathmandu", "Toranto", "Mumbai", "Londan"];
var details = country.concat(city);
document.write(details);
JOIN EXAMPLE

Join example Reverse example


var city = ["Ahmedabad", "Toranto", var city = ["Tokyo", "Toronto",
"Mumbai", "Londan"]; "Mumbai", "London"];
document.write(city.join(" or ") + document.write(city.reverse());
"<br />");
String
• JavaScript strings are for storing and manipulating text.
• A Java Script string is zero or more characters written inside quotes (single
or double)

Example:
Let a = “hello”;
Or
Let a = ‘hello’;
String
let a = "hello"; //string can warp in single and double quote

document.write (a.length); //prints lenght of string


document.write(a[1]); //prints 1'st index of string
document.write(a[0]);
String: Template literals
Template literals used backtick instead of quotation
let x = ‘Salina';
let y = ‘Bishnu';
let sentence = `salina is project friend of Bishnu`; //we use backtick
document.write(sentence);
//we can represent the above statement as follow
let sentense1 = `${x} is project friend of ${y}`; //you can insert variable directly in
template literals which are called string Interpolation
document.write(sentense1);
Escape sequence character
Because strings must be written within quotes, JavaScript will misunderstand the
following string:
let text = “Hello class“Ramesh” is absent today"; //this is not possible
The solution to avoid t
his problem is to use the backslash escape character.

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);

(\n) for new line and (\t) for horizontal tab


let text4 = 'he\tllo’;
document.write(text4);
String objects

-Normally, JavaScript strings are primitive values, created from literals:


However,
-String is also a built-in object in Js when defined with a new keyword
-It helps to perform different string operation
-String object performs an operation using some methods:
Example:
Let x = “human” //this is string
let y = new String(“Human"); //this is object
String objects methods
Name Description
charAt() Returns the character at a specified index (position)

charCodeAt() Returns the Unicode of the character at a specified index

concat() Returns two or more joined strings

endsWith() Returns if a string ends with a specified value


String objects methods
repeat() Returns a new string with a number of copies of a string
replace() Searches a string for a value, or a regular expression, and returns a string
where the values are replaced
search() Searches a string for a value, or regular expression, and returns the index
(position) of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
startsWith() Checks whether a string begins with specified characters
substr() Extracts a number of characters from a string, from a start index (position)
substring() Extracts characters from a string, between two specified indices (positions)
toLowerCase() Returns a string converted to lowercase letters
toString() Returns a string or a string object as a string
toUpperCase() Returns a string converted to uppercase letters
String object-examples

fontcolor() method toUpperCase() method


<script> <script>
let str="Object Example"; var str="Object Example";
document.write("FontColor: " + document.write("UpperCase: "
str.fontcolor("purple")); +str.toUpperCase());</script>
</script> </script>
Practice set
-Filter the number divisible by 10 from the given array.
-Create an array of squares of the given number
-Extract price from the given string “ I have Rs. 10000”
JavaScript Date Object
• The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.

• 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

Date() method getDate() method


Example: var d = new Date();
var d = new Date(); document.write(d.getDate());
document.write(d);
Math Object
-The JavaScript Math object allows you to perform mathematical tasks on
numbers.
Example:
document.write(Math.PI); //3.141592653589793
Math Object
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Methods
Math.round(x) Returns x rounded to its nearest integer

Math.ceil(x) Returns x rounded up to its nearest integer

Math.floor(x) Returns x rounded down to its nearest integer

Math.trunc(x) Returns the integer part of x

Example: document.write(Math.round(3.2)); //It returns 3


Interacting with browser
• JavaScript is what is called a Client-side Scripting Language. That means that
it is a computer programming language that runs inside an Internet browser
(a browser is also known as a Web client because it connects to a Web server
to download pages).
• When the browser loads the page, the browser has a built-in interpreter that
reads the JavaScript code it finds in the page and runs it.
Interacting with browser
console.log("hello");
window.alert("hello");
prompt("enter value");
Interacting with browser
Console methods:
console.log(): This method logs a message to the console.
console.error(): This method logs an error message to the console. It is used to display
error information and track down bugs.
console.warn('This is a warning message!’);
console.info('This is an informational message.');
console.clear();
console.time();
Window & Frame
-It’s important to learn how window object works because that is how JavaScript interacts with browser.
-In order to communication with browser javascript use something which is called Browser Object
Module. Which deals with all component from the browser. Such as history, location, navigation,
height and width from the screen.
-Window object is automatically global in Javascript.
For example: window.alert(‘hello world’)
alert(‘hello world)
This two statement gives same output, because window object is global in javaScript which does not
need to write.
Window
Creating a New Window
• One of the most convenient uses for the window object is to create a new
window.
Creating window

Syntax: WinObj=window.open("URL", "WindowName", "Feature List");


WinObj: variable is used to store the new window object. (You can make your own variable)
window.open() method is a URL, which will be loaded into the new window. If it's left blank, no Web
page will be loaded. window.open() method include width and height, to set the size of the window, and
several features.
Example: SmallWin = window.open("","small","width=100, height=120");
WindowName: This is assigned to the window object's name property and is used to refer to the
window.
Feature list are optional features, separated by commas. You can customize the new window by choosing
whether to include the toolbar, status line, and other features.
Window
Example: Opening and closing window
<body> }
<script> </script>
var win; <button onclick="open
window</button>openWindow()">
function openWindow(){
<button onclick="closeWindow()">close
win=window.open("https://phtechno.com/",'phtech',
window</button>
width=300,height=200');
</body>
}
</html>
function closeWindow(){
win.close();
Frames
• Browser window can be split into many parts called frames. Each part
behaves as a separate window and can load separate documents.
• Each frame has a separate window object and window object has a name
property containing name of the frame
Frame: example
<body>
<iframe style="width:100%;height:100px"></iframe> //creating html frames
<iframe style="width:100%;height:100px"></iframe>
<script>
const frames = window.frames;
for (let i = 0; i < frames.length; i++) {
frames[i].document.body.style.background = "red"; ///filling color in the frame
}
</script>
</body></html>
Document Object Model (DOM)
-We have HTML (for structure), CSS (for style), JavaScript (for action) in
complete website
The question is ??????
-How does JavaScript understand the Markup language?
To answer this question DOM comes in to picture…
What is DOM?
DOM is heart of any web page manipulation.
Document Object Model (DOM)
-It is something created by browser when HTML document loads in to
it.
-We interact JavaScript code with HTML code to do things like change
or add or remove content.
-Once the HTML document loads on the browser, it creates an object
which is called “document Object”.
-When a web page is loaded, the browser creates a Document Object Model of
the page.
DOM
• The DOM is a W3C (World Wide Web Consortium) standard.
• The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content, structure, and
style of a document.“
DOM
• <html>
• <head>
• <title>DOM Model</title>
• </head>
• <body>
• <h1>DataFlair’s Tutorial</h1>
• <p>DOM Tree</p>
• <p id = "text">This is a text element in the DOM
tree.</p>
• </body>
• </html>
DOM
• A DOM tree consists of four main types of nodes:
1. Document node:
• This is added at the top of the tree and represents the entire page in the
browser. As stated above, it is the starting point in the DOM tree; you need
to navigate via the document node to access any other node in your DOM
tree.
DOM
2. Element nodes:
• All the HTML elements like heading tags (<h1> to <h6>) and paragraph
tags (<p>) in the page create an element node in the tree. You use these
nodes to gain access to the elements’ attribute and text nodes.
3. Attribute nodes:
• When the opening tags in the HTML document contain attributes, the tree
represents them as attribute nodes. These are not the children of the element
nodes but a part of them.
DOM
4. Text nodes:
• Once you have access to the element node, you can reach the text content
within that element, stored inside the text nodes of the DOM tree. These
nodes cannot have child nodes. Thus, a text node always creates a new
branch in the DOM tree, and no further branches come out of it.
JavaScript Event
-Event is something that happens to the HTML elements
For example:
-If the button is clicked, then the click event happens.
-If the textbox is focused, then the focus event happens.
-If the key is pressed on the keyboard, a keypress event happens.
Event Handling
-We can write a JavaScript program to react to these events, called event handling.
-Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs.
- When JavaScript code is included in HTML, JS reacts to these events and allows
execution. Which is known as an event handler that is executed when an event occurs.
-This process of reacting to events is called Event Handling. Thus, JS handles the
HTML events via Event Handlers.
Types of JS Event
Two types:
1. Browser-Specific Event
-It happens on the browser. Examples: scrolling up and down, resizing
windows, etc.
1. DOM Specific Event
-It happens on a webpage. For example, clicking on the button, hovering over a
web page-specific element, or focusing on a textbox.
How to handle event in JS
Three ways:
1. Inline Event Handler
2. Event Handler Properties
3. Using addEventListener() method
Inline Event Handler
Using an inline event handler, you can react to the DOM event by:

-Adding an attribute to the HTML element for


which you want to handle the event.
<html>
<body>
Inline Event <form>

Handler <label for="fname">First name:</label><br>


<input type="text" id="fname" name="fname" value="XYZ"
onfocus="this.style.backgroundColor='Yellow’”
onblur="this.style.backgroundColor='Blue'"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
</body>
</html>
Inline Event Handler

-This method is mixing HTML with JS, so it is not well


formatted.
This method is not recommended.
Event Handler Properties
Using the event handler property, we can react to the
DOM event by:
-Adding a property to the DOM element for which
we want to handle the event.
-By creating separate JS files and by creating
functions.
Event Handler Properties
Using the event handler property, we can react to the DOM
event by:
-Adding a property to the DOM element for which we
want to handle the event.
-Assign JS function to that property which you want to
execute when that event occurs
Event Handler Properties: Example
<body>
<button onclick="clickevent()">click me</button> //here we call clickevent
function with and perform onclick event
<script>
function clickevent() //here we create function clickevent
{
document.write("This is click event");
}
</script>
</body> </html>
Some of the HTML events and their event
handlers: Mouse Event
Event Event Handler Description
Performed
click onclick When mouse click on an element
Double click ondbclick When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


Some of the HTML events and their event
handlers: Mouse Event
Event Occurs When
oncontextmenu A user right-clicks on an element
onmouseenter The mouse pointer moves into an element
onmouseleave The mouse pointer moves out of an element
Keyboard events:

Event Event Handler Description


Performed
Keypress onkeypress When the user press and then release
the key
onkeydown A user presses a key
onkeyup A user releases a key
Form events:
Event Event Handler Description
Performed
focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form 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

To encode and decode special character


let key1 = prompt("enter your cookie name");
let value1 = prompt("enter your cookie value");
document.cookie = `${encodeURIComponent(key1)} =
${encodeURIComponent(value1)}`
alert(document.cookie);
alert(`${decodeURIComponent(key1)} = ${decodeURIComponent(value1)}`);
Cookies: Two types
1. Session cookie: It has no life time, it remains alive until you work on
particular session. Once you close the session, it will terminate.
2. Persistent cookie: It has life time, it won’t remove until you clear the browser
or you remove it manually.
Create a Cookie with JavaScript
When you assign a string to document.cookie the browser parse it a cookie and set it
to it’s list of cookie.
JavaScript can create, read, and delete cookies with the document.cookie property.
Syntax:
document.cookie = “name=value";
There are many optional values we can set:
document.cookie=“name=value; expires=date; domain=domain;path=path;”
Example: document.cookie=“username=ram”;
Creating cookie: example
<html> document.cookie = "name=Ram"
<head> </script>
<title>Document</title> </body>
</head> </html>
<body>
<h1>cookie</h1>
<script>
Check recently created cookie in browser
Handling regular expression
A regular expression is way to search a string in a text.
Example:
Expression: Cat
Text: The hungry Cat ran down to the street. Cat was searching for mouse to
eat.
What Is a Regular Expression?
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe what
you are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text
replace operations.
• Regular expression can be used to check many operation like validation, word
repetition etc.
Syntax
/pattern/modifiers;
Example:
let pattern = /hello/i;
hello The pattern to search for
/hello/ A regular expression
/hello/i A case-insensitive regular expression
Modifiers
Modifiers are used to perform case-insensitive and global searches:

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.

let text = "Hello my 0123456789";


let result = text.match(/[^1-4]/g);
document.write(result);
Regular Expressions Patterns
(x|y) //Find any of the alternatives separated with |
let text = "re, green, red, green, gren, gr, blue, yellow";
let result = text.match(/(red|green)/g);
document.write(result);
Regular Expressions Metacharacters
Metacharacters are characters with a special meaning:
1) . metacharacter matches any character, except newline or other line
terminators.

let text = "Please do your 100% in your 4th exam";


let result = text.match(/o.r/g);
document.write(result);
Regular Expressions Metacharacters
2. \w metacharacter matches word characters.

let text = "Please do your 100% in your 4th exam";


let result = text.match(/\w/g);
document.write(result);
Regular Expressions Metacharacters
3. \W metacharacter matches non-word characters:
let text = "Please do your 100% in your 4th exam";
let result = text.match(/\W/g);
document.write(result);
Regular Expressions Metacharacters
4. \d: Find a digit and \D finds non-digits
let text = "Please do your 100% in your 4th exam";
let result = text.match(/\d/g);
let result = text.match(/\D/g);
document.write(result);
Regular Expressions Metacharacters
5. \s : Find a whitespace character and \S finds non-whitespace characters.
let text = "How are you doing today with your best friend";
let result = text.match(/\s/g);
let result = text.match(/\S/g);
document.write(result);
Regular Expressions Metacharacters
6. \b matches at the beginning or end of a word.
let text = "HELLO, How are you doung today";
let result = text.search(/\bHo/);
let result = text.search(/LO\b/);
document.write(result);
Regular Expressions Metacharacters
7. \n character matches newline characters.
let text = "HELLO, How are \n you doung today";
let result = text.search(/\n/);
document.write(result);
Regular Expressions Quantifiers:
1. The + quantifier matches any string that contains at least one character.
let text = "HELLO, How are you doing today";
let result = text.match(/o+/gi);
document.write(result);
Regular Expressions Quantifiers:
2. The * quantifier matches any string that contains zero or more occurrences
of character.
let text = "HELLO, How are you doing today";
let result = text.match(/e*/gi);
document.write(result);
Regular Expressions Quantifiers:
3. The $ quantifier matches any string at the end of it.
let text = "HELLO, How are you doing today";
let result = text.match(/ay$/gi);
let result = text.match(/ou$/gi);
document.write(result);
Regular Expressions: Example for validation

1. Generate regular expressions to test if the first letter is a capital letter in the given string

Regular expression: /^[A-Z]/;

/ - Indicates the start and end of the regular expression.

^ - 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.

[A-Z] - It specifies that the first character should be an uppercase letter.


Regular Expressions: Example for validation

1. Generate regular expressions to validate the phone Number with the following condition.
(Start with 9, the only number allowed, only 10 digits allowed)

Regular expression: /^[9]\d{9}$/


/ - Indicates the start and end of the regular expression.
^ - The caret symbol at the beginning represents the start of the string. It ensures that the number
should start with the specified pattern.
[9] - The square brackets define a character set, indicating that the first digit of the number must be 9.
\d - This shorthand character class matches any digit from 0 to 9.
{9} - The curly braces denote a quantifier, specifying the exact number of occurrences. In this case, it
means there should be exactly 9 occurrences of the preceding \d (digits).
$ - The dollar sign symbol represents the end of the string. It ensures that the number should end
exactly after the 10th digit.
Practice set
1. Write a JavaScript program to test whether the first character of a string
provided by the user is uppercase.
2. Write a JavaScript function to count the number of vowels in a given string
provided by the user.
3. Write a pattern that matches e-mail addresses.
4. Write a pattern that matches the phone number for the Nepali mobile
number

You might also like