KNOWLEDGE & LEARNING

     <section class="about-us">
       <div class="Art-board">
        <div class="Art-board1">
         <h2>
          <span class="black-text1">ABOUT</span>
          <span class="green-text">US</span>
         </h2>
         <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
         <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae deleniti ea totam praesentium ratione, sunt impedit magni commodi voluptate deserunt cupiditate, saepe quaerat asperiores similique recusandae architecto sequi! Cumque, doloribus?</p>
         <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab eos nulla eveniet minima perferendis, autem veniam tenetur nesciunt vero quod, placeat expedita officiis iure voluptates quidem consectetur animi? Sequi ipsum possimus atque cupiditate necessitatibus asperiores, at, ipsam quo expedita amet dolore doloribus distinctio saepe quod sit fugiat. Aliquid, vero fugit.</p>
         <br>
         <button>Read More</button>
        </div>
        <div class="Art-board2">
         <img src="https://sitenivel.com.br/wp-content/uploads/2024/03/Artboard-1@2x2.png" alt="Art Board" />
        </div>
       </div>
     </section>
  
     <section class="services">
       <div class="services-heading">
        <h2>
         <span class="black-text1">OUR</span>
         <span class="green-text">SERVICES</span>
        </h2>
        <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit...</p>
       </div>
       <div class="servic
        <div class="service-item">
         <div class="circle-image">
          <img src="str2.png" alt="Star Circle" />
         </div>
         <h3>Web Design</h3>
         <p>Lorem ipsum dolor sit amet...</p>
         <div class="read"><a href="#">read more</a></div>
        
        <div class="service-item">
         <div class="circle-image">
          <img src="str2.png" alt="Star Circle" />
         </div>
         <h3>Graphic Design</h3>
         <p>Lorem ipsum dolor sit amet...</p>
         <div class="read"><a href="#">read more</a></div>
        </div>
  
    
  
       </div>
     </section>
  
     <section class="portfolio">
         <div class="portfolio-heading">
             <h2>
                 <span class="black-text-p-folio">OUR</span>
                 <span class="green-text-p-folio">PORTFOLIO</span>
             </h2>
         </div>
         <div class="portfolio-headingp">
             <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Id inventore veritatis amet dolor magnam ut fugiat repellendus reprehenderit unde iure.</p>
             <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, praesentium.</p>
         </div>
         <div class="text-container">
             <p>WEB DESIGN</p> <p>GRAPHIC DESIGN</p> <p>BRANDING</p> <p><span class="logo1">LOGO</span></p> <p>MARKETING</p> <p>ADVERTISEMENT</p>
         </div>
     
         <div class="portfolio-items">
             <div class="portfolio-column">
                 <div class="portfolio-item">
                     <img src="h1.png" alt="Horse">
                 </div>
                 <div class="portfolio-item">
                     <img src="h6.png" alt="Growth Place">
                 </div>
             </div>
             <div class="portfolio-column">
                 <div class="portfolio-item">
                     <img src="h2.png" alt="Social Trees">
                 </div>
                 <div class="portfolio-item">
                     <img src="h7.png" alt="Brain Works">
                 </div>
             </div>
             <div class="portfolio-column">
                 <div class="portfolio-item">
                     <img src="h3.png" alt="Creative Brain">
                 </div>
                 <div class="portfolio-item">
                     <img src="h8.png" alt="Lion Group">
                 </div>
             </div>
             <div class="portfolio-column">
                 <div class="portfolio-item">
                     <img src="h4.png" alt="Team Success">
                 </div>
                 <div class="portfolio-item">
                     <img src="h9.png" alt="Growth Place">
                 </div>
             </div>
             <div class="portfolio-column">
                 <div class="portfolio-item">
                     <img src="h5.png" alt="Rhino Group">
                 </div>
                 <div class="portfolio-item">
                     <img src="h10.png" alt="Social Group">
                 </div>
             </div>
         </div>
     </section>
    
QUIZ TEST PRACTICE MCQS CHECK YOUR SKILL (credit GIAIC Student)
Click here For attempt quiz
Passcode giaicb1

EXAM PRACTICE (SLIDE/REPO) QUIZ & PRACTICE QUESTION


Quiz 1 Lecture 2 Variables and Data Types


Chatgpt Objective Quiz Link:
bit.ly/4cUfCP3
Code: TSQ

quiz prepared by babar shah
https://forms.gle/3LVbdANbLPkYcwV18


Final Exam MCQS/Practice



VOID MCQ
1. What is the purpose of the void type in TypeScript?

A) To represent a boolean value
B) To represent an absent or uninitialized value
C) To represent a numeric value
D) To represent a string value

Answer: B) To represent an absent or uninitialized value

1. Which of the following is a valid use of the void type?

A) let x: void = 5;
B) let x: void = null;
C) let x: void = undefined;
D) let x: void = 'hello';

Answer: C) let x: void = undefined;

1. What is the difference between void and undefined in TypeScript?

A) void is a type, while undefined is a value
B) void is a value, while undefined is a type
C) void and undefined are interchangeable
D) void is a subtype of undefined

Answer: A) void is a type, while undefined is a value

1. Can a function with a void return type return a value?

A) Yes, any value
B) Yes, but only undefined
C) No, it cannot return a value
D) It depends on the function implementation

Answer: B) Yes, but only undefined

1. What is the effect of assigning a value to a variable with a void type?

A) The value is ignored
B) The value is assigned, but a warning is given
C) A type error is thrown
D) The value is converted to undefined

Answer: C) A type error is thrown
1. What does the void keyword indicate when used as a function return type?

A) The function returns a boolean value
B) The function returns no value (or undefined)
C) The function returns a numeric value
D) The function returns a string value

Answer: B) The function returns no value (or undefined)

1. Which of the following functions correctly uses the void return type?

A) function foo(): void { return 'hello'; }
B) function foo(): void { console.log('hello'); }
C) function foo(): void { return 5; }
D) function foo(): void { return true; }

Answer: B) function foo(): void { console.log('hello'); }

1. What happens if a function with a void return type attempts to return a value?

A) The value is returned and ignored
B) A type error is thrown
C) The function returns undefined instead
D) The program crashes

Answer: B) A type error is thrown

structural typing:
1. What is the primary principle of structural typing?

A) Name-based compatibility
B) Shape-based compatibility
C) Type-based compatibility
D) Value-based compatibility

Answer: B) Shape-based compatibility

2. Which of the following is a key benefit of structural typing?

A) Improved code readability
B) Enhanced type safety
C) Increased flexibility and compatibility
D) Better support for object-oriented programming

Answer: C) Increased flexibility and compatibility

3. In structurally-typed languages, what determines whether two types are compatible?

A) The names of the types
B) The structure and shape of the types (e.g., properties, methods)
C) The inheritance hierarchy of the types
D) The values assigned to the types

Answer: B) The structure and shape of the types (e.g., properties, methods)

Use of arrays method shift unshift pop and push

MCQ 1:
What does the shift() method do to an array?

A) Removes the last element and returns it
B) Removes the first element and returns it
C) Adds a new element to the beginning of the array
D) Adds a new element to the end of the array

Answer: B) Removes the first element and returns it

MCQ 2:
What does the unshift() method do to an array?

A) Removes the first element and returns it
B) Removes the last element and returns it
C) Adds a new element to the beginning of the array
D) Adds a new element to the end of the array

Answer: C) Adds a new element to the beginning of the array

Here's a brief summary of each method:

- shift(): Removes the first element of the array and returns it.
- unshift(): Adds one or more elements to the beginning of the array.
- pop(): Removes the last element of the array and returns it.
- push(): Adds one or more elements to the end of the array.

difference between local and global variables, along with their uses:

MCQ 1:
What is the scope of a local variable?

A) Entire program
B) Specific function or block
C) Only within a loop
D) Only within a conditional statement

Answer: B) Specific function or block

MCQ 2:
What is the purpose of declaring a variable as global?

A) To limit its access to a specific function
B) To make it accessible throughout the program
C) To reduce memory usage
D) To improve performance

Answer: B) To make it accessible throughout the program

MCQ 3:
What happens when a local variable and a global variable have the same name?

A) The local variable hides the global variable
B) The global variable hides the local variable
C) Both variables become undefined
D) Both variables become null

Answer: A) The local variable hides the global variable

MCQ 4:
When should you use a global variable?

A) When the variable is used throughout the program
B) When the variable is used only within a specific function
C) When the variable is used only within a loop
D) When the variable is used only within a conditional statement

Answer: A) When the variable is used throughout the program

n try-catch blocks:

MCQ 1:
What is the purpose of the try block in a try-catch statement?

A) To handle runtime errors
B) To throw exceptions
C) To enclose code that might throw an exception
D) To skip over code that might throw an exception

Answer: C) To enclose code that might throw an exception

MCQ 2:
What happens when an exception is thrown in the try block?

A) The program terminates immediately
B) The catch block is executed
C) The finally block is executed
D) The exception is ignored

Answer: B) The catch block is executed

MCQ 3:
What is the purpose of the finally block in a try-catch statement?

A) To handle runtime errors
B) To throw exceptions
C) To execute code regardless of whether an exception was thrown
D) To skip over code that might throw an exception

Answer: C) To execute code regardless of whether an exception was thrown

MCQ 4
try {
console.log("Hello");
throw new Error("Error occurred");
} catch (error) {
console.log("Caught: " + error.message);
}

A) Hello
B) Caught: Error occurred
C) Hello Caught: Error occurred
D) Error: Error occurred

Answer: C) Hello Caught: Error occurred

Function
MCQ 1:
Which of the following is an example of a function declaration?

A) let add = (a, b) => a + b;
B) function add(a, b) { return a + b; }
C) const add = function(a, b) { return a + b; }
D) var add = function(a, b) { return a + b; }

Answer: B) function add(a, b) { return a + b; }

MCQ 2:
Which of the following is an example of an arrow function?

A) function add(a, b) { return a + b; }
B) let add = (a, b) => a + b;
C) const add = function(a, b) { return a + b; }
D) var add = function(a, b) { return a + b; }

Answer: B) let add = (a, b) => a + b;

MCQ 3:
Which of the following is an example of a function expression?

A) function add(a, b) { return a + b; }
B) let add = (a, b) => a + b;
C) const add = function(a, b) { return a + b; }
D) All of the above

Answer: D) All of the above (function expressions can take many forms)

MCQ 4:
Which of the following is an example of an immediately invoked function expression (IIFE)?

A) function add(a, b) { return a + b; }
B) let add = (a, b) => a + b;
C) (function(a, b) { return a + b; })(1, 2);
D) const add = function(a, b) { return a + b; }

