0% found this document useful (0 votes)
5 views11 pages

UNIT 3 &4 NOTES

The document outlines various aspects of JavaScript and TypeScript, including uses of JavaScript, variable declaration with const, and the structure of functions and arrays. It also explains JavaScript operators, Math and Date objects, non-primitive data types in TypeScript, and the concepts of modules and namespaces. Key features such as event bubbling, destructuring, and the differences between JavaScript and TypeScript are also discussed.

Uploaded by

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

UNIT 3 &4 NOTES

The document outlines various aspects of JavaScript and TypeScript, including uses of JavaScript, variable declaration with const, and the structure of functions and arrays. It also explains JavaScript operators, Math and Date objects, non-primitive data types in TypeScript, and the concepts of modules and namespaces. Key features such as event bubbling, destructuring, and the differences between JavaScript and TypeScript are also discussed.

Uploaded by

faziloffi786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Part A: 10 X 2 = 20 Marks

1 List some uses of javascript.


1. Web Development (Frontend and Backend):
o JavaScript is primarily used for building interactive and dynamic web pages. On
the frontend, it enables features like form validation, interactive maps,
animations, and responsive interfaces. With Node.js, it can also be used on the
backend for server-side scripting, allowing for full-stack development with a
single language.
2. Mobile Application Development:
o JavaScript is used in frameworks like React Native and Ionic to build cross-
platform mobile applications. This allows developers to write code once and
deploy it on both Android and iOS platforms, reducing development time and
effort.
2 When to use javascript const?
1. When a Variable's Value Should Not Change:
o Use const to declare variables whose values should remain constant throughout
the execution of the program. Once a value is assigned to a const variable, it
cannot be reassigned.
2. For Immutable References:

o While const ensures the variable reference cannot change, it does not make
objects or arrays immutable. It only prevents reassigning the variable itself to a
new value, but the contents of an object or array declared with const can still be
modified
3 Write the program for how to let function return a value
function add(a, b) {
return a + b; // The function returns the sum of a and b
}

let result = add(3, 4); // Calling the function with 3 and 4 as arguments
console.log(result); // Output: 7
4 Define javascript Array object.
In JavaScript, an Array is a built-in object that allows you to store multiple values in a single
variable. It is a collection of ordered elements, which can be of any type (numbers, strings,
objects, etc.). Arrays are zero-indexed, meaning the first element is at index 0.
5 What is Event Bubbling?
Event Bubbling is a concept in JavaScript where an event triggered on an element (e.g., a button
or a div) is first handled by that element and then propagates (or "bubbles up") through its
ancestor elements in the DOM hierarchy, all the way up to the root (usually the document or
window object).In simpler terms, when an event is triggered on an element, it doesn't just stay
with that element. The event "bubbles" up to its parent, then to the parent's parent, and so on.
This allows for event delegation, where you can set up event listeners on parent elements and
handle events for multiple child elements.
6 What are the features of javascript?
JavaScript is a powerful, flexible, and widely-used programming language primarily for web
development. It provides a range of features that make it highly versatile. Below are some key
features:
1. Interpreted Language:
o JavaScript is an interpreted language, meaning it doesn't need to be compiled
before execution. The browser or JavaScript engine directly interprets and runs
the code line by line.
2. Dynamic Typing:
o JavaScript is dynamically typed, meaning you don't need to declare the type of a
variable explicitly. The type of a variable is determined at runtime.
7 Differentiate javascript and typescript.

8 What is dectructing object?


Object Destructuring is a feature in JavaScript that allows you to unpack properties from an
object into distinct variables. This makes the process of extracting values from objects much
more concise and readable.
Syntax: const { property1, property2 } = object;

9 List down the non primitive datatypes of TS.


1. Object
2. Array
3. Function
4. Class
5. Interface
6. Tuple
7. Enum
8. Any
9. Unknown
10. Map
11. Set

10 Define Namespace .
A Namespace in TypeScript is a way to group related functionality, such as variables, functions, classes,
and interfaces, into a single logical unit. It helps to organize code and avoid naming conflicts by
encapsulating the code within a specific scope.

