0% found this document useful (0 votes)
4 views34 pages

WT U2 JavaScript

The document provides an overview of JavaScript, covering its introduction, features, syntax, and various programming concepts such as variable declarations, data types, operators, and control structures. It details the characteristics of primitive data types and includes examples of simple JavaScript programs. Additionally, it explains operations, expressions, and control structures, emphasizing their importance in JavaScript programming.

Uploaded by

sshreenidhi23
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)
4 views34 pages

WT U2 JavaScript

The document provides an overview of JavaScript, covering its introduction, features, syntax, and various programming concepts such as variable declarations, data types, operators, and control structures. It details the characteristics of primitive data types and includes examples of simple JavaScript programs. Additionally, it explains operations, expressions, and control structures, emphasizing their importance in JavaScript programming.

Uploaded by

sshreenidhi23
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

II BCA WT: UNIT 2 - Java Script Dept.

: BCA

JAVASCRIPT

1. Introduction to JavaScript

JavaScript is a high-level, interpreted, dynamically typed programming language used to create


interactive and dynamic web applications. It is one of the core technologies of web development
along with HTML and CSS.

JavaScript was created in 1995 by Brendan Eich.

JavaScript can run:

• In web browsers (client-side)


• On servers using [Link]

2. Features of JavaScript
 Lightweight and interpreted
 Object-oriented and prototype-based
 Event-driven
 Dynamically typed
 Supports functional programming
 Cross-platform

GENERAL SYNTACTIC CHARACTERISTICS OF JAVASCRIPT


1. Introduction
JavaScript is a high-level, interpreted, dynamically typed programming language used for web
development. It supports both client-side scripting in web browsers and server-side development.
Its syntax is influenced by C, C++, and Java. JavaScript is flexible, object-based, and prototype-
oriented in nature.

2. Case Sensitivity
JavaScript is case-sensitive. Identifiers with different letter cases are treated as different variables.
Example:
let name = "Ali";
let Name = "Ahmed";
Here, name and Name are different variables.

3. C-Style Syntax
JavaScript follows C-style syntax rules:
• Statements typically end with semicolons (;).
• Code blocks are enclosed within curly braces { }.
• Parentheses ( ) are used in conditions and function definitions.

Edurile College of Management Studies Notes By:SM Page 1


II BCA WT: UNIT 2 - Java Script Dept. : BCA

Example:
if (age > 18) {
[Link]("Adult");
}

4. Statements and Semicolons


A JavaScript program consists of executable statements. Statements are generally separated by
semicolons. Although semicolons are optional because of Automatic Semicolon Insertion (ASI),
using them is recommended to avoid errors and improve readability.
Example:
let x = 10;
let y = 20;

5. Blocks of Code
A block is a group of statements enclosed within curly braces { }. Blocks are used in functions,
loops, and conditional statements.
Example:
{
let x = 5;
[Link](x);
}

6. Variable Declarations
JavaScript provides three keywords for declaring variables:
var – Function-scoped
let – Block-scoped
const – Block-scoped and cannot be reassigned
Example:
let age = 21;
const PI = 3.14;
var city = "New York";

7. Dynamic Typing
JavaScript is dynamically typed, meaning that variable data types are determined at runtime and
can change during execution.
Example:
let value = 10;
value = "Hello";
The variable changes from a number to a string.

8. Identifiers
Identifiers are names used for variables, functions, arrays, and objects.
Rules for identifiers:
• Must begin with a letter, underscore (_) or dollar sign ($).
• Cannot begin with a number.
• Cannot use reserved keywords.

Edurile College of Management Studies Notes By:SM Page 2


II BCA WT: UNIT 2 - Java Script Dept. : BCA

• JavaScript is case-sensitive.
Valid examples:
let studentName;
let _totalMarks;
let $price;

9. Comments
Comments are used to explain code and are ignored during execution.
Single-line comment:
// This is a comment
Multi-line comment:
/* This is
a multi-line comment */

10. Expressions and Operators


An expression is a combination of values, variables, and operators that produces a result.
Example:
let sum = 5 + 3;
JavaScript supports arithmetic, comparison, logical, assignment, and ternary operators.
Example of ternary operator:
let result = (age >= 18) ? "Adult" : "Minor";

11. Functions as First-Class Objects


In JavaScript, functions are treated as first-class objects. This means:
• Functions can be assigned to variables.
• Functions can be passed as arguments.
• Functions can be returned from other functions.
Example:
function greet() {
return "Hello";
}
let sayHello = greet;

12. Object-Based and Prototype-Based Nature


JavaScript is object-based and uses prototype-based inheritance rather than classical inheritance.
Objects store data in key–value pairs.
Example:
let person = {
name: "Ali",
greet: function() {
[Link]("Hello");
}
};

13. Equality Operators


JavaScript provides two types of equality comparison:

Edurile College of Management Studies Notes By:SM Page 3


II BCA WT: UNIT 2 - Java Script Dept. : BCA

== (Loose equality – performs type conversion before comparison)


=== (Strict equality – compares both value and type)
Example:
5 == "5" // true
5 === "5" // false

