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

Unit 4 Notes

The document explains various types of JavaScript functions, including Function Declarations, Function Expressions, Arrow Functions, IIFE, Constructor Functions, Generator Functions, Recursive Functions, Async Functions, functions with Default Parameters, and Rest Parameter Functions. It also covers the JavaScript String and Array objects, detailing their creation, key properties, and important methods for data manipulation. Additionally, it introduces primitive data types in TypeScript, which include Number, String, Boolean, Symbol, Null, Undefined, and BigInt.

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 DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit 4 Notes

The document explains various types of JavaScript functions, including Function Declarations, Function Expressions, Arrow Functions, IIFE, Constructor Functions, Generator Functions, Recursive Functions, Async Functions, functions with Default Parameters, and Rest Parameter Functions. It also covers the JavaScript String and Array objects, detailing their creation, key properties, and important methods for data manipulation. Additionally, it introduces primitive data types in TypeScript, which include Number, String, Boolean, Symbol, Null, Undefined, and BigInt.

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 DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT -IV

1. Explain various types of javascript functions


JavaScript functions are essential building blocks of the language, allowing code to be
executed when called. Functions in JavaScript can be categorized into several types based on how
they are defined and invoked. Here’s an explanation of the different types of JavaScript functions.

Types of Functions in JavaScript

JavaScript functions are essential building blocks of the language, allowing code to be
executed when called. Functions in JavaScript can be categorized into several types based on
how they are defined and invoked. Here’s an explanation of the different types of JavaScript
functions.

1. Function Declaration (Named Function)

A function declaration is the most common way of defining a function. It has a name and is
hoisted to the top of the scope during the execution phase.

Syntax:

function functionName(parameters) {
// function body
return value;
}

Example:

function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // Output: Hello, Alice!

Key Points:

 Function is hoisted, meaning you can call it before it's defined in the code.
 Functions are block-scoped.

2. Function Expression (Anonymous Function)

A function expression involves defining a function within a variable. It is often


anonymous, meaning it doesn’t have a name.

Syntax:

const functionName = function(parameters) {


// function body
return value;
};

Example:

const add = function(a, b) {


return a + b;
};
console.log(add(2, 3)); // Output: 5

Key Points:

 Not hoisted — it must be declared before it is called.


 The function is assigned to a variable, which can be passed around like a regular
value.

3. Arrow Function

Arrow functions provide a shorter syntax for writing functions. They are anonymous and do
not have their own this context, making them more suitable for certain situations, such as
inside callbacks.

Syntax:

const functionName = (parameters) => {


// function body
return value;
};

Example:

const multiply = (a, b) => a * b;


console.log(multiply(3, 4)); // Output: 12

Key Points:

 Concise syntax with implicit return (if only one expression in body).
 Arrow functions don’t have their own this value — they inherit this from the
outer context.

4. Immediately Invoked Function Expression (IIFE)

An IIFE is a function that is defined and then immediately executed. It's often used to create
local scopes to avoid polluting the global namespace.

Syntax:

(function() {
// function body
})();

Example:
(function() {
console.log("This function runs immediately!");
})();

Key Points:

 It is invoked immediately after being defined.


 Often used for data encapsulation or avoiding global variable conflicts.

5. Constructor Function

A constructor function is used to create objects and initialize properties. It acts as a


blueprint for creating instances of an object.

Syntax:

function Person(name, age) {


this.name = name;
this.age = age;
}
const person1 = new Person("Alice", 25);
console.log(person1.name); // Output: Alice

Key Points:

 Typically used with the new keyword to create instances.


 Constructor functions have the ability to set properties on the created object.

6. Generator Function

A generator function allows you to define an iterative function that can yield multiple
values on demand. The function pauses its execution and can be resumed later.

Syntax:

function* generatorFunction() {
yield value1;
yield value2;
}

Example:

function* counter() {
let count = 0;
while (count < 3) {
yield count;
count++;
}
}
const gen = counter();
console.log(gen.next().value); // Output: 0
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
Key Points:

 The yield keyword is used to pause and resume the execution.


 Generator functions return a generator object that can be iterated.

7. Recursive Function

A recursive function is one that calls itself. It is useful for solving problems that can be
broken down into smaller subproblems, such as calculating factorials, traversing trees, etc.