Answer: C) (function(a, b) { return a + b; })(1, 2);

Module

MCQ 1:
What is the purpose of the export keyword in a module?

A) To import a module
B) To export a module or its parts
C) To declare a variable
D) To define a function

Answer: B) To export a module or its parts

MCQ 2:
What is the difference between export default and export?

A) export default exports a single value, while export exports multiple values
B) export default exports multiple values, while export exports a single value
C) export default is used for named modules, while export is used for default modules
D) export default is used for default modules, while export is used for named modules

Answer: D) export default is used for default modules, while export is used for named modules

MCQ 3:
How do you import a default module?

A) import { moduleName } from 'modulePath';
B) import moduleName from 'modulePath';
C) import * as moduleName from 'modulePath';
D) import moduleName = require('modulePath');

Answer: B) import moduleName from 'modulePath';

MCQ 4:
How do you import a named module?

A) import { namedExport } from 'modulePath';
B) import namedExport from 'modulePath';
C) import * as namedExport from 'modulePath';
D) import namedExport = require('modulePath');

Answer: A) import { namedExport } from 'modulePath';

Let me know if you want more questions or help with anything else!



1. What is the purpose of declaring a variable in programming?

• To store a value
• To print a message
• To perform a calculation
• To call a function
2. Which data type is used to store numbers in programming?*

• string
• boolean
• number
• float
3. What is the data type of the variable "name" in the following code: let name = "John"?

• string
• number
• void
4. Which variable declaration allows a value to be changed later in the code?
class
• let
• const
• static
5¬¬¬¬.What is the data type of the variable "age" in the following code: let age = 25?
• let
• const
• number
• string
6. const message: string = "Hello World";
message = false;

• cannot re-assigned
• false
• hello world
• 1234
7. How do you recognize the string?
• string always be written in quotations or backticks
• string always be written in curly brackets
• string always be written in parenthesis()
• string always be written in angular brackets <>


8. Which code is using type annotation?

• const myMessage = "Hello World";
• const myMessage: string = "Hello World";
• console.log("Hello World");
• All of these

9. What does the command tsc --init do? *

• Initializes a new Node.js project
• Compiles TypeScript code
• Installs TypeScript
• make tsc configure file
10. Which of the following is a correct way to write a multiple-line comment in TypeScript? *

• /* This is a comment */

• // This is a comment
• ''' This is a comment '''

Answer
1. To store a value

2. number (Note: float is not a separate data type in TypeScript, but rather a subset of the number type)

3. string

4. let (because let allows reassignment, unlike const which does not)

5. number

6. cannot re-assigned (because const values cannot be reassigned)

7. string always be written in quotations or backticks (strings can be defined using single quotes, double quotes, or backticks)

8. const myMessage: string = "Hello World"; (this code uses type annotation to specify the data type of the variable)

9. make tsc configure file (the command tsc --init creates a tsconfig.json file, which is used to configure the TypeScript compiler)

10. _/ This is a comment /_ (this is the correct way to write a multiple-line comment in TypeScript)

ADVANCE QUIZ
1
What is the type of the variable x in the following code: let x = 10?

A) string
B) number
C) boolean
D) any

Answer: B) number

2
Which of the following is a valid way to declare a variable in TypeScript?

A) var x = 10
B) let x = 10
C) const x = 10
D) All of the above

Answer: D) All of the above

3
What is the data type of the variable y in the following code: let y = 'hello'?

A) number
B) string
C) boolean
D) any

Answer: B) string

4
What is the purpose of the any data type in TypeScript?

A) To represent a boolean value
B) To represent a string value
C) To represent any data type
D) To represent a numeric value

Answer: C) To represent any data type

5
Which data type is used to represent a collection of values in TypeScript?

A) Array
B) Object
C) String
D) Number

Answer: A) Array

6
What is the type of the variable z in the following code: let z = true?

A) number
B) string
C) boolean
D) any

Answer: C) boolean

7
How do you declare a constant variable in TypeScript?

A) let x = 10
B) const x = 10
C) var x = 10
D) x = 10

Answer: B) const x = 10

8
What is the data type of the variable a in the following code: let a = [1, 2, 3]?

A) number
B) string
C) array
D) any

Answer: C) array

9
Can you assign a string value to a variable declared with the number type?

A) Yes
B) No

Answer: B) No

10
What is the purpose of the never data type in TypeScript?

A) To represent a value that never occurs
B) To represent a value that always occurs
C) To represent a string value
D) To represent a numeric value

Answer: A) To represent a value that never occurs

11
Which data type is used to represent a key-value collection in TypeScript?

A) Array
B) Object
C) String
D) Number

Answer: B) Object

12
Can you declare a variable without specifying its data type in TypeScript?

A) Yes
B) No

Answer: A) Yes (using the any type)


Arrays and its method MCQS IMPORTANT



What is the output of the following code?

Const arr = [1, 2, 3, 4, 5];
Const result = arr.reduce((acc,current) => acc + current,0);
Console.log(result);

A) 15
B) 20

C) 25
D) 30
Correct answer
A) 15
2
What is the output of following code?

Const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Const result = arr.filter(num => num % 2 === 0);
Console.log(result);

A) [1,3,5]
B) [1, 2, 3, 4, 5]
C) [2, 4, 6, 8, 10]
D) [2, 5, 6, 9, 4]

Correct answer
B) [2, 4, 6, 8, 10]

What is the output of following code?

Const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Const result = arr.slice(2,7);
Console.log(result);

A) [1,3,6]
B) [3,4,5,6,7]
C) [3,4,5,6]
D) [2,3,4,5,6]

Correct answer
C) [3,4,5,6,7]

What is the output of the following code?

Const arr = [1, 2, 3, 4, 5];
Const result = arr.filter(num => num % 2 === 0).map(num => num * 2).reduce((acc,current)=> acc + current, 0)

Console.log(result);


A) 20
B) 12
C) 30

D) 40
Correct answer
B) 12

What is the output of following code?

Const arr = [“a”,”b”,”c”];
Const result = arr.join(“ -!- “);
Const result1 = arr.join(“ =/= “);
Console.log(result);
Console.log(result1);


A) A,b,c

B) [a =/= b =/= c=/= ] 2 [a -!- b -!- c -!- ]
C) [a -!- b -!- c -!- ] [a =/= b =/= c=/= ]
D) [a , b , c ]
Correct answer
B) [a -!- b -!- c -!- ] [a =/= b =/= c=/= ]

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Console.log(arr.includes(6));




A) true
B) false
C) 0

C) -1
Correct answer
B) false

Which method is use to concatenate two or more array?


A) merge()
B) join()
C) concat()
D) push()

Correct answer
D) Concat()

What is the output of following code?

Const arr = [1,2,3,4,5]
Const result = arr.map(num => num * 2)
Console.log(result);


A) [1, 2, 3]
B) [2, 4, 6, 8, 10]
C) [2, 4, 6, 8]
D) [3, 4, 5]

Correct answer
B) [2, 4, 6, 8, 10]

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Arr.unshift(0, -1);
Arr.pop();
Console.log(arr);


//* A) [0, -1, 1, 2, 3, 4]
//* A) [-1, 0, 1, 2, 3, 4]
//* A) [0, -1, 1, 2, 3, 5]

//* A) [-1, 0, 1, 2, 4, 5]
Correct answer
//* A) [0, -1, 1, 2, 3, 4]

What is the output of following code?

Const arr1 = [1,2]
Const arr2 = [9,10]
Const result = arr1.concat(arr2)
Console.log(result);


A) [1, 9, 2, 10]
B) [1, 2, 3, 4]
C) [1, 2, 9, 10]
D) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Correct answer
C) [1, 2, 9, 10]

What is the output of following code?

Const arr1 = [1, 2]
Const arr2 = [3, 4]
Const result =arr1.concat(arr2).join(“ – “)
Console.log(result)

A) [1,2,3,4]

B) [1 – 2 – 3 – 4]
C) 1 – 2 – 3 – 4
D) [ “1 – 2 – 3 – 4”]
Correct answer
B) 1 – 2 – 3 – 4

Which element is used to transform each element of an array?


A) filter()
B) reduce()
C) map()
D) join()

Correct answer
C) Map()

Which is the output of the following code ?

Const names:string[] = [“a”,”b”,”c”,”d”,”e”,”c”,”e”,”f”,”c”]
Const ans1:boolean = names.includes(“c”,3,)
Const ans2:boolean = names.includes(“c”,7,)
Console.log(ans1);
Console.log(ans2);


A) false false
B) true true
C) false true

D) True false
Correct answer
B) true true

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Arr.push(6, 7);
Arr.shift();
Console.log(arr);


A) [2, 3, 4, 5, 6, 7]
B) [6, 7, 2, 3, 4, 5]
C) [1, 3, 4, 5, 6, 7]

E) [7, 2, 3, 4, 5, 6]
Correct answer
A) [2, 3, 4, 5, 6, 7]

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Arr.fill(0, 1, 3);
Console.log(arr);


A) [1, 0, 0, 0, 5]
B) [1, 0, 3, 4, 5]
C) [1, 0, 0, 4, 5]
D) [1, 2, 3, 4, 0]

Correct answer
B) [1, 0, 0, 4, 5]

What is the purpose of the fill() method in an array?


A) To add elements to the end of an array
B) To remove elements from an array
C) To fill an array with a specified value….
D) To sort an array

Correct answer
C) To fill an array with a specified value….

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Console.log(arr.includes(3));


A) true
B) false
C) 0

D) -1
Correct answer
A) True

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Arr.push(6, 7);
Arr.shift();
Arr.splice(2, 1);
Console.log(arr);


A) [2, 3, 5, 6, 7]
B) [2, 4, 5, 6, 7]
C) [2, 3, 6, 7]
D) [7, 2, 3, 5, 6]

Correct answer
A) [2, 3, 5, 6, 7]

What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Arr.unshift(0, -1);
Arr.splice(2, 2);
Console.log(arr);


A) [-1, 0, 1, 4, 5]
B) [0, -1, 4, 5]
C) [0, -1, 1, 2, 5]
D) [0, -1, 3, 4, 5] right option


What is the output of the following code:

Let arr = [1, 2, 3, 4, 5];
Arr.slice(1, 3);
Console.log(arr);


A) [1, 2, 3, 4, 5]
B) [2, 3]
C) [1, 4, 5]
D) [1, 2, 4, 5]

Correct answer
B) [1, 4, 5]
1. What is the value of the variable "a"? Code


let a :number = 5;

a) 5

