// Ans:03
const personName: string = "Eric";
// lowerCase
console.log(personName.toLowerCase());
// upperCase
console.log(personName.toUpperCase());
// titlecase
let firstLetter: String = personName.charAt(0).toUpperCase();
let restLetters: string = personName.slice(1).toLowerCase();
let titleCase = firstLetter + restLetters;
console.log(titleCase);
// Ans:15
const myfriends = ["Asim", "Faheem", "Azeem"];
console.log(`Due to some personal reasons, Mr.${myfriends[1]} will not come to my dinner `);
// Ans:18
// Define the array of places
let places: string[] = ["Tokyo", "Paris", "Sydney", "New York", "Rome"];
// Print the array in its original order
console.log("Original Order:", places);
// Print the array in alphabetical order without modifying the original list
console.log("Alphabetical Order:", [...places].sort());
// Show that the array is still in its original order
console.log("Original Order:", places);
// Print the array in reverse alphabetical order without changing the original list
console.log("Reverse Alphabetical Order:", [...places].sort().reverse());
// Show that the array is still in its original order
console.log("Original Order:", places);
// Reverse the order of the list
places.reverse();
console.log("Reversed Order:", places);
// Ans:19
interface Person { name: string;}
function countDinnerGuests(people: Person[]): void {
const numGuests = people.length;
console.log(`You are inviting ${numGuests} people to dinner.`);
}
const guests: Person[] = [
{ name: "Asim" },
{ name: "Faheem" },
{ name: "Azeem" }
];
countDinnerGuests(guests);
//Ans:20
// Define an array of mountains
let mountains: string[] = ["Mount Everest", "K2", "Kgchenjunga", "Lhotse", "Makalu"];
// Print the list of mountains
console.log("List of mountains:");
mountains.forEach((mountain, index) => {
console.log(`${index + 1}. ${mountain}`);
});
//Answer:21
// Define types for the items
interface Item {
name: string;
category: string;
quantity: number;
}
// Create objects containing different items
const item1: Item = {
name: "Apples",
category: "Fruit",
quantity: 10
};
const item2: Item = {
name: "Milk",
category: "Dairy",
quantity: 2
};
const item3: Item = {
name: "Bread",
category: "Bakery",
quantity: 1
};
// Print out the objects
console.log("Item 1:", item1);
console.log("Item 2:", item2);
console.log("Item 3:", item3);
// Ans: 22.Intentional Error:
let array: number[] = [1, 2, 3, 4, 5];
let index = 10; // Intentionally setting an index that is out of bounds
try {
let element = array[index]; // Accessing an element with an out-of-bounds index
console.log("Element at index", index, ":", element);
} catch (error) {
console.error("Error:", error.message);
}
// Correcting the error by checking if the index is within bounds
if (index >= 0 && index <array.length) {
let element = array[index];
console.log("Element at index", index, ":", element);
} else {
console.error("Index out of bounds.");
}
// Answ:23
let car: string = 'subaru';
console.log("Is car == 'subaru'? I predict True.");
console.log(car === 'subaru');
console.log("Is car == 'honda'? I predict False.");
console.log(car === 'honda');
console.log("Is car != 'toyota'? I predict True.");
console.log(car !== 'toyota');
console.log("Is car != 'subaru'? I predict False.");
console.log(car !== 'subaru');
console.log("Is car.includes('su')? I predict True.");
console.log(car.includes('su'));
console.log("Is car.includes('ford')? I predict False.");
console.log(car.includes('ford'));
console.log("Is car.length> 5? I predict False.");
console.log(car.length> 5);
console.log("Is car.length< 10? I predict True.");
console.log(car.length< 10);
console.log("Is car.charAt(0) === 's'? I predict True.");
console.log(car.charAt(0) === 's');
console.log("Is car.charAt(2) === 'b'? I predict True.");
console.log(car.charAt(2) === 'b');
// Ans24
// Tests for equality and inequality with strings
let string1: string = "hello";
let string2: string = "world";
console.log(string1 === string2); // false
console.log(string1 !== string2); // true
// Tests using the lower case function
let str1: string = "Hello";
let str2: string = "hello";
console.log(str1.toLowerCase() === str2.toLowerCase()); // true
// Numerical tests involving equality and inequality, greater than and less than, greater than or equal to, and less than or equal to
let num1: number = 5;
let num2: number = 10;
console.log(num1 === num2); // false
console.log(num1 !== num2); // true
console.log(num1 > num2); // false
console.log(num1 < num2); // true
console.log(num1 >= num2); // false
console.log(num1 <= num2); // true
// Tests using "and" and "or" operators
let x: number = 10;
let y: number = 5;
let z: number = 15;
console.log((x > y) && (x < z)); // true
console.log((x > y) || (x > z)); // true
// Answer25
let alien_color: string = 'green';
if (alien_color === 'green') {
console.log("Player just earned 5 points");
}
//Ans28. Stages of Life:
let age: number = 30;
if (age < 2) {
console.log("The person is a baby");
} else if (age >= 2 && age < 4) {
console.log("The person is a toddler");
} else if (age >= 4 && age < 13) {
console.log("The person is a kid");
} else if (age >= 13 && age < 20) {
console.log("The person is a teenager");
} else if (age >= 20 && age < 65) {
console.log("The person is an adult");
} else {
console.log("The person is an elder");
}
//Ans29. Favorite Fruit:
let favorite_fruits: string[] = ["banana", "apple", "orange"];
if (favorite_fruits.includes("banana")) {
console.log("You really like bananas!");
}
if (favorite_fruits.includes("apple")) {
console.log("You really like apples!");
}
if (favorite_fruits.includes("orange")) {
console.log("You really like oranges!");
}
if (favorite_fruits.includes("strawberry")) {
console.log("You really like strawberries!");
}
if (favorite_fruits.includes("kiwi")) {
console.log("You really like kiwis!");
}
//Ans31. No Users:
let usernames: string[] = []; // Empty array
if (usernames.length === 0) {
console.log("We need to find some users!");
} else {
for (let username of usernames) { if (username === "admin") {
console.log("Hello admin, would you like to see a status report?");
} else {console.log(`Hello ${username}, thank you for logging in again.`); } }}
//Ans32. Checking Usernames:
let current_users: string[] = ["john", "alice", "bob", "charlie", "david"];
let new_users: string[] = ["eric", "ALICE", "mike", "david", "sarah"];
for (let new_user of new_users) {
let usernameTaken: boolean = false;
for (let current_user of current_users) {
if (new_user.toLowerCase() === current_user.toLowerCase()) {
usernameTaken = true;
break;
}
}
if (usernameTaken) {
console.log(`Sorry, ${new_user} is already taken. Please enter a new username.`);
} else {
console.log(`${new_user} is available.`);
}
}
//Ans33. Ordinal Numbers
let numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (let number of numbers) {
let ordinal: string;
if (number === 1) {
ordinal = "st";
} else if (number === 2) {
ordinal = "nd";
} else if (number === 3) {
ordinal = "rd";
} else {
ordinal = "th";
}
console.log(`${number}${ordinal}`);
}
//Ans34. Pizzas:
let favorite_pizzas: string[] = ["pepperoni", "margherita", "vegetarian"];
for (let pizza of favorite_pizzas) {
console.log(`I like ${pizza} pizza.`);
}
console.log("I really love pizza!");
//Ans35. Animals:
let animals: string[] = ["dog", "cat", "rabbit"];
for (let animal of animals) {
console.log(`A ${animal} would make a great pet.`);
}
console.log("Any of these animals would make a great pet!");
//Ans 36. T-Shirt:
function make_shirt(size: string, message: string): void {
console.log(`Shirt size: ${size}, Message: ${message}`);
}
// Call the function
make_shirt("medium", "Hello, World!");
//Ans38 Cities:
function describe_city(city: string, country: string = "Unknown"): void {
console.log(`${city} is in ${country}.`);
}
// Call the function for three different cities
describe_city("Karachi", "Pakistan");
describe_city("Tokyo", "Japan");
describe_city("New York");
// Ans39. City Names
function city_country(city: string, country: string): string {
return `${city}, ${country}`;
}
// Call the function with three city-country pairs and print the returned values
console.log(city_country("Lahore", "Pakistan"));
console.log(city_country("Paris", "France"));
console.log(city_country("New York", "USA"));
//Ans40. Album
function make_album(artist: string, title: string, tracks?: number): Record<string, any> {
let album: Record<string, any> = {
"artist": artist,
"title": title
};
if (tracks !== undefined) {
album["tracks"] = tracks;
}
return album;
}
// Call the function to make three dictionaries representing different albums
let album1 = make_album("Artist1", "Album1");
let album2 = make_album("Artist2", "Album2", 12); // including the number of tracks
let album3 = make_album("Artist3", "Album3");
// Print each return value to show that objects are storing the album information correctly
console.log(album1);
console.log(album2);
console.log(album3);
//Ans44.Sandwiches:
function makeSandwich(...ingredients: string[]): void {
console.log("Making a sandwich with:");
ingredients.forEach((ingredient) => {
console.log("- " + ingredient);
});
console.log("Enjoy your sandwich!\n");
}
// Call the function with different numbers of arguments
makeSandwich("ham", "cheese", "lettuce");
makeSandwich("turkey", "avocado");
makeSandwich("peanut butter", "jelly");
//Ans45.Cars:
interface Car {
manufacturer: string;
model: string;
[key: string]: any; // Allow arbitrary key-value pairs
}
function createCar(manufacturer: string, model: string, ...options: [string, any][]): Car {
const car: Car = { manufacturer, model };
// Adding additional options
options.forEach(([key, value]) => {
car[key] = value;
});
return car;
}
const myCar: Car = createCar("Toyota", "Corolla", ["color", "blue"], ["year", 2022]);
console.log(myCar);
To embed this project on your website, copy the following code and paste it into your website's HTML: