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

UNIT- II

Basics of Client-side Scripting


Three Core Web Technologies
Introduction to JavaScript
○ Created by Brendan Eich, a programmer, while he was working at
Netscape Communications Corporation in 1995.
○ Originally named as “Mocha”, later changed to “LiveScript” and finally, it
was renamed to "JavaScript" (when Netscape formed a partnership with
Sun Microsystems)
○ Case sensitive and used to make web pages interactive
○ Insert dynamic text into HTML (ex: username)
○ React to events (ex: page load based on user click)
○ Perform calculations on user's computer (ex: form validation)
Introduction to JavaScript
Divided into three parts: the core, client side, and server side

The core is the heart of the language, including its operators, expressions,
statements, and subprograms

Client-side JavaScript is a collection of objects that support the control of a


browser and interactions with users (by using Js, web pages respond to user
inputs)

Server-side JavaScript is a collection of objects that make the language useful


on a Web server (to support communication with a server)
Embedding Javascript in HTML
Head section: Commonly used for scripts that
need to be loaded before the content of the
page is rendered <!DOCTYPE html>
Body section: Used for scripts that are not <html>
critical for page rendering and can be loaded <head>
after the main content <script>
javascript;
</script>
</head>
<script> <body>
javascript; <script>
</script> javascript;
</script>
</body>
</html>
Embedding Javascript in HTML
myfile.html
External: <!DOCTYPE html>
<html>
<head>
<script type=“text/javascript”
src=“myscript.js”>
myscript.js </script>
</head>
Javascript code <body>
<!-- Your HTML content goes
here >-->
<script type=“text/javascript”
src=“myscript.js”>
</script>
</body>
</html>
Comments in Javascript
Single line comments: // This is a single line comment

Multi line comments: /* This is a multi-line comment */


Reserved words in javascript

Apart from these, JavaScript also has some predefined words, such as alert,
open, java, and self.
Variables in Javascript
● A variable is a name associated with a piece of data
● Variable = information container
● In Javascript (Js), Variable definition starts with ‘var’, ‘let’, or ‘const’
● Js is dynamically typed language
● Js is case sensitive

var message = “hai” ;


keyword Variable_name value
Variables in Javascript
Examples:

var x = 10;
var y = 17;
var colour = “red”;
var name = “Katie”;
Different ways of declaring a variable
JavaScript uses the keywords var, let and const to declare variables.

The var keyword :1995 to 2015.

The let and const keywords: added to JavaScript in 2015.

The var keyword : for older browsers.

Note: Js variables are automatically declared on their first usage.


Different ways of declaring a variable
Example:

let v1=“hi”; // block scope hi


v2=“hello”; hello
const v3=“welcome; // block scope welcome

Note: The values assigned to constant variables cannot be changed.


Printing variable to console
Variables can be printed to the using console.log(variable_name)

let v1=“hi”;
console.log (v1);

hi
Challenege-1: The Age Calculator
• Store your birth year in a variable.
• Store a future year in a variable.
• Calculate your age for that year based on the stored values.
• Output them to the screen like: “The age is NN", substituting the values.
Solution

let birthyear=1988;
let futureyear=2024;
let age = futureyear – birthyear;
console.log(The age is ‘+age’);
Javascript Primitives
JavaScript has five primitive types
Undefined

Numbers

Primitive Null

Strings

Booleans
Datatypes: Undefined output

<script>
var myvar;
alert(myvar);
</script>
output
<script>
var myvar= 10;
alert(myvar);
</script>
Datatypes: Null
output
<script>
var myvar= null;
alert(myvar);
</script>
Datatypes: Numbers
<script> output

var num1,num2;
var sum;
num1 = 10;
num2 = 20;
sum = num1 + num2;
alert(sum);
</script>
Datatypes: Strings
<script> output
var str1,str2,str3;
str1 = "welcome to ";
str2 = 'javascript';
str3 = str1+str2;
alert(str3);
</script>
Datatypes: Booleans
<script> Output

var course_completed;
course_completed = false;
course_completed = true;
alert('course completed:'+course_completed);
<script>
Datatypes: Static vs Dynamic
Static type

/* C code */
int num, sum; // explicit declaration
num = 5; // now use the variables
sum = 10;
sum = sum + num;

Dynamic type

/* python code */
num = 10 // directly using the variable
num = “my number”
Datatypes: Static vs Dynamic

Is JavaScript Static type or Dynamic type?


Challenge-2: Datatypes
o Declare a variable x and assign value 10.

o Declare a variable y and assign value 5.2.

o Declare a variable z and assign value true.

o Declare a variable str and assign value “welcome”

o Print these variables to console.


Challenge-2: Solution
<script>
var x = 10, y = 5.2, z= true;
var str = "welcome";
console.log(x);
console.log(y);
console.log(z);
console.log(str);
<script>
Operators in Javascript
Arithmetic Operators:
Operators in Javascript
Assignment Operators:
Operators in Javascript
Comparison Operators:
Operators in Javascript
Logical Operators:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true
Operators in Javascript
Bitwise Operators:
Operators in Javascript
Bitwise Operators:
The typeof Operator
Returns the type of a variable.