Syntax:

function recursiveFunction() {
// Base case to stop recursion
// Recursive case to call itself
}

Example:

function factorial(n) {
if (n === 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
console.log(factorial(5)); // Output: 120

Key Points:

 Must have a base case to prevent infinite recursion.


 Each recursive call needs to bring the problem closer to the base case.

8. Async Function (with Promises)

An async function is a function that always returns a Promise. It allows the use of await to
pause execution until a Promise is resolved.

Syntax:

async function asyncFunction() {


let result = await someAsyncTask();
return result;
}

Example:

async function fetchData() {


let response = await fetch('https://jsonplaceholder.typicode.com/posts');
let data = await response.json();
console.log(data);
}
fetchData(); // Fetches data asynchronously

Key Points:
 async makes the function return a Promise.
 await pauses execution until the Promise resolves.

9. Function with Default Parameters

A function can be defined with default values for parameters. If a value is not provided when
calling the function, the default value is used.

Syntax:

function greet(name = "Guest") {


console.log(`Hello, ${name}!`);
}

Example:

greet(); // Output: Hello, Guest!


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

Key Points:

 Default parameters are evaluated at runtime.


 Can be used to make functions more flexible and avoid undefined errors.

10. Rest Parameter Function

A rest parameter allows a function to accept an arbitrary number of arguments as an


array.

Syntax:

function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}

Example:

console.log(sum(1, 2, 3, 4)); // Output: 10

Key Points:

 ... collects the remaining arguments into an array.


 Useful for variadic functions (functions that take a variable number of arguments).

Conclusion

JavaScript provides a variety of ways to define and use functions, each suited for different
scenarios:

1. Function Declarations – Traditional functions with hoisting.


2. Function Expressions – Anonymous functions assigned to variables.
3. Arrow Functions – Concise functions with no this.
4. IIFE – Functions that run immediately.
5. Constructor Functions – Functions used to create objects.
6. Generator Functions – Functions that can pause and resume.
7. Recursive Functions – Functions that call themselves.
8. Async Functions – Functions for asynchronous operations.
9. Default Parameters – Functions with default argument values.
10. Rest Parameters – Functions that take a variable number of arguments.

Each function type offers distinct advantages and can be used in various contexts depending
on the needs of the program.

2.Explain javascript string object and array object

JavaScript String Object and Array Object

In JavaScript, String and Array are both objects that are used to store and manipulate data.
Each provides a set of methods and properties that help perform operations like modifying
content, extracting parts, and iterating over values.

Let's break down each of these objects and their key features:

1. String Object in JavaScript

A String in JavaScript is a sequence of characters used to represent textual data. The String
Object is a built-in JavaScript object that allows you to manipulate, search, and format
strings.

Creating a String Object

let str = new String("Hello, World!"); // String Object


let strLiteral = "Hello, World!"; // String Literal (most common)

Key Properties of String Object

1. length: Returns the length (number of characters) of a string.


2. let str = "Hello";
3. console.log(str.length); // Output: 5
4. indexOf(): Returns the index of the first occurrence of a specified substring.
5. let str = "Hello, World!";
6. console.log(str.indexOf("World")); // Output: 7
7. charAt(): Returns the character at the specified index.
8. let str = "Hello";
9. console.log(str.charAt(1)); // Output: 'e'
10. toUpperCase(): Converts all characters in the string to uppercase.
11. let str = "hello";
12. console.log(str.toUpperCase()); // Output: "HELLO"
13. toLowerCase(): Converts all characters in the string to lowercase.
14. let str = "HELLO";
15. console.log(str.toLowerCase()); // Output: "hello"
16. slice(): Extracts a part of the string from a given start index to an end index.
17. let str = "Hello, World!";
18. console.log(str.slice(0, 5)); // Output: "Hello"
19. replace(): Replaces a substring with another substring.
20. let str = "Hello, World!";
21. console.log(str.replace("World", "JavaScript")); // Output: "Hello,
JavaScript!"
22. split(): Splits a string into an array of substrings based on a specified separator.
23. let str = "Hello, World!";
24. console.log(str.split(", ")); // Output: ['Hello', 'World!']
25. trim(): Removes whitespace from both ends of a string.
26. let str = " Hello, World! ";
27. console.log(str.trim()); // Output: "Hello, World!"

Important Methods of String Object

 concat(): Combines two or more strings.


 let str1 = "Hello, ";
 let str2 = "World!";
 console.log(str1.concat(str2)); // Output: "Hello, World!"
 includes(): Checks if a string contains a specified substring.
 let str = "Hello, World!";
 console.log(str.includes("World")); // Output: true
 startsWith(): Checks if the string starts with a specific substring.
 let str = "Hello, World!";
 console.log(str.startsWith("Hello")); // Output: true
 endsWith(): Checks if the string ends with a specific substring.
 let str = "Hello, World!";
 console.log(str.endsWith("World!")); // Output: true

2. Array Object in JavaScript

An Array in JavaScript is an ordered collection of values, which can be of any type,


including other arrays or objects. The Array Object provides several useful methods for
manipulating arrays, making it a powerful tool for managing lists of data.

Creating an Array Object

let arr = new Array(1, 2, 3, 4); // Array Object


let arrLiteral = [1, 2, 3, 4]; // Array Literal (most common)

Key Properties of Array Object

1. length: Returns the number of elements in the array.


2. let arr = [1, 2, 3, 4];
3. console.log(arr.length); // Output: 4

Key Methods of Array Object

1. push(): Adds one or more elements to the end of an array.


2. let arr = [1, 2, 3];
3. arr.push(4);
4. console.log(arr); // Output: [1, 2, 3, 4]
5. pop(): Removes the last element from an array and returns it.
6. let arr = [1, 2, 3, 4];
7. let lastElement = arr.pop();
8. console.log(lastElement); // Output: 4
9. console.log(arr); // Output: [1, 2, 3]
10. shift(): Removes the first element from an array and returns it.
11. let arr = [1, 2, 3];
12. let firstElement = arr.shift();
13. console.log(firstElement); // Output: 1
14. console.log(arr); // Output: [2, 3]
15. unshift(): Adds one or more elements to the beginning of an array.
16. let arr = [2, 3];
17. arr.unshift(1);
18. console.log(arr); // Output: [1, 2, 3]
19. concat(): Combines two or more arrays into one.
20. let arr1 = [1, 2];
21. let arr2 = [3, 4];
22. let combined = arr1.concat(arr2);
23. console.log(combined); // Output: [1, 2, 3, 4]
24. join(): Joins all elements of an array into a string, separated by a specified delimiter.
25. let arr = [1, 2, 3];
26. console.log(arr.join(", ")); // Output: "1, 2, 3"
27. slice(): Extracts a portion of an array without modifying the original array.
28. let arr = [1, 2, 3, 4];
29. console.log(arr.slice(1, 3)); // Output: [2, 3]
30. splice(): Changes the contents of an array by adding/removing elements.
31. let arr = [1, 2, 3, 4];
32. arr.splice(2, 1, 5, 6); // Removes 1 element at index 2, and
inserts 5 and 6
33. console.log(arr); // Output: [1, 2, 5, 6, 4]
34. forEach(): Executes a provided function once for each array element.
35. let arr = [1, 2, 3];
36. arr.forEach(function(element) {
37. console.log(element);
38. });
39. // Output: 1, 2, 3
40. map(): Creates a new array with the results of calling a function on every element.
41. let arr = [1, 2, 3];
42. let squared = arr.map(x => x * x);
43. console.log(squared); // Output: [1, 4, 9]
44. filter(): Creates a new array with all elements that pass the test implemented by the
provided function.
45. let arr = [1, 2, 3, 4];
46. let even = arr.filter(x => x % 2 === 0);
47. console.log(even); // Output: [2, 4]
48. reduce(): Applies a function against an accumulator and each array element (from left
to right) to reduce it to a single value.
49. let arr = [1, 2, 3];
50. let sum = arr.reduce((acc, val) => acc + val, 0);
51. console.log(sum); // Output: 6
52. some(): Tests whether at least one element in the array passes a given test.
53. let arr = [1, 2, 3];
54. let hasEven = arr.some(x => x % 2 === 0);
55. console.log(hasEven); // Output: true
56. every(): Tests whether all elements in the array pass a given test.
57. let arr = [2, 4, 6];
58. let allEven = arr.every(x => x % 2 === 0);
59. console.log(allEven); // Output: true
Conclusion

String Object and Array Object in JavaScript are both powerful tools for handling textual
and list data

, respectively.

 The String Object provides methods to manipulate and extract substrings, change
case, search for patterns, and more.
 The Array Object allows you to store and manipulate ordered data, with methods to
add, remove, and iterate through elements, making it ideal for tasks involving lists and
collections.

By understanding the features and methods of both the String and Array objects, you can
leverage JavaScript to handle a wide variety of data manipulation tasks efficiently.

3.Primitive Data Types in TypeScript

In TypeScript, primitive data types refer to the most basic forms of data that are not objects
and do not have methods or properties. These types hold a single value and are immutable
(their values cannot be changed once assigned). TypeScript includes the following primitive
data types:

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

Each of these types serves a specific purpose, and understanding them is essential for writing
efficient TypeScript code. Let’s dive deeper into each of these types with examples.

1. Number

The number type in TypeScript represents both integer and floating-point numbers. It can also
handle special values like NaN (Not-a-Number), Infinity, and -Infinity.

Example:

let age: number = 25; // An integer


let price: number = 199.99; // A floating-point number
let score: number = NaN; // Special value, Not-a-Number
let maxLimit: number = Infinity; // Positive infinity

Key Points:

 In TypeScript, number is used for all numeric values (both integers and floating-point
numbers).
 Operations like addition, subtraction, multiplication, and division work as expected.

2. String

The string type represents sequences of characters (text). Strings can be defined using
single quotes ('), double quotes ("), or backticks (`) for template literals.

Example:

let firstName: string = "John";


let lastName: string = 'Doe';
let greeting: string = `Hello, ${firstName} ${lastName}`; // Using template
literals

Key Points:

 string is used for textual data.


 TypeScript supports template literals (denoted by backticks) that allow you to embed
expressions inside a string.
 Strings in TypeScript are immutable—you cannot change a string after it’s created.

3. Boolean

The boolean type represents logical values: either true or false. This type is commonly
used for flags or conditions in decision-making processes.

Example:

let isActive: boolean = true;


let isCompleted: boolean = false;

Key Points:

 boolean is used for values that can either be true or false.


 Useful for controlling logic in if statements, loops, and conditions.

4. Symbol

A symbol is a unique and immutable primitive value that is often used as an identifier for
object properties. Symbols are primarily used when you need to create unique property keys
that won’t conflict with other properties.

Example:

let sym1: symbol = Symbol('description');


let sym2: symbol = Symbol('description');

console.log(sym1 === sym2); // Output: false (each symbol is unique)

Key Points:
 Symbols are always unique, even if they have the same description.
 They are mainly used for creating unique property keys in objects, ensuring there
are no accidental property name conflicts.

5. Null

The null type represents the intentional absence of any object value. It's used when you
explicitly want to indicate that a variable has no value.

Example:

let emptyValue: null = null;

Key Points:

 null is a primitive value that represents "no value" or "empty".


 It’s commonly used for setting object references to a non-existent value, like clearing
an object reference.

6. Undefined

The undefined type represents an uninitialized or missing value. A variable is automatically


assigned the value undefined when it is declared but not yet assigned a value.

Example:

let notAssigned: undefined;


console.log(notAssigned); // Output: undefined

Key Points:

 undefined typically means a variable has been declared but hasn’t been assigned a
value.
 It is distinct from null, which is an explicit assignment of an empty or missing value.

7. BigInt

The BigInt type was introduced to handle large integers that exceed the number range.
Unlike regular numbers, BigInt can represent arbitrarily large integers.

Example:

let largeNumber: BigInt = 1234567890123456789012345678901234567890n;


let anotherBigInt: BigInt = BigInt(1234567890);
console.log(largeNumber);

Key Points:

 BigInt is used when dealing with very large integers that cannot be accurately
represented by the number type.
 BigInt literals are written with an n suffix (e.g., 123n).

Conclusion

In TypeScript, primitive data types are the building blocks of data representation and
manipulation. They are simple, immutable values that don’t have methods or properties.
Here’s a summary of the main primitive data types:

Type Description Example


Represents both integers and floating- let
Number age: number = 25;
point numbers.
Represents a sequence of characters let
String name: string = "Alice";
(text).
Boolean Represents true or false values. let isActive: boolean = true;
Represents a unique identifier. Useful let
Symbol id: symbol = Symbol("unique");
for object property keys.
Represents an intentional absence of let
Null data: null = null;
any value.
Represents a variable that has not been let
Undefined notDefined: undefined;
assigned a value.
let bigNumber: BigInt =
BigInt Represents arbitrarily large integers. 12345678901234567890n;

Understanding these primitive types and how to use them in your TypeScript code is
fundamental to building robust and efficient applications.

4.Destructuring and Spread Operators in JavaScript and TypeScript

In modern JavaScript (ES6) and TypeScript, both destructuring and spread operators are
powerful features that allow for more concise, readable, and flexible code. These two features
simplify handling arrays and objects, improving both performance and developer
productivity.

Let’s dive into the details of both operators:

1. Destructuring

Destructuring is a shorthand syntax used to unpack values from arrays or properties from
objects into distinct variables. It allows us to extract values from arrays and objects in a way
that is both clean and concise.

Array Destructuring

Array destructuring enables you to unpack values from an array into individual variables in a
single step.
Syntax:
let [variable1, variable2, ...rest] = array;

Example:
let numbers: number[] = [10, 20, 30];

// Destructuring array
let [first, second, third] = numbers;

console.log(first); // Output: 10
console.log(second); // Output: 20
console.log(third); // Output: 30

Key Points:

 The variables on the left must match the order and number of elements in the array.
 You can skip elements by leaving empty spots in the array, e.g., [first, , third]
will skip the second element.
 The ... (rest syntax) allows collecting the remaining elements of the array into a new
array.

Example with Rest Operator in Arrays:


let numbers: number[] = [10, 20, 30, 40, 50];
let [first, second, ...others] = numbers;

console.log(first); // Output: 10
console.log(second); // Output: 20
console.log(others); // Output: [30, 40, 50]

Object Destructuring

Object destructuring allows you to unpack properties from objects into variables.

Syntax:
let {property1, property2, ...rest} = object;

Example:
let person = { name: "Alice", age: 25, occupation: "Developer" };

// Destructuring object
let { name, age } = person;

console.log(name); // Output: Alice


console.log(age); // Output: 25

Key Points:

 Property names must match the variable names on the left-hand side.
 You can rename variables using the : syntax if you want different names for your
variables.

Example with Renaming:


let person = { name: "Alice", age: 25 };

// Renaming variables while destructuring


let { name: fullName, age: yearsOld } = person;

console.log(fullName); // Output: Alice


console.log(yearsOld); // Output: 25

Example with Rest Operator in Objects:


let person = { name: "Alice", age: 25, occupation: "Developer" };
let { name, ...others } = person;

console.log(name); // Output: Alice


console.log(others); // Output: { age: 25, occupation: "Developer" }

Default Values in Destructuring:

You can assign default values to variables when destructuring, in case the property is
undefined.

let person = { name: "Alice" };

// Assigning default value for age


let { name, age = 30 } = person;

console.log(name); // Output: Alice


console.log(age); // Output: 30 (default value)

2. Spread Operator

The spread operator (...) is used to expand elements from an array or object. It allows you
to "spread" the elements into a new array or object, making it easier to copy, merge, or
expand data.

Array Spread Operator

The spread operator is used to copy or merge arrays.

Syntax:
let newArray = [...existingArray];

Example:
let numbers: number[] = [1, 2, 3];
let moreNumbers: number[] = [4, 5, ...numbers, 6];

console.log(moreNumbers); // Output: [4, 5, 1, 2, 3, 6]

Key Points:

 It is useful when you need to clone an array or merge arrays.


 Cloning an Array:
 let arr1 = [1, 2, 3];
 let arr2 = [...arr1];
 console.log(arr2); // Output: [1, 2, 3]
Object Spread Operator

The spread operator can also be used to copy properties from one object to another or to
merge objects.

Syntax:
let newObject = { ...existingObject };

Example:
let person = { name: "Alice", age: 25 };
let updatedPerson = { ...person, occupation: "Developer" };

console.log(updatedPerson); // Output: { name: "Alice", age: 25,


occupation: "Developer" }

Key Points:

 Merging objects:
 let person = { name: "Alice", age: 25 };
 let job = { occupation: "Developer", company: "Tech Corp" };

 let merged = { ...person, ...job };
 console.log(merged); // Output: { name: "Alice", age: 25, occupation:
"Developer", company: "Tech Corp" }

 Shallow Copy: The spread operator creates a shallow copy of the object. If the object