b) 33

c) "best"

d) undefined



Answer: a) 5



2. What is the benefit of using "let" instead of "var"?

a) Global scope

b) Blocked scope

c) Functional scope

d) None of the above



Answer: b) Blocked scope



3. Why does the code "console.log("let: " + z);" throw an error?

a) z is not defined in this scope

b) z is defined in this scope

c) z is a global variable

d) z is a constant



Answer: a) z is not defined in this scope



4. What is the purpose of the "import" statement in JavaScript?

a) To define a variable

b) To declare a function

c) To import a module or variable from another file

d) To export a variable



Answer: c) To import a module or variable from another file



5. What is the difference between "import a from "./first";" and "import {b, c} from "./second";)?

a) The first imports a default export, while the second imports named exports

b) The first imports named exports, while the second imports a default export

c) Both import default exports

d) Both import named exports



Answer: a) The first imports a default export, while the second imports named exports



6. What is the purpose of the "export" statement in JavaScript?

a) To import a module or variable from another file

b) To define a variable

c) To declare a function

d) To export a variable or module to another file



Answer: d) To export a variable or module to another file



7. What is the benefit of using ECMAScript modules?

a) They allow for global scope

b) They allow for blocked scope

c) They allow for easier import and export of modules and variables

d) They are not supported in modern browsers



Answer: c) They allow for easier import and export of modules and variables



8. What is the purpose of the "inquirer" module in JavaScript?

a) To prompt the user for input

b) To log output to the console

c) To import modules from other files

d) To export variables to other files



Answer: a) To prompt the user for input



NEW MCQS



1. What is the type of the variable "myname" in the code?
a) string
b) string | null
c) string | undefined
d) string | number

Answer: b) string | null

2. What is the value of "myname" after the code "myname = null;" is executed?
a) "zia"
b) null
c) undefined
d) 12

Answer: b) null

3. What happens when the code "myname = undefined;" is executed?
a) No error
b) Runtime error
c) Compile-time error
d) Syntax error

Answer: c) Compile-time error

4. What is the purpose of the "toString()" method in JavaScript?
a) To convert a value to a string
b) To convert a value to a number
c) To convert a value to a boolean
d) To convert a value to an object

Answer: a) To convert a value to a string

5. What is the type of the variable "myAge" in the code?
a) string
b) number
c) string | number
d) number | string

Answer: c) string | number

6. What is the value of "myAge" after the code "myAge = 16;" is executed?
a) "Dont Know"
b) 16
c) undefined
d) null

Answer: b) 16

7. What happens when the code "console.log(myAge.toLowerCase());" is executed?
a) No error
b) Runtime error
c) Compile-time error
d) Syntax error

Answer: c) Compile-time error

8. What is the purpose of the "toLowerCase()" method in JavaScript?
a) To convert a string to uppercase
b) To convert a string to lowercase
c) To convert a number to string
d) To convert a boolean to string

Answer: b) To convert a string to lowercase

9. What is the type of the variable "newAge" in the code?
a) string
b) number
c) string | number
d) number | string

Answer: c) string | number

10. What is the value of "newAge" after the code "let newAge = Math.random() > 0.6 ? "Khan" : 60;" is executed?
a) "Khan"
b) 60
c) undefined
d) null

Answer: a) "Khan" or b) 60

11. What happens when the code "newAge.toLowerCase();" is executed?
a) No error
b) Runtime error
c) Compile-time error
d) Syntax error

Answer: c) Compile-time error

12. What is the purpose of the "typeof" operator in JavaScript?
a) To check the type of a variable
b) To check the value of a variable
c) To check the scope of a variable
d) To check the hoisting of a variable

Answer: a) To check the type of a variable

13. What is the type of the variable "age" in the code?
a) number
b) string
c) number | string
d) number | "died" | "unknown"

Answer: d) number | "died" | "unknown"

14. What is the value of "age" after the code "age = 90;" is executed?
a) 90
b) "died"
c) "unknown"
d) "living"

Answer: a) 90

15. What happens when the code "age = "living";" is executed?
a) No error
b) Runtime error
c) Compile-time error
d) Syntax error

Answer: c) Compile-time error

16. What is the type of the variable "zia" in the code?
a) string
b) "zia"
c) "zia" | undefined
d) "zia" | null

Answer: b) "zia"

17. What happens when the code "zia = "khan";" is executed?
a) No error
b) Runtime error
c) Compile-time error
d) Syntax error

Answer: c) Compile-time error

18. What is the purpose of the "type alias" in TypeScript?
a) To create a new type
b) To create a new variable
c) To create a new function
d) To create a new class

Answer: a) To create a new type

Operators Quiz


1.What will message be?
• Let number = 11;
• Let message = number % 2 === 0 ? “Even” : “Odd”;
• Console.log(message);
2.What is the purpose of the else clause in an if-else statement?
• To execute code when the condition is true
• To call functions
• To declare variables
• To execute code when the condition is false

3.What does the following expression evaluate to?
Const result = (5 > 4) && (4 < 2);
• True
• False
• Undefine
• Null
4.What will the following expression return?
Const result = (undefined || ‘default’);
• False
• True
• Default
• Undefined
5.What is the purpose of the if statement in TypeScript?
• To loop through an array
• To make decisions based on conditions
• To declare variables
• To call functions

6.What will message be?

Let number = 13;

Let message = number % 2 === 0 ? “Even” : “Odd”;

Console.log(message);

• Even
• Odd
• 15
• Error
7.What is the purpose of the else clause in an if-else statement?
• To execute code when the condition is true
• To call functions
• To declare variables
• To execute code when the condition is false
8.What will be the output?

Let num = 10;

Let str = “10”;

If (num === str) {

Console.log(“Equal”);

} else {

Console.log(“Not Equal”);

}

• Equal
• Not Equal
• Error
• Undefined

9.What will the following code output?

Let isAvailable = false;

Console.log(!isAvailable);
• False
• Null
• Undefined
• True
10.What happens if the first operand of the && operator is false in TypeScript?
• It evaluates the second operand
• It skips evaluating the second operand
• It throws a runtime erro
• It depends on the tsconfig settings
11.What will be the output of the following TypeScript code?

Let a = 5;

Let b = 10;

Let result = (a > 0 && b++ > 5) && (a++ > 0);

Console.log(result: ${result}, a: ${a}, b: ${b});

• True, a:5, b:10
• False, a:6, b:11
• True, a: 6, b: 11
• False, a: 6, b: 11
12.What will be the output of the following TypeScript code snippet?

Let str: string = “hello”;

If (str === “HELLO”) {

Console.log(“Exact match”);

} else if (str.toLowerCase() === “hello”) {

Console.log(“Case-insensitive match”);

} else {

Console.log(“No match”);

}
• Hello
• Case-insensitive match
• No match
• HELLO
13. Given the following TypeScript code snippet, what will be the output?

Let x = 10;

Let y = 5;

If (x > 5 && y < 10) {

Console.log(“Condition is true”);

} else {

Console.log(“Condition is false”);

}
• Error
• Condition is true
• No output
• Condition is false
14. What will the following ternary operations evaluate to?

Const k = (5 > 3) ? ‘Yes’ : ‘No’;

Const l = (5 < 3) ? ‘Yes’ : (3 === 3) ? ‘Maybe’ : ‘No’;

Console.log(k, l);
• No Yes
• Yes Yes
• Yes Maybe
• Yes No
15. Given let x = true;

Let y = false;

What does (x && y) || (!x && !y) evaluate to?
• False
• Undefined
• Null
• True

16.Which logical operator would you use to check if a value is neither null nor undefined in TypeScript?
??
//
&&
!
Predict the output of the following code:

Const g = (true && false) || (false && true);

Const h = (true || false) && (false || true);

Console.log(g, h);
• False true
• True false
• True true
• False false
17. Let isAdmin: boolean = true;
Let isLoggedIn: boolean = false;
If (!isAdmin) {
Console.log(“You have access to admin privileges.”);
} else if (!isAdmin && isLoggedIn) {
Console.log(“You have access to regular user features.”);
} else {
Console.log(“You need to log in.”);
}
• You need to log in.
• You have access to admin privileges.
• You have access to regular user features.
• Other:


Function QUIZ/MCQS




Q1) Why do we use function in typescript?*
To enforce strict type checking
To create a class

To organize and reuse code
To declare a variable
Correct answer
To organize and reuse code

Q2) Tell me the output.
function myFunc(name: string = "babar"){
console.log(Hello ${name});
}
myFunc("Ahmed");

Hello Ahmed
Hello

Hello undefined
No output
Correct answer
Hello Ahmed

Q3) Mention the output.

function add(num1: number, num2?: number) {
if (!num2) {
return 10;
}
else{
return num1 + num2;
}
}
const myResult1 = add(5);
const myResult2 = add(8,4)
console.log(myResult1);
console.log(myResult2);

5, 12
12, 10

10, 12
5, 10
Correct answer
10, 12

Q4) Tell me the output.

const myFunc = () => {
return "Hello World"
}
myFunc()

undefined
Error

Hello World
No output
Correct answer
No output

Q5) How to introduce a 'default' parameter in typescript

By placing the parameter inside square brackets in the function declaration.

By using the default keyword before the parameter name in the function signature.
By providing a default value to the parameter in the function declaration.
By adding a question mark after the parameter name in the function declaration.
Correct answer
By providing a default value to the parameter in the function declaration.

Q6) Tell me the output.

function myFunc(data1: number, data2: number) {
let myValue: number = data1 + data2;
console.log(myValue * data2);
}
myFunc(5,10)

15
10

150
75
Correct answer
150

Q7) Which keyword is used to define a function in typescript?

func
class

def
function
Correct answer
function

Q8) Tell me the output

function myFunc(...data: string[]){
console.log(data[1]);
}
myFunc("Hello", "World")

Hello

Error
World
undefined
Correct answer
World

Q9) Which code is more accurate?*

const myFunc = (msg: string) => { return msg; }
const myFunc = (msg: string) => { msg }

const myFunc = (msg: string) => msg
const myFunc = (msg: string) => ( msg )
Correct answer
const myFunc = (msg: string) => msg

Q10) Why do we prefer arrow function over normal function?*

They offer more flexibility in defining optional parameter values
They provide stricter type checking and error handling

They offer more flexibility in defining default parameter values
They provide better performance due to their optimized syntax
Correct answer
They provide better performance due to their optimized syntax

Q11) Which one is the correct return type of the following function?

function myFunc(data1:number, data2: string){
const variable = data1 + data2;
return variable;
}
myFunc(10, "Hello");

