0% found this document useful (0 votes)
63 views41 pages

JavaScript Client-Side Scripting Guide

The document provides a comprehensive overview of JavaScript, covering its capabilities for client-side scripting, including manipulating HTML and CSS, data validation, and various data types. It explains variable declaration, scope, and the use of objects, arrays, and regular expressions, along with methods for form validation and debugging. Additionally, it highlights common JavaScript methods and objects such as Date and Math, as well as techniques for outputting data and handling user interactions.

Uploaded by

garimaa0022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views41 pages

JavaScript Client-Side Scripting Guide

The document provides a comprehensive overview of JavaScript, covering its capabilities for client-side scripting, including manipulating HTML and CSS, data validation, and various data types. It explains variable declaration, scope, and the use of objects, arrays, and regular expressions, along with methods for form validation and debugging. Additionally, it highlights common JavaScript methods and objects such as Date and Math, as well as techniques for outputting data and handling user interactions.

Uploaded by

garimaa0022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Client-Side Scripting

using Java script


by Dr Piyush Bagla
JavaScript

• JavaScript is the programming language of the web.

• It can update and change both HTML and CSS.

• It can calculate, manipulate and validate data.


JavaScript

• JavaScript can change HTML Elements.

• JavaScript can change HTML Attributes.

• JavaScript can change CSS.

• JavaScript can Hide HTML Elements.

• JavaScript can show HTML Elements.


JavaScript

• JavaScript can "display" data in different ways.

• Writing into an HTML element, using innerHTML.


➢ The innerHTML property defines the HTML content

• Writing into the HTML output using [Link]().


➢ Using [Link]() after an HTML document is loaded, will delete all existing HTML.
➢ The [Link]() method should only be used for testing.

• Writing into an alert box, using [Link]().


• Writing into the browser console, using [Link]().
➢ For debugging purposes, you can call the [Link]() method in the browser to display data.
JavaScript can be included in an HTML document in several different
ways; the most common are :

• Inline JavaScript

<button onclick="alert('Hello, world!')">Click me</button>

• Internal JavaScript

• Inside <body> • Inside <head>


<script> <script>
// JavaScript code here // JavaScript code here
</script> </script>

• External JavaScript

<script src="[Link]"></script>
Common ways to select HTML element

• getElementById()
• getElementsByClassName()
• getElementsByName()
• getElementsByTagName()

var n = [Link](“nm”).value;
const r = /hello/
JavaScript Variables

Variables can
be declared in
4 ways:

Automatically Using var Using let Using const

a = 5; var a = 5; let a = 5; const a = 5;


Block Scope

• Before ES6 (2015), JavaScript did not have Block Scope.

• JavaScript had Global Scope and Function Scope.

• ES6 introduced the two new JavaScript keywords: let and const.

• These two keywords provided Block Scope in JavaScript.

• Variables declared with the var always have Global Scope or Function Scope.

• Variables declared with the var keyword can NOT have block scope.

• Variables declared with var inside a { } block can be accessed from outside the block.
Introduced

var - pre ES2015

let - ES2015 (ES6)

const – ES2015 (ES6)


Declaration

var a; // allowed
let b; // allowed

const c; // not allowed


SyntaxError: Missing initializer in const declaration

const c = 10 ; // allowed
Initialization

Same line Initialization : Later Initialization :


var a;
var a = 10,
a = 10; // allowed
let b = 20;
const c = 30;
let b;
b = 20; // allowed

const c;
c = 30; // not allowed
SyntaxError: Missing initializer in const declaration
Redeclaration

var a = 10;
var a = 20; //its possible to with var

let b = 10;
let b = 20; //its not possible with let
SyntaxError: Identifier 'b' has already been declared

const c = 10;
const c = 20; //its not possible with const
SyntaxError: Identifier 'c' has already been declared
Redeclaring Var
• Variables defined with var can be • If you re-declare a JavaScript variable
redeclared. declared with var, it will not lose its value.
var a = 5;
• Redeclaring a variable using var a; // var is still 5
the var keyword can impose problems.
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Reinitialization

var a = 10; //declared once


a = 20; //reintialized again --> its possible with var

let b = 10; //declared once


b = 20; //reintialized again --> its possible with let

const c = 10; //declared once


c = 20; //reintialized again --> its NOT possible with let,
TypeError: Assignment to constant variable.
Scope
a) Functional Scope: declare greeting variable without var
When we don’t declare variables without any var, let and const , variables gets hoisted globally .
function wishPiyush() {
greeting = “Hello, Piyush!”; // global variable at runtime
[Link](greeting);
}
wishPiyush();
[Link](greeting); // Hello, Piyush!