has nested objects, those nested objects are still referenced, not cloned.

Example of Shallow Copy with Nested Objects:


let original = { person: { name: "Alice", age: 25 }, city: "New York" };
let copy = { ...original };

copy.person.name = "Bob";

console.log(original.person.name); // Output: Bob (because the nested


object is referenced)
console.log(copy.person.name); // Output: Bob

3. Combined Example: Destructuring and Spread Operators

You can use both the destructuring and spread operators together to create powerful and
flexible code.

Example with Both Destructuring and Spread Operator:


let person = { name: "Alice", age: 25, occupation: "Developer", city: "New
York" };

// Destructuring and using spread to create a new object


let { name, ...otherDetails } = person;

console.log(name); // Output: Alice


console.log(otherDetails); // Output: { age: 25, occupation: "Developer",
city: "New York" }
Example with Arrays:
let numbers: number[] = [1, 2, 3, 4];

// Destructuring and spreading to create a new array


let [first, second, ...rest] = numbers;
let newNumbers = [...rest, first];

console.log(newNumbers); // Output: [3, 4, 1]

Advantages of Destructuring and Spread Operators

 Cleaner and more readable code: These operators allow you to write less code
while performing complex operations like copying, merging, and extracting values.
 Avoiding side effects: With the spread operator, you can copy data or merge objects
