WT U2 JavaScript
WT U2 JavaScript
: BCA
JAVASCRIPT
1. Introduction to JavaScript
2. Features of JavaScript
Lightweight and interpreted
Object-oriented and prototype-based
Event-driven
Dynamically typed
Supports functional programming
Cross-platform
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.
Example:
if (age > 18) {
[Link]("Adult");
}
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.
• 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 */
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.
Example:
let a = 10;
let b = a;
b = 20;
Here, changing b does not affect a because primitives are copied by value.
1. String
2. Number
3. Boolean
4. Undefined
5. Null
6. BigInt
7. Symbol
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;
• -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.
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
5. Null
Null represents the intentional absence of a value. It is assigned manually by the
programmer.
Example:
let data = null;
6 BigInt
BigInt is used to represent very large integers beyond the safe integer limit of the Number
type.
Example:
let bigNumber = 123456789012345678901234567890n;
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.
Example:
let message = "Hello";
message[0] = "H"; // Does not change original string
Example:
let a = 5;
let b = 5;
[Link](a === b); // true
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.
<p id="result"></p>
<script>
let num1 = 10;
let num2 = 20;
let sum = num1 + num2;
<!DOCTYPE html>
<html>
<head>
<title>Even or Odd</title>
</head>
<body>
<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>
1. OPERATORS IN JAVASCRIPT
Operators are symbols used to perform operations on values and variables. They are the
foundation of JavaScript programming.
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operators Example</title>
</head>
<body>
<h2>Arithmetic Operators Demo</h2>
<script>
let a = 10;
let b = 3;
Explanation Notes:
Arithmetic operators perform basic calculations. ++ increments the value by 1, -- decrements
by 1. These are essential for counters and calculations in programs.
<!DOCTYPE html>
<html>
<head>
<title>Comparison Operators Example</title>
</head>
<body>
<h2>Comparison Operators Demo</h2>
<script>
let x = 10;
let y = '10';
Explanation Notes:
Comparison operators are used in decision-making. == checks value only, === checks value
and type. Useful in conditional statements.
<!DOCTYPE html>
<html>
<head>
<title>Logical Operators Example</title>
</head>
<body>
<h2>Logical Operators Demo</h2>
<script>
let a = true;
let b = false;
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.
<!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;
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.1.1 If Statement
Executes code if a condition is true.
<!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>
Explanation Notes:
Runs code only when the condition is true.
<!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.
<!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){
[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.
<!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.
3.3 Loops
<!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>
<!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>
<!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
1. Try-Catch Block
<!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>");
}
}
Explanation Notes:
Result: 5
Execution completed.
Error: Division by zero is not allowed!
Execution completed.
Key Points:
<!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;
}
Explanation Notes:
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.
Key Points:
<!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!";
}
Explanation Notes:
Key Points:
<!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>
</body>
</html>
Explanation Notes:
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.
<!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>
<script>
// Access the body element
const bodyNode = [Link];
[Link]("Number of child nodes in body: " + [Link] +
"<br>");
Explanation Notes:
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.
<!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>
<script>
function changeText() {
// Select element by ID
const para = [Link]("demo1");
[Link] = "Text updated using getElementById!";
}
</script>
</body>
</html>
Explanation Notes:
NOTE :
Always use getElementById for elements with unique ids. It is fast and straightforward for
direct element manipulation.
<!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>
<script>
function changeText() {
// Select first element with class 'para'
const para = [Link](".para");
[Link] = "Text updated using querySelector!";
}
</script>
</body>
</html>
Explanation Notes:
NOTE :
querySelector is useful when selecting elements using CSS-like selectors. It works with ids,
classes, tags, or even complex nested selectors.
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:
Key Properties:
Key Methods:
<!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:
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:
Key Methods:
<!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>
<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.
Key Methods:
<!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>
Explanation Notes:
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.
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:
Key Functions:
2. WINDOW OBJECT
Definition: Represents the browser window. It is the global object in JavaScript.
Key Properties:
Key Functions:
3. CONSOLE OBJECT
Definition: Used for debugging and logging messages in the developer console.
Key Functions:
<!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; }
<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));
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:
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:
Advantages:
[Link](3000, () => {
[Link]('Server running at [Link]
});
Explanation Notes:
Key Features:
Common Commands:
[Link](3000, () => {
[Link]('Server running at [Link]
});
Explanation Notes:
Notes:
💡 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]