Part B: 2 X 13=26; 1X14=14=40 Marks


11 a Explain various types of javascript operators
JavaScript operators are symbols that perform operations on variables and values. They
can be classified into different types based on their functionality. Here are the main types
of JavaScript operators:
1. Arithmetic Operators (5 Marks)
These operators perform mathematical calculations:
 + (Addition) → 5 + 3 // 8
 - (Subtraction) → 5 - 3 // 2
 * (Multiplication) → 5 * 3 // 15
 / (Division) → 6 / 3 // 2
 % (Modulus) → 5 % 2 // 1 (Remainder of division)
 ** (Exponentiation) → 2 ** 3 // 8
 ++ (Increment) → let x = 5; x++ // 6
 -- (Decrement) → let y = 5; y-- // 4
2. Assignment Operators (2 Marks)
These operators assign values to variables:
 = (Assignment) → x = 10
 += (Addition Assignment) → x += 5 (Same as x = x + 5)
 -= (Subtraction Assignment) → x -= 5
 *= (Multiplication Assignment) → x *= 5
 /= (Division Assignment) → x /= 5
 %= (Modulus Assignment) → x %= 5
 **= (Exponentiation Assignment) → x **= 3
3. Comparison Operators (2 Marks)
These operators compare values and return true or false:
 == (Equal to) → 5 == "5" (true)
 === (Strict equal to) → 5 === "5" (false, checks type)
 != (Not equal to) → 5 != 3 (true)
 !== (Strict not equal) → 5 !== "5" (true)
 > (Greater than) → 5 > 3 (true)
 < (Less than) → 3 < 5 (true)
 >= (Greater than or equal to) → 5 >= 5 (true)
 <= (Less than or equal to) → 3 <= 5 (true)
4. Logical Operators (2 Marks)
These are used for logical operations:
 && (Logical AND) → true && false (false)
 || (Logical OR) → true || false (true)
 ! (Logical NOT) → !true (false)
5. Bitwise Operators (1 Mark)
These work on binary numbers:
 & (AND) → 5 & 1 (Result: 1)
 | (OR) → 5 | 1 (Result: 5)
 ^ (XOR) → 5 ^ 1 (Result: 4)
 ~ (NOT) → ~5 (Bitwise negation)
 << (Left shift) → 5 << 1 (Result: 10)
 >> (Right shift) → 5 >> 1 (Result: 2)
6. Ternary Operator (1 Mark)
A shorthand for if-else:
 condition ? value_if_true : value_if_false
 Example: let result = (5 > 3) ? "Yes" : "No"; // "Yes"
7. Type Operators (1 Mark)
These help determine the type of a variable:
 typeof → typeof 5 // "number"
 instanceof → [] instanceof Array // true
Each type of operator plays an essential role in JavaScript programming by enabling
different operations and logical expressions.

b Explain javascript math object and date object with example


JavaScript provides built-in objects for mathematical calculations and date/time manipulations:
1. Math Object (6 Marks)
The Math object allows mathematical operations and functions. It has properties and
methods to perform various calculations.

Math Properties (Constants)

 Math.PI → 3.141592653589793

 Math.E → Euler’s number (2.718)

Math Methods

Some commonly used Math methods:

 Math.abs(x) → Returns the absolute value


 console.log(Math.abs(-5)); // 5

 Math.round(x) → Rounds to the nearest integer


 console.log(Math.round(4.7)); // 5

 Math.ceil(x) → Rounds up
 console.log(Math.ceil(4.1)); // 5

 Math.floor(x) → Rounds down


 console.log(Math.floor(4.9)); // 4

 Math.sqrt(x) → Returns the square root


 console.log(Math.sqrt(25)); // 5

 Math.pow(x, y) → Returns x raised to the power y


 console.log(Math.pow(2, 3)); // 8

 Math.random() → Returns a random number between 0 and 1


 console.log(Math.random()); // Example: 0.5687

 Math.max(a, b, c...) → Returns the maximum number


 console.log(Math.max(10, 20, 5)); // 20

 Math.min(a, b, c...) → Returns the minimum number


 console.log(Math.min(10, 20, 5)); // 5

