0% found this document useful (0 votes)
5 views

Unit II Scripting

The document provides an overview of JavaScript, including its features, applications, and how to create variables, functions, and handle events. It covers various programming concepts such as conditional statements, loops, and block scope, along with examples for better understanding. JavaScript is highlighted as a lightweight, interpreted language that enables interactive web development.

Uploaded by

Vaishnavi Dubey
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)
5 views

Unit II Scripting

The document provides an overview of JavaScript, including its features, applications, and how to create variables, functions, and handle events. It covers various programming concepts such as conditional statements, loops, and block scope, along with examples for better understanding. JavaScript is highlighted as a lightweight, interpreted language that enables interactive web development.

Uploaded by

Vaishnavi Dubey
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
You are on page 1/ 17

MASTER OF COMPUTER APPLICATION (MCA)

BMC201 : WEB TECHNOLOGY


Unit-II Scripting
Introduction to JavaScript:
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web
browser.
JavaScript was invented by Brendan Eich in 1995.

Features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. It is a light-weighted and interpreted language.
4. It is a case-sensitive language.
5. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
6. It provides good control to the users over the web browsers.

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.

Note: In HTML, JavaScript code is inserted between <script> and </script> tags.

Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>

1
Creating Variables in JavaScript:
In JavaScript, variables are used to store data values. You can create variables using three
keywords: var, let, and const. Each of these has specific use cases based on scope and
mutability (whether the variable can be reassigned or not).
1. var:

var x = 5;
console.log(x); // Output: 5

var x = 10; // Re-declaring the same variable


console.log(x); // Output: 10
2. let:
let a = 10;
console.log(a); // Output: 10

a = 20; // You can update the value


console.log(a); // Output: 20
3. const:
const pi = 3.14;
console.log(pi); // Output: 3.14

// pi = 3.14159; // Error: Assignment to constant variable


Scope of Variables:
 Global Scope: Variables declared outside of any function or block are globally scoped,
which means they can be accessed anywhere in the code.
 Function Scope: var variables declared inside a function are function-scoped.
 Block Scope: let and const are block-scoped, meaning they exist only within the block
(like within an if statement or loop) where they are declared.

Creating Functions in JavaScript:


Functions in JavaScript are blocks of reusable code that perform a specific task. They are one
of the fundamental building blocks of any JavaScript program. You can define a function once
and then call it as many times as needed.
Syntax for Creating Functions

There are multiple ways to create functions in JavaScript:

1. Function Declaration:

A function declaration defines a function with the function keyword, followed by a name, a
list of parameters, and the function body (code that the function executes).

2
Example:
<html>
<body>
<script>
function greet(name) {
return `Hello, ${name}!`;
}
document.write(greet("KIPM"));
</script>
</body>
</html>
Output:

2. Function Expression:
A function expression assigns a function to a variable. Unlike function declarations, function
expressions are not hoisted, so they cannot be called before they are defined.

<script>
const add = function(a, b) {
return a + b;
};

document.write(add(5, 10));
</script>
Output: 15
3. Arrow Functions (ES6):
Arrow functions provide a shorter syntax for writing functions. They are always anonymous
and often used for shorter function expressions.

<script>
const multiply = (a, b) => a * b;
document.write(multiply(3, 4));
</script>
Output: 12

4. Anonymous Functions:
An anonymous function is a function without a name. They are often used in situations where
a function is only used once, such as in event handling or passing to other functions
(callbacks).

<script>
setTimeout(function() {
document.write("This message will appear after 2 seconds");
}, 2000);
</script>

3
5. Immediately Invoked Function Expressions (IIFE):

An IIFE is a function that runs as soon as it is defined. These are used to avoid polluting the
global scope by enclosing variables inside a local scope.

<script>
(function() {
document.write("This function runs immediately");
})();
</script>

JavaScript UI (User Interface) Events:


The change in the state of an object is known as an Event. UI events in JavaScript are events
that are triggered by user interactions with the user interface of a web application. These events
are crucial for creating dynamic and interactive web applications.
Common UI Events
1. Mouse Events
o click: Fired when an element is clicked.
o dblclick: Fired when an element is double-clicked.
o mouseover: Fired when the mouse pointer enters an element.
o mouseout: Fired when the mouse pointer leaves an element.
o mousemove: Fired when the mouse is moved within an element.
o mousedown: Fired when a mouse button is pressed down.
o mouseup: Fired when a mouse button is released.
2. Keyboard Events
o keydown: Fired when a key is pressed down.
o keyup: Fired when a key is released.
o keypress: Fired when a character key is pressed.
3. Form Events
o submit: Fired when a form is submitted.
o change: Fired when the value of an input changes.
o focus: Fired when an element gains focus.
o blur: Fired when an element loses focus.
4. Touch Events (for mobile devices)
o touchstart: Fired when a touch point is placed on the touch surface.
o touchmove: Fired when a touch point is moved along the touch surface.
o touchend: Fired when a touch point is removed from the touch surface.

4
Event Handling

You can handle UI events using JavaScript by adding the addEventListener() method is
used to attach an event handler to a particular element..