14. Automatic Type Conversion (Type Coercion)


JavaScript automatically converts data types when required in operations.
Example:
"5" + 2 // "52"
"5" - 2 // 3

15. Hoisting
Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their
scope during compilation.
Example:
[Link](x);
var x = 5;
Variables declared with let and const behave differently from var during hoisting.

16. Strict Mode


Strict mode enables stricter parsing and error handling in JavaScript. It is activated by writing:
"use strict";
Advantages of strict mode:
• Prevents accidental global variables
• Detects common coding mistakes
• Improves code reliability and security

PRIMITIVE DATA TYPES IN JAVASCRIPT

1. Introduction to Primitive Data Types


In JavaScript, a primitive data type is a basic data type that stores a single value. Primitive
values are immutable, which means their value cannot be changed after creation. Any
modification results in a new value being created. Primitive data types are the fundamental
building blocks of JavaScript programs.

JavaScript provides seven primitive data types.

Characteristics of Primitive Data Types


• They store a single simple value.
• They are immutable in nature.
• They are compared by value, not by reference.
• They are stored directly in memory (stack memory).

Edurile College of Management Studies Notes By:SM Page 4


II BCA WT: UNIT 2 - Java Script Dept. : BCA

Example:
let a = 10;
let b = a;
b = 20;
Here, changing b does not affect a because primitives are copied by value.

Types of Primitive Data Types in JavaScript

JavaScript has seven primitive data types:

1. String
2. Number
3. Boolean
4. Undefined
5. Null
6. BigInt
7. Symbol

Each is explained below.