number
void

string
none of these
Correct answer
string

Q12) Tell me the output.

function myFunc(data1?: string, data2?: string) {
if(data1){
return data2
}
if(data2){
return data1
}
}
const answer = myFunc("Hello")
console.log(answer);

Hello
No output
undefined

Error

Q13) What will be the output.

function firstPerson(): string{
return "My name is Salman";
}
function secondPerson(): string{
return "My name is Ahmed";
}
const message: string = 10 < 5 ? firstPerson() : secondPerson();
console.log(message);

My name is Ahmed
undefined
My name is Salman

Error
Correct answer
My name is Ahmed

Q14) Tell me the output.

function myFunc(data?:string){
return data;
}
const myAnswer = myFunc();
console.log(myAnswer);


Syntax Error
myAnswer

NaN
undefined
Correct answer
undefined

Q15) Mention the output.

function myFunc(value: boolean){
const myMessage: string = !value === false ? "Yes" : "No";
return myMessage;
}
const myAnswer1: string = myFunc(true);
const myAnswer2: string = myFunc(false);
console.log(myAnswer1);
console.log(myAnswer2);

Yes, Yes
Yes, No

No, Yes
No, No

Q16) Tell me the output.

function add(str1: string, str2: string): string{
return str2 + str1;
}
const myResult = add("Hello", "World ");
console.log(myResult);

Hello World
WorldHello
HelloWorld

World Hello
Correct answer
World Hello

Q17) What is the return type of the following function?
function myFunc(data1: string, data2: number){
console.log(data1 + data2);
}
myFunc("Hello", 10)

number
string

void
null
Correct answer
void

Q18) Mention the output of the following function

let myNum: number = 10;
function myFunc(myNum: number){
console.log(myNum);
myNum = 20;
console.log(myNum);
}
myFunc(5);
console.log(myNum);

10, 20, 5
5, 10, 20

5, 20, 10
5, 20, 20
Correct answer
5, 20, 10

Q19) How to introduce an 'optional' parameter in typescript


By adding a question mark after the parameter name in the function declaration.
By using the optional keyword before the parameter name in the function signature.

By placing the parameter inside square brackets in the function declaration.
By providing a default value to the parameter in the function declaration.
Correct answer
By adding a question mark after the parameter name in the function declaration.

Q20) Which type of function is described?

const myFunc = function(){
console.log("Hello World");
}
myFunc()

Named Function
Arrow Function

Anonymous function
Method function
Correct answer
Anonymous function




Project Code

CALCULATOR TYPESCRIPT CODE PROJECT 00

#! /usr/bin/env node k
import inquirer from "inquirer";
const answer = await inquirer.prompt([
{ message: "Enter your first number", type: "number", name: "firstNumber" },
{ message: "Enter your second number", type: "number", name: "secondNumber" },
{
message: "Select one of operators to perform action ",
type: "list",
name: "operator",
choices: ["ADDITION", "SUBTRACTION", "MULTIPLICATION", "DIVISION"],
},
]);
// CONDITIONAL STATEMENT
if (answer.operator === "ADDITION") {
console.log(answer.firstNumber + answer.secondNumber);
}
else if (answer.operator === "SUBTRACTION") {
console.log(answer.firstNumber - answer.secondNumber);
}
else if (answer.operator === "MULTIPLICATION") {
console.log(answer.firstNumber * answer.secondNumber);
}
else if (answer.operator === "DIVISION") {
console.log(answer.firstNumber / answer.secondNumber);
}
else {
"PLease select correct operator";
}



NUMBER GUESSING GAME PROJECT 01


#! /usr/bin/env node
console.log("Guess a number between 1 to 8");
// now varible create
let a:number=Math.floor(Math.random()*7)
import inquirer from "inquirer";
while(true){
let input = await inquirer.prompt(
{name: "guess",type:"number",
message:"Enter your guess number you want between 1 to 8:"}
)

// provide code
let ans:number= input.guess
if (a==ans)
{console.log("congratulation your guess number is correct")
break;}
else{console.log("Sorry you guess wrong number try again ")}

}




TO DO LIST PROJECT 04


import inquirer from 'inquirer'
let todos = [];
let condition = true;

while(condition)
{
let addTask = await inquirer.prompt(
[
{
name: 'todo',
type: 'input',
message: 'EID ki shopping kya kya ki hai'
},
{
name: 'addMore',
type: 'confirm',
message: 'aur kya khareeda',
default: 'false'
}
]
);

todos.push(addTask.todo);
condition = addTask.addMore
console.log(todos)
}




QUIZ PROJECT 7


#! /usr/bin/env node

import * as readline from "readline";

// Define the interface for a question
interface Question {
question: string;
options: string[];
correctAnswerIndex: number;
}

// Define the interface for a quiz
interface Quiz {
questions: Question[];
}

// Define a function to shuffle an array
function shuffleArray(array: T[]): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

// Define a function to run the quiz
function runQuiz(quiz: Quiz, quizNumber: number): void {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

rl.question(`Quiz ${quizNumber}: Press Enter to start the quiz...`, () => {
let score = 0;

// Shuffle questions to randomize order
const shuffledQuestions = shuffleArray(quiz.questions);

askQuestion(0);

function askQuestion(index: number): void {
if (index < shuffledQuestions.length) {
const question = shuffledQuestions[index];

console.log(`Question ${index + 1}: ${question.question}`);
for (let j = 0; j < question.options.length; j++) {
console.log(`${j + 1}. ${question.options[j]}`);
}

rl.question("Enter your answer (1, 2, 3, etc.): ", (userAnswer) => {
const userAnswerIndex = parseInt(userAnswer) - 1;

if (userAnswerIndex === question.correctAnswerIndex) {
console.log("Correct!");
score++;
} else {
console.log(
"Incorrect! The correct answer is: " +
question.options[question.correctAnswerIndex],
);
}
askQuestion(index + 1);
});
} else {
rl.close();
const percentageScore = (score / shuffledQuestions.length) * 100;
console.log( `Quiz ${quizNumber} Complete! Your Score: ${score}/${shuffledQuestions.length} (${percentageScore}%)`,
);
}
}
});
}

// Example quiz
const myQuiz: Quiz = {
questions: [
{
question: "What is the capital of France?",
options: ["London", "Paris", "Berlin"],
correctAnswerIndex: 1,
},
{
question: "What is 2 + 2?",
options: ["3", "4", "5"],
correctAnswerIndex: 1,
},
{
question: "Which planet is known as the Red Planet?",
options: ["Earth", "Mars", "Venus"],
correctAnswerIndex: 1,
},
],
};

// Run the quiz
runQuiz(myQuiz, 1);



EXERCISE 45 QUESTION SOLUTION

// //EXERCISE 45 TYPESCRIPT ANSWER
// // EXERCISE_1
// console.log("Hello World!")

// // EXERCISE_2
// let personName: string= "ERIC";
// console.log(`hellow ${personName}, would you like to learn some Python today?`);

// // EXERCISE_3
// // // lower case
// // let personName: string ="Babar"
// // console.log("lowercase:", personName.toLowerCase());

// // // upper case
// // console.log("uppercase:", personName.toLocaleUpperCase());

// // // Title case
// // console.log("titlecase:", personName.replace(/\bw/g,c => c.toUpperCase()));






// // EXERCISE_4
// let qoute: string= "A person who never made a mistake never tried anything new";
// let author: string= "Albert Einstein"
// console.log(`${author} once said, "${qoute}`);
// // EXERCISE_5
// let qoute: string= "A person who never made a mistake never tried anything new";
// let famous_person="Albert Einstein";
// let message=`${famous_person} once said, ${qoute}`;
// console.log(message);

// // EXERCISE_6
// let personName: string =`\n\t BABAR AZAM\t\n`;
// console.log(personName);
// let stripped: string = personName.trim();
// console.log(stripped);




// // EXERCISE_7 &EXERCISE_8

// console.log(87 +3);
// console.log(54 -3);
// console.log(4 *2);
// console.log(16 / 2);

// // EXERCISE_9
// // let favoriteNumber: number= 4;
// // console.log(`My favorite Number is ${favoriteNumber}`);

// // EXERCISE_10
// // program written by:BABAR
// //Current date: 19/02/2024
// // this is simple 1st program we write just write hello world
// // console.log('hellow world')

// // let names: string[] =['EINSTEIN','AFRIDI','RONALDO','KOHLI'];

// // for(let i = 0; i // // console.log(names[i]) ;
// // }
// // EXERCISE_11
// // let members: string[] =['azam','saqlain','mehmood','saba','sana'];
// // for(let i=0; i // // console.log(members[i]);
// // }
// // EXERCISE_12
// let members: string[] =['azam','saqlain','mehmood','saba','sana'];
// let message: string='kal birthday hai kis ki:';
// for(let i=0; i // console.log(message + members[i]);
// }
// // EXERCISE_13
// let members: string[] =['bike','car'];
// for(let i=0; i // console.log(message + members[i]);
// }
// // EXERCISE_14
// let guest_list : string [] = ['ali','farhan','raza','ayesha'];
// for(let i=0; i // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// }
// export{guest_list}
// // EXERCISE_15
// let guest_list : string [] = ['ali','farhan','raza','ayesha'];
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')

// // }
// let not_present : string = 'farhan';
// let new_guest : string = 'Babar Azam';
// guest_list[1] = new_guest;
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }

// // EXERCISE_16
// let guest_list : string [] = ['ali','farhan','raza','ayesha'];
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }
// let not_present : string = 'farhan';
// let new_guest : string = 'Babar Azam';
// guest_list[1] = new_guest;
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }

// // EXERCISE_17
// let guest_list : string [] = ['ali','farhan','raza','ayesha'];
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }
// let not_present : string = 'farhan';
// let new_guest : string = 'Babar Azam';
// guest_list[1] = new_guest;
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }
// guest_list.unshift('shaheen','sarfaraz','rizwan');
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow. we found big table so we decide to invite 3 more guest\nThank You\n')
// // }
// console.log('\nUnfortunately we can not arrange big table,Only two people invited.');
// while(guest_list.length>2){
// let remove_guest = guest_list.pop();
// console.log(`sorry MR. ${remove_guest} you are not invited for dinner.`);
// }
// for(let i=0; i // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nYES YOU ARE STILL INVITED on TOMORROW dinner \nThank You\n')
// }
// guest_list.splice(0,2,);
// console.log(guest_list);

// // EXERCISE_18
// let places : string [] = ['cape town','delhi','faisalbad','bankok','ahmedabad']
// // console.log('original :' + places);
// // Print your array in alphabetical order without modifying the actual list.
// // console.log('copy ' + [...places].sort());

// // • Show that your array is still in its original order by printing it.
// console.log('original :' + places);

// // • Print your array in reverse alphabetical order without changing the order of the original list.
// console.log('copy ' + [...places].sort().reverse());

// // • Show that your array is still in its original order by printing it again.
// console.log('copy ' + [...places].sort().reverse());

// // • Reverse the order of your list. Print the array to show that its order has changed.
// console.log('original :' + places.sort());

// // • Reverse the order of your list again. Print the list to show it’s back to its original order.
// console.log('original :' + places.sort().reverse());




// // EXERCISE_19
// let guest_list : string [] = ['ali','farhan','raza','ayesha'];
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }
// let not_present : string = 'farhan';
// let new_guest : string = 'Babar Azam';
// guest_list[1] = new_guest;
// // for(let i=0; i // // console.log('Respeted Sir/Madam ' + guest_list[i] + ',\nWe invited you on dinner tomorrow.\nThank You\n')
// // }
// // • Reverse the order of your list. Print the array to show that its order has changed.
// console.log('original :' + places.sort());

// // • Reverse the order of your list again. Print the list to show it’s back to its original order.

// console.log('original :' + places.sort().reverse());
// // EXERCISE_20
// const languages : string [] = ['english','urdu','hindi','french','arabic']
// console.log("List of countries:")
// for(let top of languages){
// console.log(top)
// }

// // EXERCISE_21
// interface Item {
// name: string;
// price: number;
// }

// // Create two objects using the interface
// const book: Item = {
// name: "ESSENTIAL TYPESCRIPT ",
// price: 12.99,
// };

// const apple: Item = {
// name: "Apple",
// price: 0.99,
// };

// // Access and print the object properties
// console.log(`Book name: ${book.name}, price: $${book.price}`);
// console.log(`Apple name: ${apple.name}, price: $${apple.price}`);


// // EXERCISE_22
// // Define an interface for the object structure
// interface Item {
// name: string;
// price: number;
// }

// // Create two objects using the interface
// const book: Item = {
// name: "ESSENTIAL TYPESCRIPT ",
// price: 12.99,
// };

// const apple: Item = {
// name: "Apple",
// price: 0.99,
// };

// // Access and print the object properties
// console.log(`Book name: ${book.name}, price: $${book.price}`);
// console.log(`Apple name: ${apple.name}, price: $${apple.price}`);



// // EXERCISE_23
// let cars: string = 'subaru';

// // Test 1: Equality comparison (True)
// console.log("Is car == 'subaru'? I predict True.");
// console.log(car == 'subaru'); // True

// // Test 2: Strict equality comparison (True)
// console.log("Is car === 'subaru'? I predict True.");
// console.log(car === 'subaru'); // True

// // EXERCISE_24
// let car: string = 'subaru';
// let age: number = 25;
// let numbers: number[] = [1, 2, 3, 4];



// // **String Tests**

// // Test 1: Equality (True)
// console.log("Is car == 'Subaru'? I predict True.");
// console.log(car == 'Subaru'); // True (case-insensitive)

// // Test 2: Strict equality (False)
// console.log("Is car === 'Subaru'? I predict False.");
// console.log(car === 'Subaru'); // False (case-sensitive)



// // Test 3: Inequality (True)
// console.log("Is car != 'Toyota'? I predict True.");
// console.log(car != 'Toyota'); // True

// // Test 4: Inequality (False)
// console.log("Is car !== 'subaru'? I predict False.");
// console.log(car !== 'subaru'); // False (case-sensitive)


// // **Lowercase Function Tests**

// // Test 5: Lowercase conversion (True)
// console.log("Is car.toLowerCase() == 'subaru'? I predict True.");
// console.log(car.toLowerCase() == 'subaru'); // True (converted to lowercase)

// // Test 6: Lowercase conversion (False)
// console.log("Is car === car.toLowerCase()? I predict False.");
// console.log(car === car.toLowerCase()); // False (original value remains uppercase)

// // **Numerical Tests**

// // Test 7: Equality (True)
// console.log("Is age == 25? I predict True.");
// console.log(age == 25); // True





// Test 8: Inequality (False)
// console.log("Is age != 30? I predict True.");
// console.log(age != 30); // True



// // Test 9: Greater than (False)
// console.log("Is age > 30? I predict False.");
// console.log(age > 30); // False

// // Test 10: Less than or equal (True)
// console.log("Is age <= 25? I predict True.");
// console.log(age <= 25); // True
// // EXERCISE_25 &EXERCISE_26
// if(alien_color == "green"){
// console.log("the player just earned 5 points.");
// }

// // Write one version of this program that passes the if test and another that fails.
// // (The version that fails will have no output.)

// alien_color = "red";
// if(alien_color == "green"){
// console.log("the player just earned 5 points.");
// }

// // EXERCISE_27
// let alien_color: string ="green";
// // If the alien is green, print a message that the player earned 5 points.

// if(alien_color == "green"){
// console.log("the player earned 5 points.");
// }

// // • If the alien is yellow, print a message that the player earned 10 points.
// else if(alien_color == "yellow"){
// console.log("the player just earned 10 points.");
// }

// // • If the alien is red, print a message that the player earned 15 points.
// else if(alien_color == "red"){
// console.log("the player just earned 15 points.");
// }
// else{
// console.log("Please select right color")
// }
// // • Write three versions of this program, making sure
// // each message is printed for the appropriate color alien.

// // version 2
// alien_color ="red";
// if(alien_color == "green"){
// console.log("the player earned 5 points.");
// }
// else if(alien_color == "yellow"){
// console.log("the player just earned 10 points.");
// }
// else if(alien_color == "red"){
// console.log("the player just earned 15 points.");
// }
// else{
// console.log("Please select right color")
// }

// // version 3
// alien_color ="yellow";
// if(alien_color == "green"){
// console.log("the player earned 5 points.");
// }
// else if(alien_color == "yellow"){
// console.log("the player just earned 10 points.");
// }
// else if(alien_color == "red"){
// console.log("the player just earned 15 points.");
// }
// else{
// console.log("Please select right color")
// }

// // EXERCISE_28
// let age: number = 15;
// if(age<2){
// console.log("the person is a baby.")
// }

// // • If the person is at least 2 years old but less than 4, print
// // a message that the person is a toddler.

// else if(age>=2 && age <4){
// console.log("person is a toddler.")
// }

// // • If the person is at least 4 years old but less than 13,
// // print a message that the person is a kid.
// else if(age>=4 && age <13){
// console.log("person is a kid.")
// }

// // • If the person is at least 13 years old but less than 20,
// // print a message that the person is a teenager.

// else if(age>=13 && age <20){
// console.log("person is a teenager.")
// }
// // • If the person is at least 20 years old but less than 65,
// // print a message that the person is an adult.
// else if(age>=20 && age <65){
// console.log("person is a adult.")
// }
// // • If the person is age 65 or older, print a
// // message that the person is an elder
// else{
// console.log("Person is an elder.")
// }

// // EXERCISE_29
// let favorite_fruits : string [] = ['apple','orange','grapes']

// if(favorite_fruits.includes('apple')){
// console.log('I really like apple!')
// }

// if(favorite_fruits.includes('orange')){
// console.log('I really like orange!')
// }

// if(favorite_fruits.includes('mango')){
// console.log('I really like mango!')
// }

// if(favorite_fruits.includes('grapes')){
// console.log('I really like grapes!')
// }

// if(favorite_fruits.includes('bananas')){
// console.log('I really like bananas!')
// }


// // EXERCISE_30
// let users : string [] = ['sana','babar','saba','taha','admin']

// for(let user of users){
// if (user === "admin"){
// console.log("hello admin, would you like to see a status report?")
// }
// else{
// console.log(`Hello ${user}, 'thank you for logging in again.'`)
// }
// }

// // EXERCISE_31
// let users : string [] = ['sana','babar','saba','taha','admin']
// if(users.length === 0){
// console.log("We need to find some users! ")
// }
// // • Remove all of the usernames from your array,
// // and make sure the correct message is printed
// else{
// users = [];
// console.log("All user have been removed " + users.length)
// }
// // EXERCISE_32
// let current_users: string[] = ["saba", "admin", "ahmed", "babar", "raza"];
// let new_users: string[] = ["fawad", "hussain", "user7", "admin", "User9"];

// new_users.forEach((newUser) => {
// if (
// current_users.some(
// (currentUser) => currentUser.toLowerCase() === newUser.toLowerCase()
// )

// ) {
// console.log(`${newUser} will need to enter a new username.`);
// } else {

// console.log(`${newUser} is available.`);
// }
// });

// // EXERCISE_33
// let myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// // for loop
// for(let i = 0; i < myNumbers.length; i++){
// // now we use conditions
// if(myNumbers[i] == 1){
// console.log(`${myNumbers[i]}st`);
// }else if(myNumbers[i] == 2){
// console.log(`${myNumbers[i]}nd`);

// }else if(myNumbers[i] == 3){
// console.log(`${myNumbers[i]}rd`);

// }else if(myNumbers[i] >= 4 && myNumbers[i] <= 9){
// console.log(`${myNumbers[i]}th`);
// }

// }


// // EXERCISE_34
// let myPizza = ["Cheeze Pizza", "Pepperoni Pizza", "Vegeterian Pizza"];

// // print only names of pizza
// for (let i = 0; i < myPizza.length; i++) {
// console.log(myPizza[i]);
// }

// // EXERCISE_35
// let animal: string[] = ["dog", "elephant", "rabbit"];


// animals.forEach(animal => {
// console.log(`A ${animal} would make a great pet.`);
// });
// console.log("Any of these animals would make a great pet!");

// // EXERCISE_36
// function make_shirt(size: string, message: string) {
// console.log(`Making a ${size} t-shirt with the message "${message}" printed on it.`);
// }

// make_shirt("medium", "Code is Life");

// // EXERCISE_37
// function make_shirt(size: string = "large", message: string = "I love TypeScript") {
// console.log(`Making a ${size} t-shirt with the message "${message}" printed on it.`);

// }



// make_shirt(); // Default large and message

// make_shirt("medium"); // Default message, medium size

// make_shirt("small", "Dive into Coding"); // Custom message, small size



// // EXERCISE_38

// // function describe_city(nameOfCity: string, country: string = "Pakistan"){

// // return `${nameOfCity} is in ${country}`;

// // };



// // // 3 cities



// // let city1 = describe_city("South africa,cape town");



// // let city2 = describe_city("India,delhi");