without mutating the original data.
 Ease of use in functions: Destructuring can simplify function parameters, allowing
you to unpack properties from objects or arrays easily.

Example: Using Destructuring in Function Parameters:

function greet({ name, age }: { name: string, age: number }) {


console.log(`Hello ${name}, you are ${age} years old.`);
}

greet({ name: "Alice", age: 25 }); // Output: Hello Alice, you are 25
years old.

Conclusion

Both destructuring and the spread operator are essential features in modern JavaScript and
TypeScript development.

 Destructuring allows for cleaner code by enabling you to unpack arrays and objects
into variables with minimal syntax.
 The spread operator is useful for copying or merging arrays and objects in a simple
and effective way.

Together, these features significantly improve code readability, reduce verbosity, and help
prevent errors, making them a staple in modern JavaScript and TypeScript development.

5.How to let the function find the sum of two arguments and return the result

To create a function that finds the sum of two arguments and returns the result in JavaScript
or TypeScript, you can follow this simple approach:

Steps:

1. Define a function that takes two parameters.


2. Add the parameters inside the function.
3. Return the sum of the two parameters.
Code Example:
function sum(a: number, b: number): number {
return a + b;
}

// Example usage
let result = sum(3, 4); // Calling the function with arguments 3 and 4
console.log(result); // Output: 7

Explanation:

 sum(a: number, b: number): This is the function declaration. The parameters a and
b are both of type number, ensuring that the function only accepts numbers.
 return a + b;: This line performs the addition of the two arguments (a and b) and
returns the result.
 let result = sum(3, 4);: This calls the function with the arguments 3 and 4,
storing the return value in the variable result.
 console.log(result);: This prints the result to the console, which in this case
would be 7.

Additional Notes:

 The function is very flexible; you can pass any two numbers to it, and it will return
their sum.
 The function ensures type safety by specifying that both parameters must be numbers
(a: number, b: number).

This is a concise, clear, and effective way to define a function that calculates the sum of two
numbers

6.Concept of Ambient Functions in TypeScript (7 Marks)

In TypeScript, ambient functions are a concept that allows you to declare the existence of
functions (or variables) that are provided by external sources, without providing their actual
implementation. They serve as a way to inform TypeScript about the types of functions or
objects that exist outside of the TypeScript codebase, typically coming from external
libraries, JavaScript code, or global environments.

Ambient functions are mainly used when you're working with code that is not written in
TypeScript but you want TypeScript to understand the types and signatures of these
functions.

Key Points of Ambient Functions:

1. Declaration Without Implementation:


An ambient function is declared without the need to provide an implementation. The
function signature tells TypeScript what arguments the function expects and what
type it returns.
2. External Source:
These functions are assumed to be implemented elsewhere, outside the current
TypeScript file. For instance, they could be part of the browser's global objects (like
alert(), console.log()), third-party libraries, or any external code.
3. Used in Declaration Files (.d.ts):
Ambient functions are typically declared in declaration files (files with the .d.ts
extension), which are used to provide type information for external code that
TypeScript cannot directly infer.
4. Global Scope:
Ambient functions often represent globally available functions or those provided by
third-party libraries. They help TypeScript understand how to type check these
functions without needing their implementation.