typeof "John" // Returns "string"


typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
Challenge-3
A java script program using all operators.
Control Structures
Control structures allow you to manage the flow of your program.

Conditional Statements : if, else if, switch


Looping Statements : for, while, do-while, for-in, for-of
Control Flow Statements : break, continue, return
Conditional Statements
if Statement:

else if Statement:
Conditional Statements
switch Statement:
Looping statements
for Loop:

while Loop:

do-while Loop:
Looping statements
for...in Loop (for iterating over object properties)

for...of Loop (for iterating over iterable objects like arrays)


Control Flow statements
break Statement:
Used to exit a loop or switch statement prematurely.

continue Statement:
Skips the rest of the code inside a loop for the current iteration and
continues with the next iteration.

return Statement:
Exits a function and optionally returns a value.
Challenge-4
Write a JavaScript program to check whether three given integer values are in
the range 50..99 (inclusive). Return true if one or more of them are in the
specified range.
Objects in Javascript
Object is a collection of related properties and methods.
Properties represents the features of the object
Method represents actions that are performed on objects

Object creation: var my_object = new Object(); var my_car = new Object();
my_car.make = "Ford";
my_car.model = "Fusion";

Alternative way: var my_object = {Property1: “value1", property2: “value2"};

var my_car = {make: "Ford", model: "Fusion"};


Objects in Javascript
You can access object properties in two ways:

objectName.propertyName
or

objectName["propertyName"]
Objects in Javascript
var my_car = {make:“Ford",model:“Fusion"};

my_car.model  Fusion //using dot notation

my_car[“model”]  Fusion //using brackets notation


Objects in Javascript
Objects can be nested. You can create a new object that is a property of
my_car.

my_car.engine = new Object();


my_car.engine.config = "V6";
my_car.engine.hp = 263;
Objects in Javascript
A property can be deleted with delete

delete my_car.model;
Js has a loop statement, for-in, that is perfect for listing the properties of an
object.

for (var i in my_car)


console.log(i + ": " + my_car[i]);
Challenge-5
Write a Js program to create an object semester with subjects and faculty as
properties.
Assign values to the properties and print them.
Challenge-6
 Create an object car with the following properties.

 Modify property model of object car to 800.


 Print modified details of object car to console.
Built-in objects in Javascript
Different types of built-in objects:
Number object
Math object
Date object
String object
Number Object
The properties of this object are referenced through Number.
Math Object
The Math object provides a collection of properties used for performing
mathematical calculations on Number objects.

Has methods for the trigonometric functions, such as sin (for sine) and cos
(for cosine)

floor and round methods, etc

All of the Math methods are referenced through the Math object, as in
Math.sin(x).
Date Object
This object is used for obtaining date and time (based on computer’s local
time)
String Object
Used for many string related functionalities (such as concatenation)

The + operator used to add (concatenate) stings.

var txt1 = "John";


var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;

txt3 "John Doe"


String Object
Adding Strings and Numbers

var x = 5 + 5; x  10

var y = "5" + 5; y  55

var z = "Hello" + 5; z  Hello5


Type Conversions
Two types: Implicit and Explicit

Implicit type conversions: Type coercion

The automatic conversion of one data type to another

when an operation or comparison is performed on values of different types

JavaScript will attempt to convert one or both of the values to a common type
before completing the operation
Type Conversions
Explicit type conversions: Type casting

Manual conversion of a data type to another in JavaScript

Using built-in functions or methods that are specifically designed for


converting values from one type to another
Type Conversions
String Conversion:
String(value) - Converts the value to a string

Numeric Conversion:
Number(value) - Converts the value to a number
parseInt(string) - Parses a string and returns an integer
parseFloat(string) -Parses a string and returns a floating-point number

Boolean Conversion:
Boolean(value) - Converts the value to a boolean
String Properties and Methods
Screen Output and Keyboard Input
1. Console.log: Used to print messages along with the values of the
variables to the console. [console.log(variable_name);]
2. document.write: Used for displaying the message on the web browser.
[document.write(“Hello World”);]
3. Alert box: A pop up box with some message will be displayed.
[alert(“Hello world”);]
Screen Output and Keyboard Input
4. Confirm box: A message about confirmation will be displayed.
[confirm("Do you want to continue this download?");]
Screen Output and Keyboard Input
5. Prompt box: A prompt will be opened for user to enter the input
[prompt("What is your name?", "");]
Arrays
Arrays in JavaScript are a type of object that allows you to store and
manipulate a collection of elements.
Arrays
1. Creating an array:

let fruits = ["Apple", "Banana", "Orange"]; // Using array literal


let numbers = new Array(1, 2, 3, 4, 5); // Using Array constructor