Syntax
element.addEventListener(event, function, useCapture);
Note: Although it has three parameters, the parameters event and function are widely used.
The third parameter is optional to define.
Parameter Values
event: It is a required parameter. It can be defined as a string that specifies the event's name.

function: It is also a required parameter. It is a JavaScript function which responds to the event
occur.

useCapture: It is an optional parameter. It is a Boolean type value that specifies whether the
event is executed in the bubbling or capturing phase. Its possible values are true and false.
When it is set to true, the event handler executes in the capturing phase. When it is set to false,
the handler executes in the bubbling phase. Its default value is false.

Example:

<!DOCTYPE html>
<html>
<head>
<title>UI Events Example</title>
</head>
<body>
<button id="myButton">Click me!</button>
<input type="text" id="myInput" placeholder="Type something...">

<script>
// Select elements
const button = document.getElementById('myButton');
const input = document.getElementById('myInput');

// Add a click event listener to the button


button.addEventListener('click', function() {
alert('Button was clicked!');
});

// Add a change event listener to the input field


input.addEventListener('change', function() {
alert(`Input value changed to: ${input.value}`);
});

5
</script>
</body>
</html>
Output:

Example2:

<!DOCTYPE html>
<html>
<body>
<p> Example of the addEventListener() method. </p>
<p> Click the following button to see the effect. </p>
<button id = "btn"> Click me </button>
<p id = "para"></p>
<script>
document.getElementById("btn").addEventListener("click", fun);
function fun() {
document.getElementById("para").innerHTML = "Hello Students" + "<br>" + "Welcome to
KIPM- College of Management ";
}
</script>
</body>
</html>
Output:

6
Returning Data from Functions:
In JavaScript, functions can return data using the return statement. When a function is called,
it executes its code and can return a value back to the place where it was called. This allows
you to use the result of the function in other parts of your code.
Syntax:
function functionName(parameters) {
// Code to execute
return value; // This value will be returned to the caller
}
Example 1: Returning a Simple Value

Here’s an example of a function that returns a number:

<script>
function add(a, b) {
return a + b; // Returns the sum of a and b
}

const result = add(5, 3); // result will be 8


document.write(result); // Output: 8
</script>
Example 2: Returning Strings:

You can also return strings from functions:

<script>
function greet(name) {
return `Hello, ${name}!`; // Returns a greeting string
}
const greeting = greet('KIPM'); // greeting will be "Hello, KIPM!"
document.write(greeting); // Output: Hello, KIPM!
</script>
Example 3: Returning Objects
Functions can return complex data types like objects:

<html>
<body>
<script>
function createPerson(name, age) {
return {
name: name,
age: age,
}; // Returns an object
}

const person = createPerson('KIPM', '15');


document.write(person.name+" "+person.age);

7
</script>
</body>
</html>
Output:

<script>
function createArray() {
return [1, 2, 3, 4, 5]; // Returns an array
}
Example 4: Returning Arrays

You can also return arrays from functions:

<script>
function createArray() {
return [1, 2, 3, 4, 5]; // Returns an array
}

const array = createArray();


document.write(array); // Output: [1, 2, 3, 4, 5]
</script>
Working with Conditions:
In JavaScript, conditions are used to perform different actions based on different logical or
comparison results. Conditional statements evaluate expressions and execute code blocks
depending on whether the conditions are true or false.
1. if Statement:

The if statement is used to execute a block of code only if a specified condition is true.

Syntax:

if (condition) {
// code to be executed if the condition is true
}
Example:
<script>
const age = 18;
if (age >= 18) {
document.write('You are an adult.');
}
</script>
2. if...else Statement

The if...else statement provides an alternative block of code that will be executed if the
condition is false.

