Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Basic Javascript Test 1 - 200 Points

Basic js test
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Basic Javascript Test 1 - 200 Points

Basic js test
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Basic Javascript Test 1 - 200 Points

14 sep 2024
Time - 4hr : 00 mins

Part 1: Mixed Level Theory Questions. (30 Questions - 30 points)

1. Explain the differences between var, let, and const. Provide examples to
illustrate variable scope in JavaScript.
2. The filter() method returns the first element that matches the criteria
provided in a function. (T/F)
3. In JavaScript, functions are considered first-class objects. (T/F)
4. Which of the following is NOT a primitive data type in JavaScript?
a. String
b. Number
c. Object
d. boolean
5. Which method does NOT modify the original array?
a. push()
b. pop()
c. map()
d. splice()
6. Which keyword is NOT used for variable declaration in JavaScript?
a. Let
b. Var
c. Dim
d. const
7. Which is NOT a valid looping construct in JavaScript?
a. For
b. Foreach
c. While
d. do...while
8. The ________ operator in JavaScript is used to check both value and type for
equality.
9. The ________ keyword is used to declare a variable that cannot be reassigned.
10.What is the purpose of the throw statement?
11.To convert a string to an integer in JavaScript, you can use the ________
function.
12.The ________ method can be used to find the index of a specific element in an
array.
13.The switch statement can only evaluate expressions that return primitive
values
14.JavaScript is a statically typed language (T/F).
15.In JavaScript, all objects are stored by reference. (T/F)
16.The finally block will always execute after a try block, even if an error is
thrown. (T/F)
17.Which keyword is used to define a JavaScript class?
a. Function
b. Object
c. Class
d. constructor
18.What are template literals in JavaScript, and how do they differ from regular
strings?
19.The reduce() method executes a reducer function for each value of the array
from right to left. (T/F)
20.The delete operator can remove a property from an object. (T/F)
21.JavaScript does not support the concept of classes. (T/F)
22.Which of the following is NOT a method of JavaScript objects?
a. Object.keys()
b. Object.values()
c. Object.map()
d. Object.entries()
23.The ________ keyword is used to refer to the current instance of an object in a
class or function.
24.Which method can be used to merge two or more arrays in JavaScript?
a. concat()
b. merge()
c. combine()
d. join()
25.Explain the concept of "hoisting" in JavaScript with examples for variables
and functions.
26.Describe how the reduce() method works in JavaScript and provide an
example of its use.
27.What is the concept of "destructuring" in JavaScript? Provide examples of
both array and object destructuring.
28.Explain how JavaScript handles "scope" with examples of global scope, local
scope, block scope, and lexical scope.
29.Describe the spread operator (...) and its various use cases in JavaScript.
Provide examples for each.
30.Which of the following does NOT belong to JavaScript String methods?
a. toUpperCase()
b. toLowerCase()
c. round()
d. trim()
31.What will be the result of str.substring(3, 7) if str = "TypeScript"?
32.How does str.substring(3, 7) differ from str.substring(7, 3) for str =
"Functionality"?
33. What will be the output of str.substring(-2, 4) for str = "Python"? Explain why.
34.How do you get the current year from a Date object?
35.How would you compare two dates, date1 as 2024-08-15 and date2 as
2023-08-15, to check which one comes first?
36.

Part 2: Find the Output (20 Questions - 20 points)


1.

2.

3.

4.

5.

6.
7.

8.

9.

10.

11.

12.

13.

14.
15.

16.

17.

18.
19.

20.

Part 3: Short Coding problems (30 Questions - 30 points)

1. Write a program to swap two numbers without using a third variable.


2. Write a function that takes a string and returns it in reverse.
3. Write a program that checks if a number is positive, negative, or zero
4. Write a function that returns the maximum number from an array
5. Write a function to find the factorial of a number.
6. Write a function that takes an array of numbers and returns an array of
squares of even numbers.
7. Write a function to convert a string to a number and handle the conversion
error if the string is not a valid number.
8. Write a function that generates a random integer between two given
numbers.
9. Write a function that counts the number of vowels in a given string.
10. Create an object representing a car with properties make, model, and year.
Write a function to display the car's details.
11.Write a function expression and an arrow function that both return the
square of a number.
12. Write a function that takes an object with properties firstName, lastName,
and age and returns a formatted string.
13. Write a program to print the first n Fibonacci numbers.
14.Write a function that divides two numbers and handles division by zero using
try...catch.
15.Write a function that removes duplicate elements from an array.
16.Write a function that checks if a given string is a palindrome.
17. Write a program that demonstrates the difference between var, let, and
const, On the basis of scoping
18.Write a function to merge two arrays using the spread operator.
19. Write a function that takes an array of numbers and returns the sum of all
numbers using the reduce method.
20.Write a function that capitalizes the first letter of each word in a string.
21. Create an object representing a rectangle with properties width and height,
and a method area() that calculates and returns the area of the rectangle
using this.
22.Write a function that throws an error with a custom message if a number is
not even.
23. Create a class Animal with a method speak() and a subclass Dog that
overrides the speak() method.
24. Add a method double() to the JavaScript Number prototype that doubles the
value of a number.
25.Sort a nested array of numbers.
26.Write a function that takes an array of arrays and returns a flattened array
with each element doubled.
27.Write a function that takes an array of numbers and returns a Set containing
all unique numbers from the array.
28.Write a function that takes two Sets and returns a new Set that contains only
the elements found in both Sets (intersection).
29.Write a forEach loop that prints each element in the array [10, 20, 30].
30.Write a switch statement that prints the day of the week based on a variable
day.
31. explain the error and how would you fix it?
Uncaught ReferenceError: usernme is not defined at script.js:15