2. Date Object (7 Marks)


The Date object is used to work with dates and times.

Creating a Date Object

 Current Date & Time


 let now = new Date();
 console.log(now);
 Specific Date
 let customDate = new Date(2024, 3, 2); // April 2, 2024 (Months
are 0-indexed)
 console.log(customDate);

 String Format
 let dateStr = new Date("2024-04-02T10:00:00");
 console.log(dateStr);
Date Methods

 Get Methods (Retrieve Date Parts)

o getFullYear() → Gets the year


o console.log(now.getFullYear()); // 2024

o getMonth() → Gets the month (0-based)


o console.log(now.getMonth()); // 3 (April)

o getDate() → Gets the day of the month


o console.log(now.getDate()); // 2

o getDay() → Gets the day of the week (0 = Sunday)


o console.log(now.getDay()); // 2 (Tuesday)

o getHours(), getMinutes(), getSeconds(), getMilliseconds()


o console.log(now.getHours()); // 10
o console.log(now.getMinutes()); // 30
o console.log(now.getSeconds()); // 45

 Set Methods (Modify Date Values)

o setFullYear(year) → Sets the year


o now.setFullYear(2025);
o console.log(now);

o setMonth(month), setDate(day), setHours(h), setMinutes(m),


setSeconds(s)

 Date Formatting
 console.log(now.toDateString()); // "Tue Apr 02 2024"
 console.log(now.toISOString()); // "2024-04-02T10:00:00.000Z"
Date Calculations
let future = new Date();
future.setDate(future.getDate() + 7); // Adds 7 days
console.log(future);
12 a Explain non primitive data types of Typescript
In TypeScript, non-primitive data types are more complex than primitive types. They
include objects, arrays, functions, tuples, and classes.
1. Object (3 Marks)
An object is a collection of key-value pairs. It can store multiple values of different types.
Example:
let person: { name: string; age: number; isStudent: boolean } = {
name: "John",
age: 25,
isStudent: true
};

console.log(person.name); // "John"
 Objects can also have optional properties using ?:
let car: { brand: string; model?: string } = { brand: "Toyota" };
2. Array (3 Marks)
An array is a collection of elements of the same type. TypeScript provides strong typing
for arrays.
Example:
let numbers: number[] = [10, 20, 30];
let names: Array<string> = ["Alice", "Bob"];
Operations on Arrays:
numbers.push(40); // Adds an element
console.log(numbers.length); // 4
3. Tuple (2 Marks)
A tuple is a fixed-length array where each element has a specific type.
Example:
let employee: [string, number] = ["John", 25];
console.log(employee[0]); // "John"
console.log(employee[1]); // 25
 Tuples allow optional elements:
let data: [string, number?] = ["Alice"];
4. Function (2 Marks)
Functions in TypeScript have defined parameter and return types.
Example:
function add(a: number, b: number): number {
return a + b;
}

console.log(add(5, 10)); // 15
 Functions can also have optional parameters:
function greet(name: string, age?: number): string {
return age ? `Hello, ${name}, you are ${age} years old.` : `Hello, $
{name}`;
}
5. Class (3 Marks)
A class is a blueprint for creating objects. It supports encapsulation, inheritance, and
polymorphism.
Example:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}

makeSound(): void {
console.log(`${this.name} makes a sound`);
}
}

let dog = new Animal("Dog");


dog.makeSound(); // "Dog makes a sound"

b Describe details about modules and namespaces.


