Unit II Scripting
Unit II Scripting
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
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>
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');
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
<script>
function add(a, b) {
return a + b; // Returns the sum of a and b
}
<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
}
7
</script>
</body>
</html>
Output:
<script>
function createArray() {
return [1, 2, 3, 4, 5]; // Returns an array
}
Example 4: Returning Arrays
<script>
function createArray() {
return [1, 2, 3, 4, 5]; // Returns an array
}
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) {
} else {
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;
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:
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:
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>
Condition check Before each iteration Before each iteration After each iteration
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:
// 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:
Syntax:
// 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(b); // Output: 20
</script>
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.
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)
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}
</script>
Output: 102 Shyam Kumar 40000
Example:
<script>
emp.id=101;
emp.name="KIPM";
emp.salary=50000;
</script>
15
Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.
Example:<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Utkal",30000);
You can select elements in the DOM using various methods, such as:
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