Part 4: Coding problems (20 Questions - 20 points)

1. Write a function that converts a string to a number. If the conversion fails,


catch the error and return a message saying "Invalid number format".

console.log(safeConvertToNumber("42")); // Should return 42


console.log(safeConvertToNumber("abc")); // Should return "Invalid number
format"
2. Find the bugs :
function multiplyNumbers(a, b) {
return a * b;
}
let result = multiplyNumbers(4, 5);
console.log(""The result is: "" + rsult);
let numbers = [1, 2, 3, 4];
console.log(""The fifth number is: "" + numbers[4]);"
3. Implement a function comparePrimitiveStrings(str1, str2) that compares two
string objects for equality by comparing their primitive values using valueOf().
4. Write a function getCharFromAscii(ascii) that returns the character
corresponding to a given ASCII value using fromCharCode().
5. Implement a function hasFileExtension(filename, extension) that checks if a
filename ends with a given extension using endsWith().
6. Implement a function swapWords(str, word1, word2) that swaps the first
occurrence of word1 with word2 in a string and vice versa. Use replace() to
achieve this.
7. Suppose you need to format a date as yyyy-mm-dd in JavaScript. How would
you do it, ensuring that both the month and day are always two digits (e.g.,
2024-08-05 instead of 2024-8-5)?
8. How would you handle creating a Date object for a specific date, such as
"2024-02-29", which is valid in a leap year, and how would you check if a
given year is a leap year in JavaScript?
Hint: To determine if a given year is a leap year, you can write a function that
follows the rules:
A year is a leap year if it's divisible by 4.
However, if it's divisible by 100, it’s not a leap year, unless it’s also divisible by
400.
9. How would you add 7 days to the current date and print the resulting date?
10.Given a positive integer, find the next larger number that can be formed by
rearranging its digits. If no such number exists, return -1.
11. Write a function called largestNumberFromDigits that takes a number as an
argument, splits it into its digits, rearranges them to form the largest possible
number, and returns that number.
12. Write a function called isPalindrome that takes a number as an argument
and returns true if the number is the same when its digits are reversed, and
false otherwise.
13.Write a function that takes two arrays and returns a new array containing the
symmetric difference of the two arrays. The symmetric difference is defined
as the elements that are in either of the arrays, but not in their intersection.
Use Set to achieve this.
Input : ['apple', 'banana', 'cherry'], ['cherry', 'date', 'banana']
Output : ['apple', 'date']
14. Write a function that takes an object with nested properties and returns a
string using destructuring.
Input : {
name: 'Alice',
address: {
city: 'Wonderland',
country: 'Fantasy'
}
}
Output : 'Alice lives in Wonderland, Fantasy'
15.Write a function that takes an array and a value, and fills the array with the
value from index 2 to 4.
16. Write a function that takes an array of objects with a score property and
returns the last object where the score is greater than 80.
17. Write a function that takes any number of arguments and returns their sum
using the rest parameter.
18. Write a function that takes any number of arguments and returns the
maximum number using the rest parameter.
19.Write a function that takes an array and creates an object where the keys are
the indices and the values are the elements, using the entries method.
20.Write a function that takes an array of objects with an age property and
returns the array sorted by age in descending order.

Part 5: Coding problems (10 Questions - 100 points)

1. Validate and Process User Input

You're given an array of user input strings representing numbers. Your task is to
write a function that:
. Validates each input to ensure it can be converted to a number.
. Converts each valid string to a number.
. If any input is invalid (i.e., cannot be converted to a number), the function
should throw an error with a descriptive message.
. Returns an array of the valid numbers in sorted order.
. If the array is empty after filtering out invalid inputs, return an error message
saying "No valid numbers found."

Example Inputs and Outputs:

Input: ["10", "20", "abc", "30"]


Output: [10, 20, 30] (after sorting)

Input: ["abc", "xyz"]


Output: Error message "No valid numbers found"