Syntax for Declaring Ambient Functions:

To declare an ambient function, the declare keyword is used. This keyword tells TypeScript
that the function exists and its type signature, but it doesn't provide an implementation.

Syntax:

declare function functionName(param1: type1, param2: type2): returnType;

Example:

Let's say you are working with an external JavaScript library or a global browser function
that isn't written in TypeScript. Here's how you might declare an ambient function:

declare function alert(message: string): void;

In this example:

 declare indicates that alert is a global function (provided by the browser).


 message: string specifies that the function takes a string parameter.
 void indicates that the function doesn't return anything.

Real-World Example:

1. Ambient Function for a Global Browser API:

The browser provides a global setTimeout() function. Here's how we can declare it:

declare function setTimeout(callback: Function, delay: number): number;


 setTimeout() is a built-in function in JavaScript (and the browser) that allows us to
delay the execution of code.
 TypeScript is not aware of this function unless we declare it using declare.
 callback: Function specifies that the first argument is a function, and delay:
number means the second argument is a number (milliseconds).
 number is the return type because setTimeout() returns a numeric ID for the
timeout.

2. Ambient Function for External Libraries (e.g., jQuery):

If you are using an external JavaScript library, like jQuery, that doesn't come with TypeScript
type definitions, you might want to declare an ambient function.