2. Accessing Elements:

console.log(fruits[0]); // Output: "Apple"


console.log(numbers[2]); // Output: 3
Arrays
3. Modifying Elements:

fruits[1] = "Grapes";
console.log(fruits); // Output: ["Apple", "Grapes", "Orange"]

4. Array Methods:
Push and Unshift: Push method adds new items to the end of an array
whereas Unshift method adds new items at front of an array.
array.push(item1, item2, ..., itemX);
array.unshift(item1, item2, ..., itemX);
Arrays
Pop and Shift: Pop removes the last item of an array and slice removes the
first item of an array
array.pop()
array.shift()

Slice: Extracts elements from the specified index.


array.slice(starting_index, End_index);
Splice: Add/delete new items in middle of the array.
array.splice(index, howmany, item1, ....., itemX)
Arrays
Join: Converts all the elements of an array to strings and catenates them into
a single string.
var names = new Array["Mary", "Murray", "Murphy", "Max"];
var name_string = names.join(" : ");
["Mary : Murray : Murphy : Max“]
Reverse: Reverses the order of the elements of the Array object
Sort: Coerces the elements of the array to become strings if they are not
already strings and sorts them alphabetically.
names.sort();
["Mary", "Max", "Murphy", "Murray"]
Arrays
Concat: Concatenates its actual parameters to the end of the Array object.
var names = new Array["Mary", "Murray", "Murphy", "Max"];
var new_names = names.concat("Moo", "Meow");
["Mary", "Murray", "Murphy", "Max“, “Moo", "Meow"]
Length: The length of an array is both read and write accessible through the
length property.
names.length();
names.length=20;
Challenge-7.1
 Create an empty array “myArray”

 First add string “hai”

 Second add number 10

 What is the length of the “myArray”

 Print the array to the console.


Challenge-7.2
 Create an empty array “myArray” with 1 to 6 elements.

 Add element 10 at the index 10.

 What is the length of the myArray.

 List out your observations


Functions
Functions are blocks of reusable code that perform a specific task or return a
value.

1. Function Declaration:
Functions
2. Function parameters:

Functions can take parameters, which are values that you provide when
calling the function.
Functions
3. Return statement:

Functions can return a value using return statement.


Functions
4. Function Invocation:

Functions are executed (or invoked) by using parentheses().


Functions
5. Function Scope:

Variables declared inside a function are typically scoped to that function and
not accessible outside of it.
Challenge-8.1
1. Write a javascript program for Calculator Functions.

Create four functions: add, subtract, multiply, and divide.

Each function should take two parameters (two numbers) and return the
result of the corresponding operation.

2. Write a javascript program for string Capitalization using functions

3. Write a javascript program to find the Largest Element using functions


Challenge-8.2
Write a javascript program for Palindrome Checker

Take string as a parameter

Return True if the string is palindrome.


Constructors in Javascript
JavaScript constructors are special functions that create and initialize the
properties of the objects.

New: Used to create an instance of an object that has a constructor function.

my_car = new car();


car.make=“Ford”;
car.model=“Fusion”;
car.year=“2012”;
Constructors in Javascript
This: Used to refer an object

function my_car(new_make, new_model, new_year)


{
this.make = new_make;
this.model = new_model;
this.year = new_year;
}
Challenge-9
Write a javascript program on constructors using new and this.
Pattern matching using regular expressions
Pattern matching in JavaScript is often done using regular expressions.

Regular Expression is a sequence of characters that forms a search pattern

Regular expressions (regex or RegExp) provide a powerful and flexible way to


search, match, and manipulate strings based on patterns.

A kind of search, find and replace operations on string data.


Pattern matching using regular expressions
Creating a Regular Expression: Using RegExp constructor or literal syntax
Pattern matching using regular expressions
Basic Matching:
Uses test method to check if a string contains a match for a pattern.

test() is case-sensitive by
default
Pattern matching using regular expressions
Matching and Extracting:
Use match method to find matches in a string.
Returns an array of matches or null if no match found.

match() is not case-sensitive by


default
Pattern matching using regular expressions
Flags:
Regular expressions can have flags that modify their default behavior.

Flag Description

i Performs case-insensitive matching

g Performs global search for all occurrences

^ match the start of each line

$ match the end of each line

m match the start and end of each line


Example
Example
Pattern matching using regular expressions
Quantifiers:

Quantifiers are used to specify how many occurrences of a character


or group should be matched.
Example
Pattern matching using regular expressions
Character Classes:
Character classes allow you to match any one of a set of characters
Pattern matching using regular expressions
Groups and Capturing:
Parentheses ‘()’ are used to create groups
Can capture the matched content using them
Pattern matching using regular expressions
Replace:
Used to replace matches with a specified string
Examples
/\d\.\d\d/

/\D\d\D/

/\w\w\w/

/x*y+z?/

/[A-Za-z]\w*/

You might also like