Input: ["50", "10", "invalid", "30"]


Output: [10, 30, 50] (after sorting)
2. Validate Email Addresses: Write a function that takes an array of email
addresses and validates them using a regular expression. Return an array of
valid emails. If no valid emails are found, return an error message saying "No
valid emails found."

Input: ["user@example.com", "invalid-email", "test@domain.co"]

Output: ["user@example.com", "test@domain.co"]

3. Find the Longest Word: Write a function that takes a sentence as input and
returns the longest word in the sentence. If there are multiple words with the
same length, return the first one.

Input: "The quick brown fox jumps over the lazy dog"

Output: "jumps"

4. Validate Phone Numbers: Write a function that takes an array of phone numbers
and checks if they follow a specific format (e.g., (123) 456-7890). Return an array
of valid phone numbers. If no valid phone numbers are found, return an error
message saying "No valid phone numbers found."

Input: ["(123) 456-7890", "123-456-7890", "(987) 654-3210"]

Output: ["(123) 456-7890", "(987) 654-3210"]

5. Find Missing Numbers in a Sequence: Write a function that takes an array of


sorted unique integers and returns an array of missing integers in the sequence.

Input: [1, 2, 4, 6, 7, 9]

Output: [3, 5, 8]

6. Generate an Acronym: Write a function that takes a phrase and returns its
acronym formed by the first letter of each word in uppercase.

Input: "object oriented programming"

Output: "OOP"
7. Flatten a Nested Object: Write a function that takes a nested object and flattens it
into a single-level object with dot notation keys.

Input: { a: 1, b: { c: 2, d: { e: 3 } } }

Output: { "a": 1, "b.c": 2, "b.d.e": 3 }

8. Find the First Non-Repeating Character: Write a function that takes a string as
input and returns the first non-repeating character. If all characters repeat, return
an error message saying "No non-repeating character found."

Input: "swiss"
Output: "w"

9. You need to create a Student Grade Management System using JavaScript that
performs the following tasks:

Student Data Structure: Create two arrays:

studentIds (array): Contains unique identifiers (IDs) for each student.


studentNames (array): Contains the names of each student corresponding to
their IDs.
studentMarks (2D array): Contains the marks of each student in three subjects
(math, science, english). Each sub-array in studentMarks represents a student’s marks.
Marks should be between 0 and 100.
Add a Student: Write a function addStudent(id, name, mathMarks, scienceMarks,
englishMarks) that adds a new student to the studentIds, studentNames, and
studentMarks arrays. Ensure that the id is unique and the marks are within the valid
range (0 to 100). If the id is not unique or the marks are not valid, display an appropriate
error message.

Calculate Average Marks: Write a function calculateAverageMarks(studentId)


that calculates the average marks of a student based on their math, science, and
english marks using their studentId. If the studentId is not found, display an error
message.

Determine Grade: Write a function determineGrade(averageMarks) that takes the


average marks and returns the grade based on the following criteria:

A if average marks are 90 and above.


B if average marks are between 80 and 89.
C if average marks are between 70 and 79.
D if average marks are between 60 and 69.
F if average marks are below 60.
Display All Students and Their Grades: Write a function displayAllStudents() that
iterates over all students and prints their id, name, average marks, and grade to the
console.

Delete a Student: Write a function deleteStudent(studentId) that deletes a


student from the studentIds, studentNames, and studentMarks arrays by their id. If the
studentId is not found, display an error message.

Additional Requirements:

Use const, let, and var where appropriate.


Ensure proper scoping of variables.
Handle edge cases such as invalid input, empty student list, etc.
Use at least one ternary operator, Math functions (e.g., Math.floor for rounding
average marks), logical operators (&&, ||), and unary operators (++, --).

10. Problem: E-Commerce Order Processing System


Write a function processOrder that takes two parameters: orderStatus (a string
representing the current status of an order) and orderDetails (an object containing
details about the order, such as the order ID, customer name, and items). The function
should use a switch statement to handle different order statuses and perform the
appropriate action. If the status is invalid, it should return an error message.

Order Statuses to Handle:


Pending: Display a message "Order [orderID] is pending. Awaiting payment
confirmation.".
Processing: Display a message "Order [orderID] is being processed. Items are being
packed."
Shipped: Display a message "Order [orderID] has been shipped. Expected delivery date
is [date]." Assume the delivery date is 5 days from the current date.
Delivered: Display a message "Order [orderID] has been delivered to [customerName].
Thank you for shopping with us!"
Canceled: Display a message "Order [orderID] has been cancelled. A refund will be
initiated shortly."
Refunded: Display a message "Order [orderID] has been refunded to [customerName]."
Invalid Status: If an order status is not one of the above, return a message "Invalid order
status: [status]. Please check the status and try again."

. All the best .

You might also like