// // let city3 = describe_city("Pakistan, Hyderabad");

// // let city4 = describe_city("Dubai", "UAE");



// // console.log(city1);

// // console.log(city2);

// // console.log(city3);

// // console.log(city4);



// // EXERCISE_39

// function city_country(city: string, country: string){

// // return `"${city}, ${country}"`

// console.log(`"${city}, ${country}"`)

// }



// city_country("Karachi", "Pakistan");



// let mycities = city_country("Karachi", "Pakistan");

// console.log(mycities);



// console.log(city_country("Dubai", "UAE"));

// console.log(city_country("London", "United Kingdom"));

// console.log(city_country("Riyaz", "Saudi Aarbia"));



// // EXERCISE_40

// function myAlbum(artistName: string, albumTitle: string){

// return {artistName, albumTitle}

// }



// let album1 = myAlbum("Ali", "Rang-e-Mohabat");

// let album2 = myAlbum("Madad", "Roshan Andhera");

// let album3 = myAlbum("Ayaz", "Mausam-e-Dil");



// console.log(album1);

// console.log(album2);

// console.log(album3);





// // Number of tracks

// function myAlbum2(artistName: string, albumTitle: string, numberOfTracks?: number){


// return {artistName, albumTitle, numberOfTracks}

// }



// let album4 = myAlbum2("Ali", "dil hai", 30);

// let album5 = myAlbum2("Madad", "ajeeb kahani", 55);

// let album6 = myAlbum2("babar", "typescript ki coding", 78);



// console.log(album4);

// console.log(album5);

// console.log(album6);



// // EXERCISE_41

// // let magicianNames = ["Ayaz", "Fayaz", "Tariq", "Madad"];



// // function show_magicians(){

// // for(let item of magicianNames){

// // console.log(item);

// // }

// // };



// // EXERCISE_42

// let magicianNames = ["Ayaz", "Fayaz", "Tariq", "Madad"];



// function show_magicians(greet: string){



// for(let item of magicianNames){

// console.log(greet, item);

// }

// };



// show_magicians("Hello, How are you Mr.");

// show_magicians("Hello, "); //2nd time calling



// // EXERCISE_43

// let magicianNames2 = ["Ayaz", "Fayaz", "Tariq", "Madad"];



// // making a copy of an array

// let magicianNamesCopy = [...magicianNames2];



// function show_magicians(greet: string){

// let withGreetings = "";



// for(let item of magicianNamesCopy){

// withGreetings += `${greet} ${item}\n`;

// }

// return withGreetings;

// };

// let myGreetings = show_magicians("Hello");

// let makeArray = myGreetings.split('\n');

// console.log(makeArray);



// // original array

// console.log(magicianNames2)


// // EXERCISE_44

// function mySandwiches(...items: string []){

// return `I want Sandwich of ${items}`;

// };



// let collection1 = mySandwiches("Ham", " Cheeze", " Lettuce"); // can add as many you wish

// let collection2 = mySandwiches("Turkey", " Swiss");

// let collection3 = mySandwiches(); // without arrgument



// console.log(collection1);

// console.log(collection2);

// console.log(collection3);



// // EXERCISE_45

// function carDetails (manufacturer: string, modelName: string, ...additionalInfo){



// const car = {manufacturer, modelName, ...Object.fromEntries(additionalInfo)};

// return car;

// };



// const myCarDetails = carDetails("Toyota", "Corolla", ['color', 'blue'], ['year', 2022]);



// console.log(myCarDetails);




HTML BEGINERS CODE








Sir ZIA REPO AND EXAM QUESTION LEAK/PRACTICE



NODE_PROJECTS



step00_helloworld

let message = "Hello World";// Infering Types,
//take your cursor on the variable name
console.log(message);


step00a_json_objects

JSON stands for Javascript Object Notation.

JSON is a text-based data format that is used to store and transfer data.

// JSON syntax

{

"name": "Vipin",

"age": 21,

"gender": "male",
}


step00b_syntax_error

lett message = "Hello World";//syntax error
console.log(message);


step00c_type_error

let message = "Hello World";
console.loger(message);


step00d_assignability_error

let message = "Hello World";

message = 6;
console.log(message);


step01_strong_typing

//strongly typed syntax
let a : string = "Pakistan";
a = "USA";
let b : number = 9;
let c : boolean = true;

//type inference
let e = "USA";
let f = 10.9;
f = 22;
let g = false;
g = true;


step02_const_let

//use const where variable values do not change
const a = 5;
const b : number = 33;
const c ="best";

//I suggest use let instead of var everywhere,
//becuase let has blocked scope
if (true) {
let z = 4;
//use z
}
else {
let z = "string";
//use z
}
console.log("let: " + z);// Error: z is not defined in this scope


step03a_modules

import a from "./first";
import {b, c as d} from "./second";
console.log(a + b + d);


step03b_native_ECMAScript_modules

import a from "./first.js";
import {b, c} from "./second.js";

console.log(a + b + c);
//two file create karni hai
let a = 5;

export default a;


step03c_import_inquirer_ECMAScript_module

import inquirer from "inquirer";

let answers = await inquirer.prompt([{
name: "age",
type: "number",
message: "Enter your Age:"}
]);

console.log("Insha Allah, in " + (60 - answers.age) + " years you will be 60 years old.");


step03d_chalk

import inquirer from "inquirer";
import chalk from "chalk";

let answers = await inquirer.prompt([{
name: "age",
type: "number",
message: "Enter your Age:"}
]);

console.log(chalk.blue("Insha Allah, in " + (60 - answers.age) + " years you will be 60 years old."));


step04_unions_literals

let myname: string | null;

myname = null;
console.log(myname);

myname = "zia";
console.log(myname);

//myname = undefined; //Error
//myname = 12; //Error

let myAge: string | number;

myAge = 16;//narrowing
console.log(myAge);

//console.log(myAge.toLowerCase());//Error

myAge = "Dont Know";//narrowing
console.log(myAge);

console.log(myAge.toString()); // common to both types
//can be called even without narrowing

console.log(myAge.toLowerCase());//Can be called on string
//because of narrowing

let newAge = Math.random() > 0.6 ? "Khan": 60;

//newAge.toLowerCase();//Error: Transpiler cannot narrow

if (newAge === "Khan") {
// Type of newAge: string
newAge.toUpperCase(); // Can be called
}

if(typeof newAge === "string"){
// Type of newAge: string
newAge.toUpperCase(); // Can be called
}

typeof newAge === "string"
? newAge.toUpperCase() // Ok: string
: newAge.toFixed(); // Ok: number


let age: number | "died" | "unknown";

age = 90;//OK
age = "died";//OK
age = "unknown";//OK
//age = "living";//Error


let zia: "zia";

zia = "zia";
//zia = "khan";//Error


let yourName = Math.random() > 0.6 ? "Hira Khan": undefined;

if (yourName) {
yourName.toUpperCase(); // Ok: string
}

//yourName.toUpperCase();//Error: Object is possibly 'undefined'.

yourName?.toUpperCase();//OK

// You can also define a type alias
type RawData = boolean | number | string | null | undefined;

let data: RawData;

// You can even combine them

type Id = number | string;

type IdMaybe = Id | undefined | null;


step05a_objects

.
let teacher = {
name: "Zeeshan",
experience: "10"
}

console.log(teacher.name);
console.log(teacher["experience"]);


// Type Declaration
let student : {
name: string,
age: number
}

student = {
name: "Hira",
age: 30
}

console.log(student["name"]);
console.log(student.age);



step05b_object_aliased


// anonymous

let teacher : {name: string, exp: number} = {
name: "Zeeshan",
exp: 10
}

// Aliased Object Type
type Student = {
name: string,
age?: number
}

let student: Student = {
name: "Hira",
age: 30
}

console.log(student["name"]);
console.log(student.age);

// Interfaces

interface Manager {
name: string,
subordiates?: number
}

let storeManager: Manager = {
name: "Bilal"
}



step05c_structural_typing_object_literals


// These two interfaces are completely
// transferrable in a structural type system:

interface Ball {
diameter: number;
}

interface Sphere {
diameter: number;
}

let ball: Ball = { diameter: 10 };
let sphere: Sphere = { diameter: 20 };

sphere = ball;
ball = sphere;

// If we add in a type which structurally contains all of
// the members of Ball and Sphere, then it also can be
// set to be a ball or sphere.

interface Tube {
diameter: number;
length: number;
}

let tube: Tube = { diameter: 12, length: 3 };

//tube = ball;//Error
ball = tube;

// Because a ball does not have a length, then it cannot be
// assigned to the tube variable. However, all of the members
// of Ball are inside tube, and so it can be assigned.

// TypeScript is comparing each member in the type against
// each other to verify their equality.

//===================================================

// Now lets do it Case By Case


//Case when "FRESH"" object literal are assigned to a variable
//Rule: When a fresh object literal is assigned to a variable or passed for a parameter of a non-empty target type,
//it is an error for the object literal to specify properties that don't exist in the target type.
//The rationale for the below two errors is that since the fresh types of the object literals are
//never captured in variables, static knowledge of the excess or misspelled properties should not be silently lost.

let myType = { name: "Zia", id: 1 };

//Case 1
myType = { id: 2, name: "Tom" };//Case 1: can only assign a type which has the the same properties
//Object literals can only have properties that exist in contextual type


//Case 2a
myType = { id: 2, name_person: "Tom" };//Case 2a: Error, renamed or missing property

//Case 2b
//A type can include an index signature to explicitly indicate that excess properties are permitted in with fresh objects:

var x: { id: number, [x: string]: any };//Note now 'x' can have any name, just that the property should be of type string

x = { id: 1, fullname: "Zia" }; // Ok, `fullname` matched by index signature


//Case 3
myType = { id: 2, name: "Tom", age: 22 };//Case 3: Error, excess property



//=================================================


//Case when STALE object literal are assigned to a variable

let myType2 = { id: 2, name: "Tom" };

//Case 1
myType = myType2;//Case 1: can only assign a type which has the the same properties, rule same for fresh and stale object

let myType3 = { id: 2, name_person: "Tom" };
//Case 2a
myType = myType3;//Case 2: Error, renamed or missing property, rule same for stale and fresh object


//Case 2b
//A type can include an index signature to explicitly indicate that excess properties are permitted in with fresh objects:

var x: { id: number, [x: string]: any };//Note now 'x' can have any name, just that the property should be of type string
var y = { id: 1, fullname: "Zia" };
x = y;// Ok, `fullname` matched by index signature


var myType4 = { id: 2, name: "Tom", age: 22 };