declare function $<T>(selector: string): T;

 This declares a function $, which you might use as part of the jQuery library. The
function takes a string (selector) and returns a generic type T that is determined at
runtime based on how the function is used.

Use Cases for Ambient Functions:

1. Global Functions:
Ambient functions are particularly useful for declaring globally available functions
that are part of the runtime environment, such as browser APIs (alert(),
console.log()), Node.js APIs (process.exit()), or third-party libraries.
2. Integration with JavaScript Libraries:
When integrating TypeScript with JavaScript libraries that do not have type
definitions, you can declare ambient functions to provide type safety for the library's
API.
3. Third-Party Modules Without Type Definitions:
In cases where a third-party module or API does not provide TypeScript definitions,
you can declare the module’s functions using the declare keyword to avoid type
errors during development.

Example with declare for a Global Function:

If you're working with a global function in your environment that TypeScript doesn't know
about, such as a function defined in another script or in a non-TypeScript environment:

// Declaring an ambient function for a function in an external JS file


declare function customAlert(message: string): void;

// Now you can use `customAlert` without error


customAlert("This is an ambient function!");
Advantages of Ambient Functions:

1. Type Safety:
Ambient functions allow TypeScript to understand and type-check the arguments and
return values, improving safety when working with external or non-TypeScript code.
2. Avoid Errors:
By declaring ambient functions, you avoid runtime errors and ensure that you are
calling these functions with the correct types and parameters.
3. Improved Development Experience:
TypeScript can offer autocompletion, type inference, and error checking for these
ambient functions, improving the developer experience when working with external
libraries or global APIs.

Conclusion:

In TypeScript, ambient functions are a way to declare functions that are defined outside of
your current codebase (such as global browser functions or third-party libraries). They allow
TypeScript to recognize and type-check functions that are already available in the runtime
environment but are not part of the current TypeScript code. By using the declare keyword,
developers can leverage external JavaScript code while maintaining strong typing in
TypeScript.

7.Describe loops and Functions used in Typescript

TypeScript, being a superset of JavaScript, provides all the loop structures and function
syntax available in JavaScript, with additional type-checking benefits. Below, we will explain
the different loops and functions in TypeScript.

1. Loops in TypeScript

Loops in TypeScript are used to execute a block of code repeatedly under certain conditions.
TypeScript supports all JavaScript loop structures, including for, while, and do...while.
The major difference with TypeScript is that you can specify types for variables used in the
loops.

a. for loop

The for loop is the most commonly used loop. It consists of three parts:

1. Initialization: Set the loop counter.


2. Condition: The loop continues as long as the condition is true.
3. Increment/Decrement: This modifies the loop counter after each iteration.

Syntax:

for (let i = 0; i < 5; i++) {


console.log(i); // Output: 0, 1, 2, 3, 4
}
 Initialization: let i = 0 initializes the loop counter.
 Condition: i < 5 continues the loop as long as i is less than 5.
 Increment: i++ increases the counter after each iteration.

b. while loop

A while loop executes as long as the condition is true. It first checks the condition before
entering the loop.

Syntax:

let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}

 The loop continues to run while the condition (i < 5) is true.


 The loop counter (i++) is incremented manually inside the loop body.

c. do...while loop

The do...while loop is similar to the while loop, but it executes the block of code at least
once before checking the condition.

Syntax:

let i = 0;
do {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
} while (i < 5);

 The condition is checked after the code block is executed, ensuring that the loop runs
at least once.

d. for...in loop

The for...in loop is used to iterate over the keys (indices) of an object or array.

Syntax:

const person = { name: 'Alice', age: 25, city: 'New York' };


for (let key in person) {
console.log(`${key}: ${person[key]}`);
// Output: name: Alice, age: 25, city: New York
}

e. for...of loop

The for...of loop is used to iterate over iterable objects (such as arrays, strings, etc.) by
accessing their values.
Syntax:

const numbers = [10, 20, 30, 40];


for (let num of numbers) {
console.log(num); // Output: 10, 20, 30, 40
}

2. Functions in TypeScript

Functions in TypeScript allow us to define reusable blocks of code. TypeScript builds upon
JavaScript's function syntax and adds type annotations for function parameters and return
values to ensure type safety.

a. Function Declaration

A function declaration defines a function with a name, a list of parameters, and a block of
code to execute.

Syntax:

function greet(name: string): string {


return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Output: Hello, Alice!

 Parameter Type Annotation: name: string ensures that name is always a string.
 Return Type Annotation: : string ensures the function returns a string.

b. Function Expression

A function expression defines a function as part of an expression, often assigned to a


variable. This is useful for defining anonymous functions.

Syntax:

const multiply = (a: number, b: number): number => {


return a * b;
}

console.log(multiply(5, 3)); // Output: 15

 This is an arrow function which is a shorter syntax to write functions.


 a: number, b: number: Parameters are typed as numbers.
 : number: Specifies the return type is a number.

c. Optional Parameters

TypeScript allows you to define function parameters as optional using the ? symbol.

Syntax:
function greet(name: string, age?: number): string {
if (age) {
return `Hello, ${name}. You are ${age} years old.`;
}
return `Hello, ${name}!`;
}

console.log(greet("Alice")); // Output: Hello, Alice!


console.log(greet("Bob", 30)); // Output: Hello, Bob. You are 30 years old.

 The age parameter is optional, so the function can be called with just name.

d. Default Parameters

You can provide default values for parameters if no value is passed.

Syntax:

function greet(name: string, age: number = 18): string {


return `Hello, ${name}. You are ${age} years old.`;
}

console.log(greet("Alice")); // Output: Hello, Alice. You are 18 years old.


console.log(greet("Bob", 25)); // Output: Hello, Bob. You are 25 years old.

 Here, age has a default value of 18. If not provided, 18 will be used.

e. Rest Parameters

Rest parameters allow you to pass a variable number of arguments to a function.

Syntax:

function sum(...numbers: number[]): number {


return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4)); // Output: 10

 The ...numbers: number[] allows the function to accept any number of numeric
arguments, which are then stored in an array.

Conclusion

 Loops: TypeScript supports all basic JavaScript loops (for, while, do...while,
for...in, and for...of) along with the ability to specify the types of variables used
in loops for added safety and clarity.
 Functions: Functions in TypeScript extend JavaScript's capabilities by providing
strong typing for parameters and return values. TypeScript also introduces features
like optional parameters, default values, and rest parameters to enhance flexibility and
maintainability.

You might also like