Output:
Hello, Piyush!
Hello, Piyush!
Scope
a) Functional Scope: declare greeting variable with var now
function wishPiyush() {
var greeting = "Hello, Piyush!"; //greeting remained functional scoped
[Link](greeting);
}
wishPiyush();
[Link](greeting); // Hello, Piyush!

Output:
Hello, Piyush!
ReferenceError: greeting is not defined
Scope
{
var x = 10;
b) Block Scope }
[Link](x); // output 10

{
let y = 20;
}
[Link](y); // output : ReferenceError: y is not defined

{
const z = 30;
}
[Link](z); // output : ReferenceError: z is not defined
Hoisted

[Link](x); // Outputs 'undefined'


var x = 10; // Assignment remains in its original position

let and const : are also Hoisted*

* variables with let and const are also hoisted but at the top of block scope and
they are not assigned with undefined.
JavaScript Datatypes

In JavaScript:
• var, let, and const are not data types themselves; they are keywords
used for variable declaration.
• Data types in JavaScript are the types of values that variables can hold,
such as numbers, strings, booleans, objects, arrays, etc.
• When you write something like var a = 10;, a can hold a number value (10
in this case), so we say that a is a variable holding a numeric literal.
• In summary, while in C and C++, we explicitly specify the data type of a
variable when declaring it, in JavaScript, we declare variables using
keywords like var, let, or const, and the data type of a variable is
determined by the value it holds.
JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined

JavaScript Data 6.
7.
Null
Symbol
8. Object
Types
The Object Datatype

The object data type can contain:


1. Primitive values
2. Other objects
3. Arrays
4. Functions
5. Dates
6. Symbols and more
JavaScript Data Types
Data Type Example Code Explanation
Represents numeric values
Number let age = 30; [Link](age); // 30
(integers or decimals)
let bigNumber = 12345678901234567890123456789n; Represents very large integers,
BigInt
[Link](bigNumber); use n at the end
Sequence of characters enclosed in
String let greeting = "Hello, world!"; [Link](greeting);
quotes
Boolean let isActive = true; [Link](isActive); Logical true or false values
Variable declared but not assigned
Undefined let x; [Link](x); //eundefined
a value
Represents intentional absence of
Null let y = null; [Link](y); // null
any value
Unique identifier, often used as
Symbol let sym = Symbol("id"); [Link](sym);
object keys
let person = {name: "Alice", age: 25};
Object Collection of key-value pairs
[Link](person);
JavaScript Data Types (example)

// Number
let age = 30;
[Link](age); // 30

// BigInt
let bigNumber = 12345678901234567890123456789n;
[Link](bigNumber); // 12345678901234567890123456789n

// String
let greeting = "Hello, world!";
[Link](greeting); // Hello, world!

// Boolean
let isActive = true;
[Link](isActive); // true

// Undefined
let x;
[Link](x); // undefined
JavaScript Data Types (example)

// Null
let y = null;
[Link](y); // null

// Symbol
let sym = Symbol("id");
[Link](sym); // Symbol(id)

// Object
let person = {name: "Alice", age: 25};
[Link](person); // { name: 'Alice', age: 25 }
JavaScript Object

What is a JavaScript Object?


• An Object in JavaScript is a collection of key-value pairs.
• Keys (also called properties) are strings (or Symbols).
• Values can be any data type, including other objects or functions.
• Objects allow you to group related data and functionality together.

How to create an object?


1. Using Object Literal (most common)

const person = {
name: "Alice",
age: 25,
isStudent: false
};
JavaScript Object

2. Using new Object() syntax


const person = new Object();
[Link] = "Alice";
[Link] = 25;
[Link] = false;

Accessing Object Properties


• Dot notation:
[Link]([Link]); // Alice

• Bracket notation (useful if key is dynamic or not a valid identifier):

[Link](person["age"]); // 25

let key = "isStudent";


[Link](person[key]); // false
JavaScript Object

const car = {
make: "Toyota",
model: "Camry",
year: 2022,
start: function() {
[Link]("Car started");
},
info: function() {
[Link](`${[Link]} ${[Link]} (${[Link]})`);
}
};
[Link](); // Car started
[Link](); // Toyota Camry (2022)
Ways to see the output

• [Link]() can overwrite the whole page if used after page load.
• DOM manipulation requires existing elements or creating new ones.
• Not ideal for debugging internal code logic.

• The [Link]() method outputs messages to the browser console or [Link]


terminal.
• Mainly used for debugging.
Pop-up boxes in JavaScript

1. Alert Box
2. Confirm Box
3. Prompt Box
JavaScript Form Validation

Forms can be validated using HTML, and JavaScript.

[Link] Validation: HTML5 introduced several built-in validation attributes for form inputs such
as required, min, max, pattern, etc.