//Case 3
myType = myType4;//Case 3: Ok, excess property allowed in case of stale object which is different from fresh object





/*
var x: { foo: number };
x = { foo: 1, baz: 2 }; // Error, excess property `baz`

var y: { foo: number, bar?: number };
y = { foo: 1, baz: 2 }; // Error, excess or misspelled property `baz`



var a: { foo: number };
var a1 = { foo: 1, baz: 2 };
a = a1;//No Error

var z: { foo: number, bar?: number };
var z1 = { foo: 1, baz: 2 };
z = z1;//No Error
*/



step05d_nested_objects


type Author = {
firstName: string;
lastName: string;
};

type Book = {
author: Author;
name: string;
};

const myBook : Book = {
author: {
firstName: "Zia",
lastName: "Khan"
},
name: "My Best Book"
}



step05e_intersection_types


interface Student {
student_id: number;
name: string;
}

interface Teacher {
teacher_Id: number;
teacher_name: string;
}

type intersected_type = Student & Teacher;

let obj1: intersected_type = {
student_id: 3232,
name: "rita",
teacher_Id: 7873,
teacher_name: "seema",
};

console.log(obj1.teacher_Id);
console.log(obj1.name);



step05f_any__unknown_never_types


// Any

let myval: any;

myval = true; // OK
myval = 42; // OK
myval = "hey!"; // OK
myval = []; // OK
myval = {}; // OK
myval = Math.random; // OK
myval = null; // OK
myval = undefined; // OK
myval = () => { console.log('Hey again!'); }; // OK


//Unknown

let value: unknown;

value = true; // OK
value = 42; // OK
value = "hey!"; // OK
value = []; // OK
value = {}; // OK
value = Math.random; // OK
value = null; // OK
value = undefined; // OK
value = () => { console.log('Hey again!'); }; // OK


// Assigning a value of type unknown to variables of other types

let val: unknown;

const val1: unknown = val; // OK
const val2: any = val; // OK
const val3: boolean = val; // Will throw error
const val4: number = val; // Will throw error
const val5: string = val; // Will throw error
const val6: Record = val; // Will throw error
const val7: any[] = val; // Will throw error
const val8: (...args: any[]) => void = val; // Will throw error


// Never

// Function returning never must not have a reachable end point
function error(message: string): never {
throw new Error(message);
}

// Inferred return type is never
function fail() {
return error("Something failed");
}

// Function returning never must not have a reachable end point
function infiniteLoop(): never {
while (true) {}
}



step06_explict_casting


let myname: unknown = "Zia";
console.log((myname as string).length);
console.log(( myname).length)



step07a_enum


enum Color {Red, Green, Blue};//starts with 0
var c: Color = Color.Green;

enum Color1 {Red = 1, Green, Blue};
var colorName: string = Color1[2];
console.log(colorName);

enum Color2 {Red = 1, Green = 2, Blue = 4};//can assign values to all
var colorIndex = Color2["Blue"];
console.log(colorIndex);



step07b_const_enum


const enum Color {Red, Green, Blue};//starts with 0
var c: Color = Color.Green;

const enum Color1 {Red = 1, Green, Blue};
var colorName: string = Color[2]; //Not allowed with const enums
console.log(colorName);

const enum Color2 {Red = 1, Green = 2, Blue = 4};//can assign values to all
var colorIndex = Color2["Blue"];
console.log(colorIndex);



step08_arrays


let array1 : number[] = [5, 6, 7];//correct syntax
console.log(array1[1]);//correct syntax
let array2:Array = [1, 2, 3];//alternative correct syntax
let array3 : number[] = [];//correct syntax to define an empty array

let array4: number[] = new number[2];//error

let array5: number[] = [];
array5.push(1234);//dynamically adding



step09a_functions


//Note: All parameters are required

//Named function
function add(x: number, y: number): number {
return x+y;
}

//Anonymous function
let myAdd1 = function(x: number, y: number): number {
return x+y;
};


//Anonymous function with explict type
let myAdd2: (x:number, y:number)=>number = function(x: number, y: number): number {
return x+y;
};

//type names dont matter
let myAdd3: (baseValue:number, increment:number)=>number = function(x: number, y: number): number {
return x+y;
};
//Lambda functions
let myAdd4 = (a : number, b : number) => a + b;
//output will be: var myAdd4 = function(a : number, b : number) {return a + b};

type GreetFunction = (a: string) => void;
function greeter(fn: GreetFunction) {
//....
}




step09b_function_optional_parameter


//Named function with optional parameters
function buildName(firstName: string, lastName?: string) : string {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}

let result1 = buildName("Bob"); //ok
let result2 = buildName("Bob", "Adams", "Sr."); //error, too many parameters
var result3 = buildName("Bob", "Adams"); //also ok



//anonymous function type with optional parameters
var buildName1 : (firstName: string, lastName?: string) => string =
function(firstName: string, lastName?: string) : string {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}



step09c_function_default_parameter


//Named function with optional and default parameters
//(Note that the parameter type will be optional when used with default value)
function buildName(firstName: string, lastName = "Khan") : string {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}

let result1 = buildName("Bob"); //works correctly because last parameter is optional
let result2 = buildName("Bob", "Adams", "Sr."); //error, too many parameters
let result3 = buildName("Bob", "Adams"); //correct



//anonymous function type with defult parameters
//(Note that the parameter type will be optional when used with defult value)
let buildName1 : (firstName: string, lastName?: string) => string =
function(firstName: string, lastName = "Khan") : string {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}



step09d_function_rest_parameter


function buildName(firstName: string, ...restOfName: string[]) {//Named function with Rest parameters
return firstName + " " + restOfName.join(" ");
}

var employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");




//anonymous function type with Rest parameters
var buildNameFun: (fname: string, ...rest: string[])=>string =
function (firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}

//Note: Rest, optional and default parameters can only
// be at the end of the parameter list



step09e_async


function myCallBack(text: string) {
console.log("inside myCallback " + text);
}

function callingFunction(initialText: string, callback: (text: string) => void)
{
callback(initialText);
}

callingFunction("myText", myCallBack);
//second file work
function delay(milliseconds: number): Promise {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, milliseconds);
});
}

//Using `then`, `catch`, and `finally`:
delay(1000)
.then(() => {
console.log('The delay is over');
})
.catch((error) => {
console.error('Something went wrong:', error);
})
.finally(() => {
console.log('This is always executed');
});


//Using `async/await`:
try {
await delay(1000);
console.log('Await: The delay is over');
} catch (error) {
console.error('Await: Something went wrong:', error);
} finally {
console.log('Await: This is always executed');
}

//Now Do Coding from the following Article
//https://blog.logrocket.com/async-await-in-typescript/


//Review the tutorial and convert the code in TypeScript
//https://www.codingame.com/playgrounds/347/javascript-promises-mastering-the-asynchronous/what-is-asynchronous-in-javascript





step09f_function_overloads


//overloads give us type-checked calls

//its customary to order overloads from most specific to least specific
function add(arg1: string, arg2: string): string;//option 1
function add(arg1: number, arg2: number): number;//option 2
function add(arg1: boolean, arg2: boolean): boolean;//option 3
//this is not part of the overload list,
//so it has only three overloads
function add(arg1: any, arg2: any): any {
return arg1 + arg2;
}

//Calling 'add' with any other parameter types would cause an error except for the three options
console.log(add(1, 2));
console.log(add("Hello", "World"));
console.log(add(true, false));


step10_tuples


//Tuple types have the advantage that you can accurately describe the type of an array of mixed types

var tuple: [number, string] = [1, "bob"];
var secondElement = tuple[1]; // secondElement now has type 'string'

// Typically an array contains zero to many objects of a
// single type. TypeScript has special analysis around
// arrays which contain multiple types, and where the order
// in which they are indexed is important.

// These are called tuples. Think of them as a way to
// connect some data, but with less syntax than keyed objects.

// You can create a tuple using JavaScript's array syntax:

const failingResponse = ["Not Found", 404];

// but you will need to declare its type as a tuple.

const passingResponse: [string, number] = ["{}", 200];

// If you hover over the two variable names you can see the
// difference between an array ( (string | number)[] ) and
// the tuple ( [string, number] ).

// As an array, the order is not important so an item at
// any index could be either a string or a number. In the
// tuple the order and length are guaranteed.

if (passingResponse[1] === 200) {
const localInfo = JSON.parse(passingResponse[0]);
console.log(localInfo);
}

// This means TypeScript will provide the correct types at
// the right index, and even raise an error if you try to
// access an object at an un-declared index.

passingResponse[2];

// A tuple can feel like a good pattern for short bits of
// connected data or for fixtures.

type StaffAccount = [number, string, string, string?];

const staff: StaffAccount[] = [
[0, "Adankwo", "adankwo.e@"],
[1, "Kanokwan", "kanokwan.s@"],
[2, "Aneurin", "aneurin.s@", "Supervisor"],
];

// When you have a set of known types at the beginning of a
// tuple and then an unknown length, you can use the spread
// operator to indicate that it can have any length and the
// extra indexes will be of a particular type:

type PayStubs = [StaffAccount, ...number[]];

const payStubs: PayStubs[] = [
[staff[0], 250],
[staff[1], 250, 260],
[staff[0], 300, 300, 300],
];

const monthOnePayments = payStubs[0][1] + payStubs[1][1] + payStubs[2][1];
const monthTwoPayments = payStubs[1][2] + payStubs[2][2];
const monthThreePayments = payStubs[2][2];

// You can use tuples to describe functions which take
// an undefined number of parameters with types:

declare function calculatePayForEmployee(id: number, ...args: [...number[]]): number;

calculatePayForEmployee(staff[0][0], payStubs[0][1]);
calculatePayForEmployee(staff[1][0], payStubs[1][1], payStubs[1][2]);

//
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#tuples-in-rest-parameters-and-spread-expressions
// https://auth0.com/blog/typescript-3-exploring-tuples-the-unknown-type/
step11_oop


step12a_class_structural_typing_question

step12b_class_structural_typing

step12c_typing_confusion

step13a_inheritance

step13b_abstract_classes

step13c_constructor

step14_classes_private_modifier

step15_nominal_types

step16_classes_protected_modifier

step17_accessors

step18_static_properties

step19a_interfaces

step19b_interfaces_optional_properties

step19c_interfaces_functional_types

step19d_interfaces_array_types

step20_interfaces_class_types



100 DAYS OF CHALLENGE


Exercise 63



Shape Shifter: Write a program that can describe either a circle or a rectangle using a special type alias, including properties unique to each shape.