1 String
A String represents textual data. Strings are written inside single quotes (' '), double quotes ("
"), or backticks ( ).

Example:
let name = "Ali";
let message = 'Hello World';

Strings are immutable. Any operation performed on a string returns a new string instead of
modifying the original.

Example:
let text = "Hello";
text = text + " Student";

2. Number
The Number data type represents numeric values. JavaScript does not distinguish between
integers and floating-point numbers.

Example:
let age = 21;
let price = 99.99;

Special numeric values in JavaScript include:


• Infinity

Edurile College of Management Studies Notes By:SM Page 5


II BCA WT: UNIT 2 - Java Script Dept. : BCA

• -Infinity
• NaN (Not a Number)

Example:
let result = 10 / 0; // Infinity
let value = "abc" / 2; // NaN

3. Boolean
A Boolean represents logical values. It can have only two values: true or false.

Booleans are commonly used in conditional statements.

Example:
let isStudent = true;
let isLoggedIn = false;

Example in condition:
if (isStudent) {
[Link]("Access granted");
}

4 Undefined
Undefined represents a variable that has been declared but has not been assigned a value.

Example:
let x;
[Link](x); // undefined

Undefined is automatically assigned by JavaScript when a variable is declared but not


initialized.

5. Null
Null represents the intentional absence of a value. It is assigned manually by the
programmer.

Example:
let data = null;

Difference between null and undefined:


• undefined means a variable has not been assigned a value.
• null means an empty or unknown value assigned intentionally.

6 BigInt
BigInt is used to represent very large integers beyond the safe integer limit of the Number
type.

Edurile College of Management Studies Notes By:SM Page 6


II BCA WT: UNIT 2 - Java Script Dept. : BCA

It is written by adding n at the end of a number.

Example:
let bigNumber = 123456789012345678901234567890n;

BigInt is useful when working with very large numerical values.

7. Symbol
Symbol is a primitive data type used to create unique identifiers. Each Symbol value is
unique, even if they have the same description.

Example:
let id1 = Symbol("id");
let id2 = Symbol("id");

Even though both symbols have the same description, they are different.

Symbols are mainly used as unique object property keys.

Immutability of Primitive Types


Primitive values cannot be changed directly. Instead, when a change appears to occur, a new
value is created.

Example:
let message = "Hello";
message[0] = "H"; // Does not change original string

This shows that primitives are immutable.

Comparison of Primitive Values


Primitive values are compared by value.

Example:
let a = 5;
let b = 5;
[Link](a === b); // true

Since both store the same value, they are equal.

Conclusion
Primitive data types in JavaScript are the most basic types used to store simple values. They
include String, Number, Boolean, Undefined, Null, BigInt, and Symbol. Primitive values are
immutable, stored by value, and form the foundation of JavaScript programming.
Understanding primitives is essential for writing efficient and error-free JavaScript code.

Edurile College of Management Studies Notes By:SM Page 7


II BCA WT: UNIT 2 - Java Script Dept. : BCA

SIMPLE JAVASCRIPT PROGRAM (DIRECT EXECUTION)


1. Hello World Program (Direct Output on Webpage)
<!DOCTYPE html>
<html>
<head>
<title>Hello Program</title>
</head>
<body>

<h2>JavaScript Hello World</h2>


<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>

2. Addition of Two Numbers (Direct Output)


<!DOCTYPE html>
<html>
<head>
<title>Addition Program</title>
</head>
<body>

<h2>Addition of Two Numbers</h2>

<p id="result"></p>

<script>
let num1 = 10;
let num2 = 20;
let sum = num1 + num2;

[Link]("result").innerHTML = "Sum is: " + sum;


</script>
</body>
</html>

Edurile College of Management Studies Notes By:SM Page 8


II BCA WT: UNIT 2 - Java Script Dept. : BCA

3. Even or Odd Program (Using Button Click)

<!DOCTYPE html>
<html>
<head>
<title>Even or Odd</title>
</head>
<body>

<h2>Check Even or Odd</h2>

<input type="number" id="number">


<button onclick="checkNumber()">Check</button>

<p id="output"></p>

<script>
function checkNumber() {
let num = [Link]("number").value;

if (num % 2 == 0) {
[Link]("output").innerHTML = "Even Number";
} else {
[Link]("output").innerHTML = "Odd Number";
}
}
</script>

</body>
</html>

OPERATIONS, EXPRESSIONS, AND CONTROL STRUCTURES IN JAVASCRIPT

1. OPERATORS IN JAVASCRIPT
Operators are symbols used to perform operations on values and variables. They are the
foundation of JavaScript programming.

1.1 Arithmetic Operators


Used for mathematical calculations. Examples: +, -, *, /, %, ++, --.

Edurile College of Management Studies Notes By:SM Page 9


II BCA WT: UNIT 2 - Java Script Dept. : BCA

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operators Example</title>
</head>
<body>
<h2>Arithmetic Operators Demo</h2>
<script>
let a = 10;
let b = 3;

[Link]("Addition: " + (a + b) + "<br>"); // 13


[Link]("Subtraction: " + (a - b) + "<br>"); // 7
[Link]("Multiplication: " + (a * b) + "<br>");// 30
[Link]("Division: " + (a / b) + "<br>"); // 3.3333
[Link]("Modulus: " + (a % b) + "<br>"); // 1
a++;
[Link]("Increment: " + a + "<br>"); // 11
b--;
[Link]("Decrement: " + b + "<br>"); // 2
</script>
</body>
</html>

Explanation Notes:
Arithmetic operators perform basic calculations. ++ increments the value by 1, -- decrements
by 1. These are essential for counters and calculations in programs.

1.2 Comparison Operators


Used to compare two values and return true or false. Examples: ==, ===, !=, !==, >, <, >=,
<=.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Comparison Operators Example</title>
</head>
<body>
<h2>Comparison Operators Demo</h2>
<script>
let x = 10;
let y = '10';

Edurile College of Management Studies Notes By:SM Page 10


II BCA WT: UNIT 2 - Java Script Dept. : BCA

[Link]("x == y: " + (x == y) + "<br>"); // true


[Link]("x === y: " + (x === y) + "<br>"); // false
[Link]("x != 5: " + (x != 5) + "<br>"); // true
[Link]("x > 5: " + (x > 5) + "<br>"); // true
[Link]("x <= 10: " + (x <= 10) + "<br>"); // true
</script>
</body>
</html>

Explanation Notes:
Comparison operators are used in decision-making. == checks value only, === checks value
and type. Useful in conditional statements.

1.3 Logical Operators


Used to combine Boolean expressions: && (AND), || (OR), ! (NOT).

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Logical Operators Example</title>
</head>
<body>
<h2>Logical Operators Demo</h2>
<script>
let a = true;
let b = false;

[Link]("a && b: " + (a && b) + "<br>"); // false


[Link]("a || b: " + (a || b) + "<br>"); // true
[Link]("!a: " + (!a) + "<br>"); // false
</script>
</body>
</html>

Explanation Notes:
Logical operators are used to combine multiple conditions in control statements, essential for
complex decision-making.

2. EXPRESSIONS IN JAVASCRIPT
Expressions are combinations of values, variables, and operators that evaluate to a value.

HTML Program Example:

Edurile College of Management Studies Notes By:SM Page 11


II BCA WT: UNIT 2 - Java Script Dept. : BCA

<!DOCTYPE html>
<html>
<head>
<title>Expressions Example</title>
</head>
<body>
<h2>Expressions Demo</h2>
<script>
let x = 5;
let y = 10;
let result = (x + y) * 2;

[Link]("Result of (x + y) * 2: " + result + "<br>"); // 30


</script>
</body>
</html>

Explanation Notes:
Expressions compute a value. (x + y) * 2 evaluates first x + y, then multiplies the sum by 2.
Used wherever JavaScript expects a value.

3. CONTROL STRUCTURES IN JAVASCRIPT


Control structures guide program flow through decisions and loops.

3.1 Conditional Statements

3.1.1 If Statement
Executes code if a condition is true.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>If Statement Example</title>
</head>
<body>
<h2>If Statement Demo</h2>
<script>
let score = 75;
if(score >= 50){
[Link]("Pass<br>");
}
</script>
</body>
</html>

Edurile College of Management Studies Notes By:SM Page 12


II BCA WT: UNIT 2 - Java Script Dept. : BCA

Explanation Notes:
Runs code only when the condition is true.

3.1.2 If-Else Statement


Executes one block if true, another if false.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>If-Else Example</title>
</head>
<body>
<h2>If-Else Demo</h2>
<script>
let score = 40;
if(score >= 50){
[Link]("Pass<br>");
} else {
[Link]("Fail<br>");
}
</script>
</body>
</html>

Explanation Notes:
Provides two possible paths: true executes if block, false executes else.

3.1.3 Else-If Ladder


Checks multiple conditions in sequence.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Else-If Example</title>
</head>
<body>
<h2>Else-If Ladder Demo</h2>
<script>
let marks = 85;
if(marks >= 90){
[Link]("A+<br>");
} else if(marks >= 75){

Edurile College of Management Studies Notes By:SM Page 13


II BCA WT: UNIT 2 - Java Script Dept. : BCA

[Link]("A<br>");
} else if(marks >= 50){
[Link]("B<br>");
} else {
[Link]("Fail<br>");
}
</script>
</body>
</html>

Explanation Notes:
Evaluates conditions in order. First true condition executes; others are skipped.

3.2 Switch Statement


Selects a block of code based on a variable value.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Switch Statement Example</title>
</head>
<body>
<h2>Switch Statement Demo</h2>
<script>
let day = 3;
switch(day){
case 1:
[Link]("Monday<br>");
break;
case 2:
[Link]("Tuesday<br>");
break;
case 3:
[Link]("Wednesday<br>");
break;
default:
[Link]("Other Day<br>");
}
</script>
</body>
</html>

Explanation Notes:
Efficiently handles multiple discrete cases without nested if statements.

Edurile College of Management Studies Notes By:SM Page 14


II BCA WT: UNIT 2 - Java Script Dept. : BCA

3.3 Loops

3.3.1 For Loop


Repeats code a fixed number of times.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>For Loop Example</title>
</head>
<body>
<h2>For Loop Demo</h2>
<script>
for(let i = 1; i <= 5; i++){
[Link]("Count: " + i + "<br>");
}
</script>
</body>
</html>

3.3.2 While Loop


Repeats code while a condition is true.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>While Loop Example</title>
</head>
<body>
<h2>While Loop Demo</h2>
<script>
let i = 1;
while(i <= 5){
[Link]("Count: " + i + "<br>");
i++;
}
</script>
</body>
</html>

3.3.3 Do-While Loop


Executes code at least once, then checks condition.

Edurile College of Management Studies Notes By:SM Page 15


II BCA WT: UNIT 2 - Java Script Dept. : BCA

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Do-While Loop Example</title>
</head>
<body>
<h2>Do-While Loop Demo</h2>
<script>
let i = 1;
do{
[Link]("Count: " + i + "<br>");
i++;
} while(i <= 5);
</script>
</body>
</html>

Explanation Notes:
Loops automate repetitive tasks. for is used when iterations are known, while when based on
conditions, and do-while ensures execution at least once.

4. CONCLUSION

 Operators perform calculations and comparisons.


 Expressions evaluate to values.
 Control structures manage program flow using conditions and loops.
 Mastery of these concepts is essential for writing efficient and dynamic JavaScript
programs.

ERROR HANDLING IN JAVASCRIPT


Error handling allows a program to detect and respond to runtime errors without crashing.
JavaScript provides try, catch, finally, and throw to manage errors.

1. Try-Catch Block

 try: Contains code that may throw an error.


 catch: Handles the error if it occurs.
 finally (optional): Executes code regardless of error occurrence.
 throw: Manually generates an error.

HTML Program Example:

Edurile College of Management Studies Notes By:SM Page 16


II BCA WT: UNIT 2 - Java Script Dept. : BCA

<!DOCTYPE html>
<html>
<head>
<title>Error Handling Example</title>
<style>
body { font-family: Arial, sans-serif; }
h2 { color: #2E8B57; }
p { font-size: 16px; }
</style>
</head>
<body>
<h2>JavaScript Error Handling Demo</h2>
<script>
function divideNumbers(a, b){
try {
if(b === 0){
throw "Division by zero is not allowed!";
}
let result = a / b;
[Link]("Result: " + result + "<br>");
} catch(error) {
[Link]("Error: " + error + "<br>");
} finally {
[Link]("Execution completed.<br>");
}
}

// Test the function


divideNumbers(10, 2); // Valid division
divideNumbers(10, 0); // Error division
</script>
</body>
</html>

Explanation Notes:

 The divideNumbers function checks if the denominator is 0.


 throw is used to generate a custom error message.
 try executes the risky code, catch handles the error gracefully.
 finally executes regardless of error, useful for cleanup or final messages.
 Output:

Result: 5
Execution completed.
Error: Division by zero is not allowed!
Execution completed.

Edurile College of Management Studies Notes By:SM Page 17


II BCA WT: UNIT 2 - Java Script Dept. : BCA

USER-DEFINED FUNCTIONS IN JAVASCRIPT


Functions are reusable blocks of code designed to perform a specific task. User-defined
functions are created by the programmer to organize code and avoid repetition.

Key Points:

 Defined using the function keyword.


 Can accept parameters and return values.
 Helps make code modular and readable.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>User Defined Function Example</title>
<style>
body { font-family: Arial, sans-serif; }
h2 { color: #1E90FF; }
p { font-size: 16px; }
</style>
</head>
<body>
<h2>User-Defined Function Demo</h2>
<script>
// Function to calculate square of a number
function square(number){
return number * number;
}

// Function to greet user


function greet(name){
return "Hello, " + name + "!";
}

// Using the functions


let num = 5;
[Link]("Square of " + num + " is " + square(num) + "<br>");
[Link](greet("Student") + "<br>");
</script>
</body>
</html>

Explanation Notes:

Edurile College of Management Studies Notes By:SM Page 18


II BCA WT: UNIT 2 - Java Script Dept. : BCA

 square and greet are user-defined functions.


 Functions take inputs (parameters) and return results using return.
 Calling a function with arguments executes the reusable code.
 Output example:

Square of 5 is 25
Hello, Student!

NOTE :
Use user-defined functions to simplify complex programs. Functions can be called multiple
times with different arguments, reducing code repetition.

EVENT HANDLING IN JAVASCRIPT


Event handling allows JavaScript to respond to user actions, like clicks, typing, mouse
movements, or form submissions.

Key Points:

 Use HTML attributes (onclick, onmouseover) or addEventListener in JS.


 Functions called in response to events are called event handlers.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
<style>
body { font-family: Arial, sans-serif; }
h2 { color: #FF4500; }
button { padding: 10px 15px; font-size: 16px; margin: 5px; cursor: pointer; }
p { font-size: 16px; }
</style>
</head>
<body>
<h2>Event Handling Demo</h2>
<button id="clickBtn">Click Me</button>
<p id="message"></p>

<script>
// Function to handle button click
function displayMessage(){
[Link]("message").innerText = "Button was clicked!";
}

Edurile College of Management Studies Notes By:SM Page 19


II BCA WT: UNIT 2 - Java Script Dept. : BCA

// Adding event listener


[Link]("clickBtn").addEventListener("click", displayMessage);
</script>
</body>
</html>

Explanation Notes:

 displayMessage is the event handler function.


 addEventListener("click", displayMessage) links the button click to the function.
 When the user clicks the button, the message updates dynamically.
 Event handling makes web pages interactive and responsive.

DOCUMENT OBJECT MODEL (DOM) IN JAVASCRIPT


The DOM allows JavaScript to access and modify HTML elements dynamically. It
represents the web page as a tree of objects.

Key Points:

 Use DOM to change content or style of elements.


 Common methods: getElementById, innerText, style.
 Works with events to make pages interactive.

Simple HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Simple DOM Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; } /* Big font */
button { font-size: 18pt; padding: 10px 15px; margin: 10px; cursor: pointer; }
</style>
</head>
<body>
<p id="demo">Click the button to change this text.</p>
<button onclick="changeText()">Click Me</button>

<script>
function changeText() {
[Link]("demo").innerText = "Text updated using DOM!";
}
</script>

Edurile College of Management Studies Notes By:SM Page 20


II BCA WT: UNIT 2 - Java Script Dept. : BCA

</body>
</html>

Explanation Notes:

 [Link]("demo") accesses the paragraph element.


 innerText changes its text content.
 Clicking the button triggers the changeText() function.
 Simple DOM manipulation allows dynamic content updates without reloading the
page.

NOTE :
The DOM is essential for interactive web pages. Even with a simple program, you can
change text, styles, or respond to user actions, making the page dynamic.

DOM MANIPULATION IN JAVASCRIPT


The Document Object Model (DOM) represents an HTML page as a tree structure where
each HTML element is a node. JavaScript can access, modify, and manipulate these nodes.

1. TREE STRUCTURE IN DOM


The DOM represents an HTML document as a hierarchy of nodes:

 Root node: document


 Parent nodes: <html>, <body>
 Child nodes: headings, paragraphs, buttons, etc.
 Sibling nodes: elements at the same level under a parent

HTML Program Example (Tree Structure):

<!DOCTYPE html>
<html>
<head>
<title>DOM Tree Structure Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
p { margin: 10px 0; }
</style>
</head>
<body>
<h2>DOM Tree Structure Demo</h2>
<p id="p1">Paragraph 1</p>
<p id="p2">Paragraph 2</p>
<p id="p3">Paragraph 3</p>

Edurile College of Management Studies Notes By:SM Page 21


II BCA WT: UNIT 2 - Java Script Dept. : BCA

<script>
// Access the body element
const bodyNode = [Link];
[Link]("Number of child nodes in body: " + [Link] +
"<br>");

// Access specific child nodes


[Link]("First child node: " + [Link] + "<br>");
[Link]("Last child node: " + [Link] + "<br>");
</script>
</body>
</html>

Explanation Notes:

 [Link] accesses the <body> node.


 childNodes lists all child nodes including text and element nodes.
 firstChild and lastChild return the first and last nodes under a parent.
 Understanding tree structure helps navigate between parent, child, and sibling
nodes.

NOTE :
Tree structure is essential for navigating and manipulating elements in a hierarchical
manner. You can access any element relative to its parent or sibling.

2. SELECTING ELEMENTS: getElementById


getElementById selects a unique element by its id.

HTML Program Example (getElementById):

<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
button { font-size: 18pt; padding: 10px 15px; margin-top: 10px; cursor: pointer; }
</style>
</head>
<body>
<p id="demo1">This text will change using getElementById.</p>
<button onclick="changeText()">Change Text</button>

Edurile College of Management Studies Notes By:SM Page 22


II BCA WT: UNIT 2 - Java Script Dept. : BCA

<script>
function changeText() {
// Select element by ID
const para = [Link]("demo1");
[Link] = "Text updated using getElementById!";
}
</script>
</body>
</html>

Explanation Notes:

 [Link]("demo1") accesses the element with id demo1.


 innerText changes its content dynamically.
 Useful for selecting single, unique elements.

NOTE :
Always use getElementById for elements with unique ids. It is fast and straightforward for
direct element manipulation.

3. SELECTING ELEMENTS: querySelector


querySelector selects the first element that matches a CSS selector. Can select by id, class,
or tag.

HTML Program Example (querySelector):

<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
button { font-size: 18pt; padding: 10px 15px; margin-top: 10px; cursor: pointer; }
p { color: #2F4F4F; }
</style>
</head>
<body>
<p class="para">This text will change using querySelector.</p>
<button onclick="changeText()">Change Text</button>

Edurile College of Management Studies Notes By:SM Page 23


II BCA WT: UNIT 2 - Java Script Dept. : BCA

<script>
function changeText() {
// Select first element with class 'para'
const para = [Link](".para");
[Link] = "Text updated using querySelector!";
}
</script>
</body>
</html>

Explanation Notes:

 [Link](".para") selects first element with class para.


 Supports CSS selectors: .class, #id, tag.
 More flexible than getElementById but only selects the first matching element.

NOTE :
querySelector is useful when selecting elements using CSS-like selectors. It works with ids,
classes, tags, or even complex nested selectors.

OBJECTS AND FUNCTIONS IN JAVASCRIPT: DOCUMENT, WINDOW,


CONSOLE

JavaScript is an object-oriented language, and many predefined objects are available to


interact with the browser and the page. Among the most important are: document, window,
and console. These objects provide properties and methods to access, manipulate, and
control web pages dynamically.

1. DOCUMENT OBJECT
Definition: The document object represents the entire HTML document loaded in the
browser. It is part of the DOM (Document Object Model) and provides access to all
elements, content, and structure of the page.

Detailed Explanation:

 The document object is the primary interface between JavaScript and the HTML
page.
 It allows developers to read and change content, attributes, and styles dynamically
without reloading the page.
 Using the document object, you can select elements, modify text or HTML, add or
remove elements, and handle events.
 Common use cases include:

Edurile College of Management Studies Notes By:SM Page 24


II BCA WT: UNIT 2 - Java Script Dept. : BCA

o Changing headings or paragraphs dynamically.


o Updating form values or validation messages.
o Modifying page title or content based on user actions.

Key Properties:

 [Link] → Get/set the page title.


 [Link] → Access the <body> element.

Key Methods:

 getElementById("id") → Selects a unique element by its ID.


 querySelector("selector") → Selects the first element matching a CSS selector.
 write() → Writes HTML content directly to the document (mainly for testing).

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Document Object Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
button { font-size: 18pt; padding: 10px 15px; margin: 10px; cursor: pointer; }
</style>
</head>
<body>
<h2>Document Object Demo</h2>
<p id="para">Original Paragraph Text</p>
<button onclick="changeTitle()">Change Page Title</button>
<button onclick="updateText()">Update Paragraph Text</button>

<script>
function changeTitle() {
[Link] = "Title Updated Using Document Object";
}

function updateText() {
[Link]("para").innerText = "Paragraph updated using document
object!";
}
</script>
</body>
</html>

Explanation Notes:

Edurile College of Management Studies Notes By:SM Page 25


II BCA WT: UNIT 2 - Java Script Dept. : BCA

 [Link] changes the browser tab title.


 getElementById() selects a specific element to change content dynamically.
 document is essential for DOM-based manipulation in NEA projects.

2. WINDOW OBJECT
Definition: The window object represents the browser window and is the global object in
JavaScript. Every global variable or function is a property or method of the window object.

Detailed Explanation:

 The window object is the top-level object in JavaScript running in the browser.
 It provides control over the browser environment including popups, screen size,
navigation, and timing functions.
 Common use cases include:
o Displaying alerts and confirmation dialogs.
o Taking user input dynamically using prompts.
o Accessing viewport size for responsive designs.
o Controlling navigation or opening new browser windows.

Key Properties:

 [Link] → Width of the browser viewport.


 [Link] → Height of the browser viewport.

Key Methods:

 alert(message) → Displays a popup alert.


 confirm(message) → Shows a popup with OK/Cancel and returns true/false.
 prompt(message) → Shows a popup for user input.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Window Object Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
button { font-size: 18pt; padding: 10px 15px; margin: 10px; cursor: pointer; }
</style>
</head>
<body>
<h2>Window Object Demo</h2>
<button onclick="showAlert()">Show Alert</button>

Edurile College of Management Studies Notes By:SM Page 26


II BCA WT: UNIT 2 - Java Script Dept. : BCA

<button onclick="askConfirmation()">Confirm Action</button>


<button onclick="askPrompt()">Input Your Name</button>
<p id="info"></p>

<script>
function showAlert() {
[Link]("Hello! This is an alert using window object.");
}

function askConfirmation() {
const result = [Link]("Do you want to continue?");
[Link]("info").innerText = "Confirmation result: " + result;
}

function askPrompt() {
const name = [Link]("Enter your name:");
[Link]("info").innerText = "Hello, " + name + "!";
}
</script>
</body>
</html>

Explanation Notes:

 Alerts, confirmation boxes, and prompts are simple ways to interact with users.
 The window object allows control over the environment in which the webpage
runs.
 All global functions like alert(), prompt() are part of window.

3. CONSOLE OBJECT
Definition: The console object is used for logging and debugging. It allows developers to
inspect variables, display errors, and test code in the browser console.

Detailed Explanation:

 The console object is not visible to users, only accessible in developer tools.
 It is essential for NEA development to test and debug code before displaying results
on the page.
 Common use cases include:
o Tracking variable values during program execution.
o Showing warnings for potential issues.
o Logging errors to investigate problems.
o Displaying arrays or objects neatly for easier inspection.

Edurile College of Management Studies Notes By:SM Page 27


II BCA WT: UNIT 2 - Java Script Dept. : BCA

Key Methods:

 [Link]() → General information.


 [Link]() → Warning messages.
 [Link]() → Error messages.
 [Link]() → Display arrays or objects in a table format.

HTML Program Example:

<!DOCTYPE html>
<html>
<head>
<title>Console Object Example</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
button { font-size: 18pt; padding: 10px 15px; margin: 10px; cursor: pointer; }
</style>
</head>
<body>
<h2>Console Object Demo</h2>
<button onclick="logInfo()">Log Info</button>
<button onclick="showWarning()">Show Warning</button>
<button onclick="showError()">Show Error</button>

<script>
function logInfo() {
[Link]("This is a console log message.");
}

function showWarning() {
[Link]("This is a console warning!");
}

function showError() {
[Link]("This is a console error!");
}

const students = [
{ name: "Alice", marks: 85 },
{ name: "Bob", marks: 78 },
{ name: "Charlie", marks: 92 }
];
[Link](students);
</script>
</body>
</html>

Edurile College of Management Studies Notes By:SM Page 28


II BCA WT: UNIT 2 - Java Script Dept. : BCA

Explanation Notes:

 [Link]() is for general debugging.


 [Link]() highlights potential issues.
 [Link]() highlights errors in code.
 [Link]() is excellent for visualizing structured data like arrays or objects.

NOTE:
The console object is a powerful tool for debugging and testing code without affecting the
user interface. It is essential for NEA coding and problem-solving.

Summary of Objects and Functions Notes:

 Document Object: Access and manipulate HTML elements dynamically.


 Window Object: Control browser-level behavior like popups, screen size, and user
input.
 Console Object: Debug, test, and inspect data in developer console.
 These objects are core building blocks for interactive, dynamic web pages and NEA
projects.

OBJECTS AND FUNCTIONS IN JAVASCRIPT: DOCUMENT, WINDOW,


CONSOLE

JavaScript provides predefined objects to interact with the web page, browser, and
developer console. The most important objects are:

1. DOCUMENT OBJECT
Definition: Represents the HTML page. Allows accessing and modifying page content and
structure.

Key Properties:

 [Link] → Gets/sets page title.


 [Link] → Accesses <body> element.

Key Functions:

 getElementById("id") → Select a unique element.


 querySelector("selector") → Select the first element matching CSS selector.
 write() → Writes content directly to the page.

Use: Changing headings, paragraphs, and page content dynamically.

Edurile College of Management Studies Notes By:SM Page 29


II BCA WT: UNIT 2 - Java Script Dept. : BCA

2. WINDOW OBJECT
Definition: Represents the browser window. It is the global object in JavaScript.

Key Properties:

 [Link] → Browser viewport width.


 [Link] → Browser viewport height.

Key Functions:

 alert("message") → Shows popup alert.


 confirm("message") → Shows OK/Cancel dialog.
 prompt("message") → Gets input from user.

Use: Popups, input collection, viewport control, browser-level interaction.

3. CONSOLE OBJECT
Definition: Used for debugging and logging messages in the developer console.

Key Functions:

 [Link]() → General messages.


 [Link]() → Warnings.
 [Link]() → Errors.
 [Link]() → Display arrays/objects in table format.

Use: Inspect variables, debug code, test arrays or objects.

Complete HTML Program Demonstrating Document, Window, Console Objects:

<!DOCTYPE html>
<html>
<head>
<title>Objects Demo</title>
<style>
body { font-family: Arial, sans-serif; font-size: 20pt; }
button { font-size: 18pt; padding: 10px 15px; margin: 10px;
cursor: pointer; }
p { color: #2F4F4F; }

Edurile College of Management Studies Notes By:SM Page 30


II BCA WT: UNIT 2 - Java Script Dept. : BCA
</style>
</head>
<body>
<h2>Document, Window, and Console Demo</h2>
<p id="docPara">Original paragraph text.</p>
<p id="windowInfo"></p>
<p id="consoleOutput"></p>

<button onclick="updateDocument()">Document</button>
<button onclick="useWindow()">Window</button>
<button onclick="useConsole()">Console</button>

<script>
// Document object
function updateDocument() {
[Link] = "Document Updated!";
[Link]("docPara").innerText = "Text
updated using document object.";
}

// Window object
function useWindow() {
alert("Hello! This is a window alert.");
const name = prompt("Enter your name:");
[Link]("windowInfo").innerText =
"Hello, " + name + "!";
}

// Console object
function useConsole() {
const output = [];
[Link]("Console log message");
[Link]("Console warning!");
[Link]("Console error!");
const students = [{name:"Alice", marks:85},{name:"Bob",
marks:78}];
[Link]("Students Table: " +
[Link](students));

// Show output on page


[Link]("consoleOutput").innerText =
[Link]("\n");

// Also log in console for developer


[Link]("Console log message");
[Link]("Console warning!");
[Link]("Console error!");
[Link](students);
}
</script>
</body>

Edurile College of Management Studies Notes By:SM Page 31


II BCA WT: UNIT 2 - Java Script Dept. : BCA
</html>

Explanation Notes:

1. Document Object:
o [Link] changes the browser tab title.
o getElementById() modifies paragraph content dynamically.
2. Window Object:
o alert() shows a popup.
o prompt() takes user input.
o innerWidth and innerHeight get browser viewport size.
3. Console Object:
o [Link](), [Link](), [Link]() display messages in
developer tools.
o [Link]() shows arrays in table format.

Note:

 Use document to access and change HTML content.


 Use window for browser-level interaction and user input.
 Use console for debugging and inspecting data.
 Mastering these objects is essential for NEA projects and interactive web pages.

FRAMEWORKS INTRODUCTION: [Link] & NPM

JavaScript is not only for frontend (browser) development but can also be used for backend
(server-side) programming using [Link]. NPM (Node Package Manager) works with
[Link] to manage libraries and packages, making development faster and easier.

1. [Link]
Definition: [Link] is a JavaScript runtime built on Chrome’s V8 engine that allows
JavaScript to run outside the browser, mainly for server-side development.

Key Features:

 Event-driven & Non-blocking: Handles multiple requests efficiently.


 Server-side JavaScript: Can create web servers, APIs, and handle file operations.
 Fast Execution: Powered by V8 engine, ideal for real-time applications.
 Single Language: JavaScript for both frontend and backend.

Advantages:

 Fast and scalable.

Edurile College of Management Studies Notes By:SM Page 32


II BCA WT: UNIT 2 - Java Script Dept. : BCA

 Large ecosystem with NPM packages.


 Real-time applications like chat apps, live updates, and games.

Example ([Link] HTTP Server):

const http = require('http');

const server = [Link]((req, res) => {


[Link](200, {'Content-Type': 'text/html'});
[Link]('<h1>Hello from [Link] Server!</h1>');
});

[Link](3000, () => {
[Link]('Server running at [Link]
});

Explanation Notes:

 require('http') → Imports HTTP module.


 createServer() → Handles client requests.
 [Link]() → Sends response to browser.
 listen(3000) → Runs server on port 3000.

2. NPM (NODE PACKAGE MANAGER)


Definition: NPM is the package manager for [Link]. It allows developers to install,
manage, and share JavaScript libraries.

Key Features:

 Comes pre-installed with [Link].


 Manages dependencies for projects.
 Allows global or local installation of packages.

Common Commands:

 npm init → Initialize a [Link] project.


 npm install package-name → Install a package locally.
 npm install -g package-name → Install globally.
 npm update → Update installed packages.

Example using Express (NPM package):

// Install express first: npm install express


const express = require('express');
const app = express();

[Link]('/', (req, res) => {

Edurile College of Management Studies Notes By:SM Page 33


II BCA WT: UNIT 2 - Java Script Dept. : BCA
[Link]('<h1>Hello from Express via [Link]!</h1>');
});

[Link](3000, () => {
[Link]('Server running at [Link]
});

Explanation Notes:

 express() → Creates Express application.


 [Link]() → Handles GET request to /.
 [Link]() → Sends response to client.
 listen(3000) → Server runs at port 3000.

Notes:

 [Link]: Enables backend JavaScript development.


 NPM: Manages libraries and dependencies for projects.
 Together: [Link] + NPM = full-stack JavaScript development.
 Practice: Start with a simple HTTP server and add NPM packages like Express to
handle routes easily.

💡 Tip: [Link] programs run in terminal, not in browser HTML. To see output:

1. Open terminal.
2. Run node [Link] (or node [Link] for Express).
3. Open browser at [Link]

Edurile College of Management Studies Notes By:SM Page 34

You might also like