[Link] Validation: You can use JavaScript to implement custom validation logic beyond
what HTML provides. This allows you to perform complex validation tasks, such as validating
the format of input data, checking for uniqueness, or interacting with external data sources for
validation.

[Link] Role: While CSS itself cannot perform form validation, it can be used to enhance the
visual feedback of validation errors. For example, you can style invalid form inputs using the
:invalid and :valid pseudo-classes to provide visual cues to users.
Regular Expression
Regular expressions in JavaScript, also known as regex or regexp, are a sequence of characters that
form a search pattern.

1. Creating Regular Expression


Regular expressions in JavaScript can be created using the RegExp constructor or by using a regex
literal enclosed in forward slashes (/).

// Using RegExp constructor


const regex1 = new RegExp('pattern’);;

// Using regex literal


const regex2 = /pattern/;
2. Matching Patterns

Regular expressions are used with string methods like test() and match() to check if a
pattern matches a string or to extract substrings that match the pattern.

Example:

const str = 'Hello, world!’;


const pattern = /hello/i; // Case-insensitive match
[Link]([Link](str)); // Output: true
[Link]([Link](pattern)); // Output: ["Hello”]
3. Modifiers

Regular expressions support modifiers that affect how a pattern is matched, such as:
1. i: Case-insensitive match
2. g: Global match (find all matches, not just the first)
3. m: Multiline match

Example:

const str = 'Apple, apple, APPLE’;


const pattern = /apple/ig; // Case-insensitive, global match
[Link]([Link](pattern)); // Output: ["Apple", "apple", "APPLE"]

Replace
[Link](/apple/i, ”GEHU");
Regular Expression Patterns

Brackets are used to find a range of characters:


Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:


Metacharacter Description
\w Find a word character
\W Find a non word character
\b Find a match at the beginning of a word like this: \bWORD, or at the end of
a word like this: WORD\b
\d Find a digit
Regular Expression Patterns
Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
Array

JavaScript Arrays
An array is a collection of values stored in a single variable.

let fruits = ["Apple", "Banana", "Mango"];


[Link](fruits[0]); // Output: Apple

let arr1 = [10, 20, 30];


let arr2 = new Array("red", "green", "blue");
Array

Common Array Methods


Method Description Example
push() Adds item at the end [Link]("Orange")
pop() Removes last item [Link]()
shift() Removes first item [Link]()
unshift() Adds item at the start [Link]("Kiwi")
concat() Joins two arrays [Link](arr2)
slice(start, end) Returns a portion [Link](1,3)
splice(start, count) Adds/removes elements [Link](1,1)
indexOf() Finds index of item [Link]("Banana")
includes() Checks if exists [Link]("Apple")
sort() Sorts elements [Link]()
reverse() Reverses array [Link]()

forEach() Loops through array [Link](f => [Link](f))

map() Returns new array [Link](n => n * 2)


filter() Filters array [Link](n => n > 10)
reduce() Reduces to single value [Link]((a,b)=>a+b)
JavaScript Date Object

Used to work with dates and times.

let now = new Date();


[Link](now); // Current date and time
Common Methods:
Method Description Example
getFullYear() Get year [Link]()
getMonth() Get month (0–11) [Link]()
getDate() Get day of month [Link]()
getDay() Get weekday (0–6) [Link]()
getHours() Get hour [Link]()
getMinutes() Get minutes [Link]()
toDateString() Readable date [Link]()
toLocaleString() Local date/time [Link]()
JavaScript Math Object

Used for mathematical calculations.


[Link]([Link]); // 3.14159
[Link]([Link](25)); // 5

Common Methods:
Method Description Example
[Link](x) Rounds to nearest integer [Link](4.6) → 5
[Link](x) Rounds down [Link](4.9) → 4
[Link](x) Rounds up [Link](4.1) → 5
[Link](a,b,...) Max value [Link](2,5,10)
[Link](a,b,...) Min value [Link](2,5,10)
[Link]() Random (0–1) [Link]()
[Link](a,b) Power [Link](2,3) → 8
[Link](x) Absolute value [Link](-7) → 7
JavaScript String Object
Represents and manipulates text.
let str = "JavaScript";
Common Methods:
Method Description Example
length Length of string [Link]
toUpperCase() Converts to uppercase [Link]()
toLowerCase() Converts to lowercase [Link]()
charAt(i) Character at index [Link](2)
indexOf(sub) Position of substring [Link]("Script")
slice(start, end) Extract substring [Link](0,4) → "Java"
substring(start, end) Similar to slice [Link](4,10)
replace(a, b) Replace substring [Link]("Java", "Type")
trim() Remove spaces " hello ".trim()
split() Split into array [Link]("") → ['J','a',...]
concat() Join strings [Link](" is fun")

You might also like