*Explain & TIP:* A type alias lets you create a custom type. It's like a shortcut for describing more complex information, such as the details of different shapes.

Exercise 64


Combine Strings and Numbers: Write a function that merges a piece of text with a number. For example, if provided with "Age: " and 30, it should give back "Age: 30".

*Explain & TIP:* In JavaScript, the + operator can add numbers together or join strings. Mixing a string with a number changes the number into a string for the joining.

Exercise 67


Arithmetic with Mixed Types: Write a function that takes two parameters: a number and a string that represents a number (e.g., "5"). Return their sum as a number.

*Explain & TIP:* JavaScript allows arithmetic operations between mixed types. When you add a number to a string that looks like a number, JavaScript converts the string to a


Exercise 68


Multiplying Decimals: Create a function that accepts two decimal numbers and returns their product. Round the result to two decimal places.

*Explain & TIP:* When working with decimals in JavaScript, results can be unexpectedly long. Rounding can help keep numbers manageable.

Exercise 69


Dividing and Finding the Remainder: Write a function that divides two numbers and returns both the quotient and the remainder. Use an object to return both values.

*Explain & TIP:* Division can give you a whole part (quotient) and a leftover part (remainder). Returning both in an object is a neat way to keep them together.


Exercise 70


Understanding let in Loops: Write a function that uses a loop with the let keyword to print numbers from 1 to 5. Explain how the let keyword affects the visibility of the loop variable.

*Explain & TIP:* The let keyword provides block scope in JavaScript, which means variables declared with let inside a loop are only accessible within that loop. This helps avoid unintended interference wit

Exercise 71


Compare let and const: Create two examples where let allows reassignment but const does not. Try to reassign a const-declared variable and catch the error.

*Explain & TIP:* let allows you to declare variables that can be reassigned, while const is for variables that should not change once set. Using const helps make your code safer and more predictable.

Block Scope with let and const: Demonstrate block scope by creating a code block with {} that uses both let and const. Show how variables declared inside the block are not accessible outside of it.

*Explain & TIP:* Block scope, created by {} in JavaScript, confines let and const variables to that block, enhancing code organization and preventing accidental access from outside the block.

Assigning and Updating Variables: Create a function where you declare a variable using let and assign an initial value. Then, update its value within the same function and log both the initial and updated values.

*Explain & TIP:* In JavaScript, you can assign a value to a variable with = and later update it as needed. This is fundamental for keeping track of changing data within your programs.

Swapping Variables: Demonstrate how to swap the values of two variables. Start with variables a = 5 and b = 10, then swap their values so that a becomes 10 and b becomes 5.

*Explain & TIP:* Swapping variables is a common task. You can use a temporary variable to hold one value while you swap them around. It's like juggling where you temporarily place one ball in a basket to free up your hand

Exercise

Compound Assignment Operators: Use compound assignment operators to simplify arithmetic operations. Start with x = 4 and perform a series of operations (addition, subtraction, multiplication, division) on x using compound operators.

*Explain & TIP:* Compound assignment operators combine an arithmetic operation with assignment, making your code cleaner and more concise. Instead of writing x = x + 2, you can simply write x += 2.



MCQS FROM SIR ZIA REPO



MCQ1: What is the type of the variable message in the code let message = "Hello World"?
a) Number
b) String
c) Object
d) Boolean

Answer: b) String

MCQ2: What is the purpose of JSON?
a) To store and transfer data
b) To display data on a webpage
c) To perform calculations
d) To create a database

Answer: a) To store and transfer data

MCQ3: What is the error in the code lett message = "Hello World"?
a) Syntax error
b) Type error
c) Assignability error
d) None

Answer: a) Syntax error

MCQ4: What is the error in the code let message = "Hello World"; console.loger(message)?
a) Syntax error
b) Type error
c) Assignability error
d) None

Answer: b) Type error

MCQ5: What is the error in the code let message = "Hello World"; message = 6?
a) Syntax error
b) Type error
c) Assignability error
d) None

Answer: c) Assignability error
step 01 MCQS
MCQ1: What is the type of variable a in the code let a : string = "Pakistan"?
a) Number
b) String
c) Boolean
d) Object

Answer: b) String

MCQ2: What is the value of variable b in the code let b : number = 9?
a) "USA"
b) 9
c) true
d) "Pakistan"

Answer: b) 9

MCQ3: What is the type of variable e in the code let e = "USA"?
a) Number
b) String
c) Boolean
d) Object

Answer: b) String (Note: This is an example of type inference, where the type is inferred by the assigned value)

MCQ4: What is the value of variable g after the code let g = false; g = true?
a) false
b) true
c) "USA"
d) 10.9

ste 02 MCQS
MCQ1: What is the purpose of using const in JavaScript?
a) To declare variables that can be changed
b) To declare variables that cannot be changed
c) To declare functions
d) To declare classes

Answer: b) To declare variables that cannot be changed

MCQ2: What is the benefit of using let instead of var?
a) Global scope
b) Blocked scope
c) Functional scope
d) None

Answer: b) Blocked scope

MCQ3: What will be the output of the code console.log("let: " + z)?
a) let: 4
b) let: "string"
c) Error: z is not defined in this scope
d) undefined

Answer: c) Error: z is not defined in this scope
MCQDS 4
if (true) {
let z = 4;
//use z
}
else {
let z = "string";
//use z
}
console.log("let: " + z);
*

a) cannot use "z" in the if clause after declartation
b) cannot use "z" in else clause after declartation
c) cannot use "z" in the log statement
d) can use "z" in all the cases

Answer: b) true

Step 03
MCQ1: What is being imported from the module "./first"?
a) b
b) a
c) c
d) d

Answer: b) a

MCQ2: What is the alias of the imported variable "c" from the module "./second"?
a) b
b) d
c) a
d) c

Answer: b) d

MCQ3: What is the purpose of the "inquirer" module in the code?
a) To print colored text
b) To prompt the user for input
c) To calculate the age
d) To export variables

Answer: b) To prompt the user for input

MCQ4: What is the purpose of the "chalk" module in the code?
a) To prompt the user for input
b) To print colored text
c) To calculate the age
d) To export variables

Answer: b) To print colored text

MCQ5: What will be the output of the code console.log(chalk.blue("Insha Allah, in " + (60 - answers.age) + " years you will be 60 years old."))?
a) A blue colored text
b) A red colored text
c) A green colored text
d) A yellow colored text

Answer: a) A blue colored text
MCQ1: What is the type of the variable myname?
a) string
b) null
c) string | null
d) undefined

Answer: c) string | null

MCQ2: What will be the output of the code console.log(myname) after the assignment myname = "zia"?
a) null
b) "zia"
c) undefined
d) 12

Answer: b) "zia"

MCQ3: What is the purpose of narrowing in TypeScript?
a) To widen the type of a variable
b) To narrow the type of a variable
c) To change the type of a variable
d) To assign a value to a variable

Answer: b) To narrow the type of a variable

MCQ4: What is the type of the variable myAge after the assignment myAge = 16?
a) string
b) number
c) string | number
d) undefined

Answer: b) number

MCQ5: What will be the output of the code console.log(myAge.toLowerCase()) after the assignment myAge = "Dont Know"?
a) "dont know"
b) "Dont Know"
c) Error
d) undefined

Answer: a) "dont know"

MCQ6: What is the type of the variable newAge?
a) string
b) number
c) string | number
d) undefined

Answer: c) string | number

MCQ7: What is the purpose of the typeof operator in the code?
a) To check the type of a variable
b) To assign a value to a variable
c) To narrow the type of a variable
d) To widen the type of a variable

Answer: a) To check the type of a variable

MCQ8: What is the type of the variable age?
a) number
b) string
c) "died" | "unknown" | number
d) "living" | number

Answer: c) "died" | "unknown" | number

1. What is the starting index of an enum in TypeScript?
a) 0
b) 1
c) -1
d) None

Answer: a) 0

1. What is the value of colorName in the code enum Color1 {Red = 1, Green, Blue}; var colorName: string = Color1[2];?
a) Red
b) Green
c) Blue
d) None

Answer: c) Blue

1. What is the value of colorIndex in the code enum Color2 {Red = 1, Green = 2, Blue = 4};//can assign values to all var colorIndex = Color2["Blue"];?
a) 1
b) 2
c) 4
d) None

Answer: c) 4

1. What is the purpose of the const enum keyword in TypeScript?
a) To define a constant enum
b) To define a variable enum
c) To define a type alias
d) To define a namespace

Answer: a) To define a constant enum

1. What is the syntax to define an array in TypeScript?
a) let array: number[] = [1, 2, 3];
b) let array: Array = [1, 2, 3];
c) let array = [1, 2, 3];
d) None

Answer: a) let array: number[] = [1, 2, 3];

1. What is the purpose of the push method in an array?
a) To add an element to the end of the array
b) To remove an element from the end of the array
c) To insert an element at a specific index
d) To delete an element at a specific index

Answer: a) To add an element to the end of the array

1. What is the syntax to define a function in TypeScript?
a) function add(x: number, y: number): number { return x+y; }
b) let add = function(x: number, y: number): number { return x+y; };
c) let add: (x:number, y:number)=>number = function(x: number, y: number): number { return x+y; };
d) None

Answer: a) function add(x: number, y: number): number { return x+y; }

1. What is the purpose of the GreetFunction type in the code?
a) To define a function type
b) To define a variable type
c) To define a namespace
d) To define a class

Answer: a) To define a function type

1. What is the purpose of the buildName function in the code?
a) To build a full name from first and last names
b) To build a first name from a full name
c) To build a last name from a full name
d) None

Answer: a) To build a full name from first and last names

1. What is the purpose of the restOfName parameter in the buildName function?
a) To accept a variable number of arguments
b) To accept a single argument
c) To accept an optional argument
d) None

Answer: a) To accept a variable number of arguments

1. What is the purpose of the delay function in the code?
a) To delay the execution of a function
b) To execute a function immediately
c) To cancel the execution of a function
d) None

Answer: a) To delay the execution of a function

1. What is the purpose of the then method in the delay function?
a) To handle the success case of the promise
b) To handle the error case of the promise
c) To handle the finally case of the promise
d) None

Answer: a) To handle the success case of the promise

1. What is the purpose of the catch method in the delay function?
a) To handle the success case of the promise
b) To handle the error case of the promise
c) To handle the finally case of the promise
d) None

Answer: b) To handle the error case of the promise

1. What is the purpose of the finally method in the delay function?
a) To handle the success case of the promise
b) To handle the error case of the promise
c) To handle the finally case of the promise
d) None

Answer: c) To handle the finally case of the promise