In TypeScript, Modules and Namespaces are used to organize and manage code
efficiently. Modules are preferred in modern TypeScript, while namespaces are used in
legacy code bases.
1. Modules (7 Marks)
Modules in TypeScript allow us to split code into multiple files, making it easier to
manage and reuse. TypeScript modules follow ES6 module syntax and can be
imported/exported between files.
Types of Modules:
1. Internal Modules – Old terminology for Namespaces.
2. External Modules – Modern TypeScript modules using import and export.
Exporting and Importing Modules:
 Export Example (math.ts):
 export function add(a: number, b: number): number {
 return a + b;
 }

 export const PI = 3.14;
 Import Example (app.ts):
 import { add, PI } from "./math";

 console.log(add(5, 10)); // 15
 console.log(PI); // 3.14
 Default Export (logger.ts):
 export default function logMessage(message: string): void {
 console.log("Log:", message);
 }
 Importing Default Export (app.ts):
 import logMessage from "./logger";

 logMessage("Hello TypeScript!"); // Log: Hello TypeScript!
Advantages of Modules:
✅ Code Reusability
✅ Encapsulation
✅ Better Maintainability
✅ Supports ES6 Imports
2. Namespaces (6 Marks)
Namespaces were used in older TypeScript versions to group related code together.
Unlike modules, namespaces are wrapped inside a single global object.
Creating a Namespace:
namespace MathOperations {
export function add(a: number, b: number): number {
return a + b;
}

export function subtract(a: number, b: number): number {


return a - b;
}
}

// Using Namespace
console.log(MathOperations.add(10, 5)); // 15
console.log(MathOperations.subtract(10, 5)); // 5
Nested Namespaces:
namespace Company {
export namespace HR {
export function getEmployeeCount(): number {
return 50;
}
}
}

console.log(Company.HR.getEmployeeCount()); // 50
Differences Between Modules and Namespaces
Feature Modules Namespaces
Usage Preferred in modern TypeScript Used in legacy TypeScript
Scope Works at file/module level Works at global level
Import Required? Yes (import/export) No (Global access)
Compatibility Works with JavaScript TypeScript-specific
13 a (i) How to pass variables to a function and use these variables values in the function
In TypeScript (or JavaScript), we can pass variables to a function as parameters. These
variables can then be used inside the function for processing.
1. Function with Parameters (3 Marks)
We define function parameters and pass values when calling the function.
Example:
function greet(name: string): void {
console.log("Hello, " + name);
}

greet("Alice"); // Output: Hello, Alice


Here, the function greet takes name as a parameter and prints a greeting.
2. Function with Multiple Parameters (2 Marks)
Functions can accept multiple arguments.
Example:
function add(a: number, b: number): number {
return a + b;
}

console.log(add(5, 10)); // Output: 15


 Here, a and b are parameters.
 5 and 10 are arguments passed to the function.
3. Using Default Parameters (1 Mark)
TypeScript allows default values for parameters.
Example:
function greetUser(name: string = "Guest"): void {
console.log(`Hello, ${name}`);
}

greetUser(); // Output: Hello, Guest


greetUser("Bob"); // Output: Hello, Bob
 If no argument is passed, Guest is used as the default value.
4. Using Optional Parameters (1 Mark)
Optional parameters are defined using ?.
Example:
function showInfo(name: string, age?: number): void {
if (age) {
console.log(`${name} is ${age} years old.`);
} else {
console.log(`${name}'s age is unknown.`);
}
}

showInfo("Alice", 25); // Output: Alice is 25 years old.


showInfo("Bob"); // Output: Bob's age is unknown.
(ii) How to write a for loop to run the same block of code a specified number of times.
A for loop in TypeScript (or JavaScript) is used to execute a block of code repeatedly for
a specified number of times. It consists of three parts:
1. Initialization → Declares and initializes a loop variable.
2. Condition → Checks if the loop should continue.
3. Increment/Decrement → Updates the loop variable.
1. Basic for Loop (3 Marks)
The simplest way to run a block of code multiple times.
Example:
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}
Explanation:
 let i = 1 → Initializes i with 1.
 i <= 5 → Runs while i is less than or equal to 5.
 i++ → Increments i by 1 in each iteration.
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
2. Using for Loop with an Array (2 Marks)
Iterating over an array using a for loop.
Example:
let fruits: string[] = ["Apple", "Banana", "Cherry"];

for (let i = 0; i < fruits.length; i++) {


console.log(fruits[i]);
}
Output:
Apple
Banana
Cherry
3. Reverse for Loop (1 Mark)
Looping backward by decrementing the counter.
Example:
for (let i = 5; i >= 1; i--) {
console.log("Countdown:", i);
}
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
4. Skipping Iterations with continue (1 Mark)
Using continue to skip specific iterations.
Example:
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skips when i is 3
console.log(i);
}
Output:
1
2
4
5
(Iteration 3 is skipped)

b (i) What is Generics? How it is used in Typescript?


Generics allow us to create reusable and flexible components that work with multiple data
types instead of just one. They provide type safety while allowing code reusability.
1. What is Generics? (3 Marks)
Generics let us define a function, class, or interface without specifying a concrete type.
Instead, we use a placeholder type (like <T>) that can be replaced with actual types when
the function or class is used.
Why Use Generics?
✅ Avoids writing duplicate code for different data types
✅ Provides type safety
✅ Increases code reusability
2. Using Generics in TypeScript (4 Marks)
A. Generic Function (2 Marks)
A function that works with any data type:
function identity<T>(value: T): T {
return value;
}

console.log(identity<string>("Hello")); // Output: Hello


console.log(identity<number>(100)); // Output: 100
 <T> → Defines a generic type T.
 identity<T>(value: T): T → The function uses T instead of a fixed type.
 We specify the actual type (string or number) when calling the function.
B. Generic Class (1 Mark)
A class that can store and return values of any type.
class Box<T> {
private item: T;

constructor(item: T) {
this.item = item;
}

getItem(): T {
return this.item;
}
}

let numberBox = new Box<number>(50);


console.log(numberBox.getItem()); // Output: 50

let stringBox = new Box<string>("TypeScript");


console.log(stringBox.getItem()); // Output: TypeScript
 <T> makes the class flexible to hold any type (number, string, etc.).
C. Generic Interface (1 Mark)
Interfaces can also use generics to ensure type safety.
interface KeyValuePair<K, V> {
key: K;
value: V;
}

let pair: KeyValuePair<string, number> = { key: "Age", value: 30 };


console.log(pair); // Output: { key: 'Age', value: 30 }
 <K, V> → Represents two generic types.
 Ensures key is always a string, and value is always a number.
(ii) Describe the term collections in Typescript.
In TypeScript, collections refer to data structures used to store and manipulate groups of
values. The most common collections are Arrays, Tuples, Sets, and Maps.
1. Arrays (2 Marks)
An array is an ordered collection of elements of the same type.
Example:
let numbers: number[] = [10, 20, 30, 40];

numbers.push(50); // Adds 50 to the array


console.log(numbers[0]); // Output: 10
 Uses indexing to access elements.
 Supports methods like push(), pop(), map(), and filter().
2. Tuples (1 Mark)
A tuple is a fixed-size collection where each element can have a different type.
Example:
let person: [string, number] = ["Alice", 25];

console.log(person[0]); // Output: Alice


console.log(person[1]); // Output: 25
 Ensures type safety for each position.
3. Sets (2 Marks)
A Set is a collection of unique values, meaning duplicates are not allowed.
Example:
let uniqueNumbers: Set<number> = new Set([1, 2, 3, 3, 4]);

uniqueNumbers.add(5);
console.log(uniqueNumbers); // Output: {1, 2, 3, 4, 5}
 Prevents duplicates.
 Supports methods like add(), delete(), and has().
4. Maps (2 Marks)
A Map stores key-value pairs, where keys can be any type (unlike objects, where keys
must be strings).
Example:
let studentScores: Map<string, number> = new Map();

studentScores.set("Alice", 90);
studentScores.set("Bob", 85);

console.log(studentScores.get("Alice")); // Output: 90
 Keys can be strings, numbers, or objects.
 Supports methods like set(), get(), and has()

You might also like