8
Syntax:
if (condition) {

// code to be executed if the condition is true

} else {

// code to be executed if the condition is false

Example:

<script>
const age = 16;
if (age >= 18) {
document.write('You are an adult.');
} else {
document.write('You are a minor.');
}
</script>
3. if...else if...else Statement

The if...else if...else statement is used to check multiple conditions. If one of the conditions is
true, the corresponding block of code is executed.

Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
Example:
<script>
const score = 85;

if (score >= 90) {


document.write('Grade: A');
} else if (score >= 80) {
document.write('Grade: B');
} else if (score >= 70) {
document.write('Grade: C');
} else {
document.write('Grade: F');
}
</script>

9
4. Ternary Operator (? :)

The ternary operator is a shorthand for if...else. It allows you to assign a value or perform an
action based on a condition in a single line.

Syntax:

condition ? expressionIfTrue : expressionIfFalse;

Example:
<script>
const age = 20;
const status = (age >= 18) ? 'Adult' : 'Minor';
document.write(status); // Output: Adult
</script>
6. switch Statement

The switch statement is an alternative to if...else when you need to compare the same
expression against multiple values. It’s more readable when you have many possible outcomes.

Syntax:

switch (expression) {
case value1:
// code to execute if expression === value1
break;
case value2:
// code to execute if expression === value2
break;
default:
// code to execute if expression doesn't match any case
}
Example:
<script>
const day = 'Monday';

switch (day) {
case 'Monday':
document.write('Start of the work week.');
break;
case 'Wednesday':
document.write('Midweek.');
break;
case 'Friday':
document.write('Weekend is near.');
break;
default:

10
document.write('Just another day.');
}
</script>
looping in JavaScript:
Looping in JavaScript is a way to repeat a block of code multiple times. JavaScript offers
several looping constructs, each suited to different use cases. The most common looping
structures are:
1. for loop:

The for loop is used when you know the number of iterations in advance.

Syntax:
for (initialization; condition; increment) {
// Code to be executed
}
Example:
<script>
for (let i = 0; i < 5; i++) {
document.write(i+" "); // Output: 0, 1, 2, 3, 4
}
</script>
2. while loop:

The while loop continues executing as long as the condition is true.

Syntax:

while (condition) {

// Code to be executed

Example:

<script>
let i = 0;
while (i < 5) {
document.write(i+" "); // Output: 0, 1, 2, 3, 4
i++;
}
</script>

11
3. do...while loop:

The do...while loop is similar to while, but it guarantees that the code block runs at least once.

Syntax:

do {

// Code to be executed

} while (condition);

Example:

<script>
let i = 0;
do {
document.write(i+" "); // Output: 0, 1, 2, 3, 4
i++;
} while (i < 5);
</script>

Key Differences Table:

Feature for loop while loop do-while loop

Done in the loop


Initialization Done outside the loop Done outside the loop
statement

Condition check Before each iteration Before each iteration After each iteration

Executes at least ❌ No (if condition is ❌ No (if condition is


once? ✅ Yes (even if false)
false) false)

At least one-time
Use case Known iterations Unknown iterations
execution

4. for...of loop:

The for...of loop iterates over iterable objects like arrays or strings.

Syntax:

for (let variable of iterable) {

// Code to be executed

12
}

Example:

<script>
let arr = [10, 20, 30];
for (let value of arr) {
document.write(value+" "); // Output: 10, 20, 30
}
</script>

5. for...in loop:

The for...in loop iterates over the properties of an object.

Syntax:

for (let key in object) {

// Code to be executed

Example:

<script>
let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
document.write(key+" ",obj[key]+" "); // Output: a 1, b 2, c 3
}
</script>
Block Scope Variables in JavaScript:
In JavaScript, block scope refers to variables that are accessible only within a specific
block, typically denoted by curly braces {}. Block scope was introduced with ES6
(ECMAScript 2015) (European Computer Manufacturers Association Script) and
applies to variables declared using let and const. Variables declared using var are not
block-scoped; instead, they are function-scoped or globally scoped.
Block Scope with let and const
 let: Declares a block-scoped, local variable. The value can be updated within its
scope, but it cannot be redeclared in the same scope.

13
 const: Declares a block-scoped, read-only constant. The value cannot be
reassigned, though objects and arrays declared as const can have their contents
modified.
Example:
<script>

let a = 10;

const b = 20;

document.write(a+" "); // Output: 10

document.write(b); // Output: 20

// Outside the block

document.write(a); // ReferenceError: a is not defined

document.write(b); // ReferenceError: b is not defined

</script>

Why Block Scope is Useful


 Avoids Polluting the Global Scope: Block-scoped variables remain local to their
block, preventing accidental overwriting of variables in other parts of the program.
 Temporal Dead Zone: Variables declared with let or const are hoisted to the top of
their block but are not initialized until the line where they are declared. This creates a
temporal dead zone where any reference to the variable before its declaration results in
a ReferenceError.

JavaScript Objects:
In JavaScript, objects are a fundamental data structure used to store collections of data
and more complex entities. An object is a collection of key-value pairs, where keys are
strings (or symbols) and values can be any data type (primitive types or other objects).
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object.
But, we direct create objects.

Creating Objects in JavaScript

14
There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal:

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}
Note: As you can see, property and value is separated by : (colon).
Example:

<script>

emp={id:102,name:"Shyam Kumar",salary:40000}

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>
Output: 102 Shyam Kumar 40000

2) By creating instance of Object:

The syntax of creating object directly is given below:

var objectname=new Object();


Here, new keyword is used to create object.

Example:

<script>

var emp=new Object();

emp.id=101;

emp.name="KIPM";

emp.salary=50000;

document.write(emp.id+" "+emp.name+" "+emp.salary);

</script>

Output: 101 KIPM 50000

3) By using an Object constructor

15
Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.

The this keyword refers to the current object.

Example:<script>

function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Utkal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>

Output: 103 Utkal 30000

Manipulating DOM Elements with JavaScript:


Manipulating the Document Object Model (DOM) with JavaScript is a key aspect of
web development. It allows you to dynamically change the content, style, and structure
of your web pages.
1. Selecting DOM Elements

You can select elements in the DOM using various methods, such as:

 document.getElementById(): Selects an element by its ID.


 document.getElementsByClassName(): Selects all elements with a specific
class name.
 document.getElementsByTagName(): Selects all elements with a specific tag
name.
 document.querySelector(): Selects the first element that matches a specified
CSS selector.
 document.querySelectorAll(): Selects all elements that match a specified CSS
selector.

Example:
<script type="text/javascript">

function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>

16
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Output:

17

You might also like