Elevate your JavaScript proficiency with our curated collection of challenging questions designed to push your coding boundaries. Whether you’re a seasoned developer or just starting on your coding journey, these JavaScript challenge questions will sharpen your problem-solving skills and deepen your understanding of this versatile programming language. Get ready to embark on a journey of coding excellence and conquer these thought-provoking challenges!

Table of Contents
Top 30 javascript commonly asked questions along with brief responses:
1. What is JavaScript?
– JavaScript is a high-level, interpreted programming language used for web development.
2. Explain the difference between `null` and `undefined`.
– `null` is an assigned value representing the absence of any object value, while `undefined` is a variable that has been declared but not assigned any value.
3. What is the DOM?
– The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects.
4. What is closure in JavaScript?
– A closure is a function that has access to variables from its outer (enclosing) scope, even after the outer function has finished executing.
5. Explain the concept of hoisting.
– Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase.
6. What is the difference between `let`, `const`, and `var`?
– `let` and `const` are block-scoped, while `var` is function-scoped. `const` cannot be reassigned, and `let` allows reassignment.
7. What is event delegation?
– Event delegation is a technique where a single event listener is attached to a common ancestor, rather than individual elements. It is useful for handling events on multiple child elements.
8. What is the purpose of the `this` keyword in JavaScript?
– `this` refers to the object to which the current code context (function) belongs.
9. Explain the concept of prototypal inheritance.
– In JavaScript, objects can inherit properties and methods from other objects through their prototype chain.
10. What is the difference between synchronous and asynchronous programming?
– Synchronous programming executes code sequentially, while asynchronous programming allows tasks to be performed concurrently.
11. How does AJAX work?
– AJAX (Asynchronous JavaScript and XML) enables web pages to update content asynchronously by exchanging data with a web server behind the scenes.
12. What is the purpose of the `bind` method?
– The `bind` method is used to create a new function with a specified `this` value and initial arguments provided.
13. What is the event loop in JavaScript?
– The event loop is a mechanism that handles the execution of code, callbacks, and events in a non-blocking way.
14. Explain the difference between `==` and `===`.
– `==` performs type coercion, while `===` checks both value and type without coercion.
15. What is the purpose of the `map` function in JavaScript?
– The `map` function is used to apply a provided function to all elements in an array, creating a new array with the results.
16. What is a closure? Provide an example.
– A closure is a function that encapsulates variables from its lexical scope. Example:
“`javascript
function outer() {
let x = 10;
function inner() {
console.log(x);
}
return inner;
}
let closureExample = outer();
closureExample(); // Outputs 10
“`
17. What is the difference between `let` and `const`?
– `let` allows reassignment, while `const` does not.
18. What is the purpose of the `async` and `await` keywords?
– `async` is used to declare an asynchronous function, and `await` is used to wait for a promise to resolve before continuing the code execution.
19. Explain the concept of the Same-Origin Policy.
– The Same-Origin Policy is a security measure that restricts web pages from making requests to a different domain than the one that served the web page.
20. What is a callback function?
– A callback function is a function passed as an argument to another function and is executed after the completion of a specific task.
21. Explain the purpose of the `JSON.stringify` method.
– `JSON.stringify` converts a JavaScript object or value into a JSON string.
22. What is the purpose of the `localStorage` and `sessionStorage` objects?
– `localStorage` and `sessionStorage` provide a way to store key-value pairs in a web browser with varying levels of persistence.
23. What is the difference between `splice` and `slice`?
– `splice` is used to modify an array by adding or removing elements, while `slice` creates a new array by extracting a portion of an existing array.
24. Explain the concept of debouncing.
– Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, throttling the execution of a function.
25. What is a promise in JavaScript?
– A promise is an object representing the eventual completion or failure of an asynchronous operation.
26. What is the purpose of the `use strict` directive?
– `’use strict’;` enables a strict mode in JavaScript, catching common coding mistakes and preventing the use of certain error-prone features.
27. How does the `for…of` loop differ from the `for…in` loop?
– `for…of` is used to iterate over the values of an iterable object, while `for…in` is used to iterate over the enumerable properties of an object.
28. Explain the concept of currying.
– Currying is the technique of converting a function with multiple arguments into a sequence of functions that each take a single argument.
29. What is the purpose of the `Object.keys()` method?
– `Object.keys()` returns an array of a given object’s own enumerable property names.
30. Explain the concept of the Single Responsibility Principle.
– The Single Responsibility Principle is a design principle that suggests a class or module should have only one reason to change, meaning it should have only one responsibility or job.
Video Playlist Javascript Tutorials:
Javascript Fundamentals: 16 questions and answers:
// Question 1: Check if two values are equal using strict equality
// Description: Write a function that checks if two values are equal using strict equality.
function isEqual(a, b) {
const result = a === b;
console.log(`Are ${a} and ${b} equal? ${result}`);
return result;
}
// Test cases for isEqual
isEqual(5, 5); // Output: true (5 is equal to 5)
isEqual(5, “5”); // Output: false (5 is not equal to “5” due to different types)
// ****************************************************
// Question 2: Get the type of a value
// Description: Write a function that returns the type of a given value.
function getType(value) {
const result = typeof value;
console.log(`The type of ${value} is ${result}`);
return result;
}
// Test cases for getType
getType(“Hello”); // Output: string (the type of “Hello” is string)
getType(42); // Output: number (the type of 42 is number)
// ****************************************************
// Question 3: Get the nth character of a string
// Description: Write a function that returns the nth character of a given string.
function getNthCharacter(str, n) {
const result = str.charAt(n);
console.log(`The ${n}th character of “${str}” is “${result}”`);
return result;
}
// Test cases for getNthCharacter
getNthCharacter(“Hello”, 2); // Output: l (the 2nd character of “Hello” is “l”)
getNthCharacter(“JavaScript”, 5); // Output: S (the 5th character of “JavaScript” is “S”)
// ****************************************************
// Question 4: Remove first n characters of a string
// Description: Write a function that removes the first n characters from a given string.
function removeFirstNChars(str, n) {
const result = str.slice(n);
console.log(`After removing first ${n} characters from “${str}”: “${result}”`);
return result;
}
// Test cases for removeFirstNChars
removeFirstNChars(“Programming”, 4); // Output: ramming (remove first 4 characters from “Programming”)
removeFirstNChars(“OpenAI”, 2); // Output: enAI
// ****************************************************
// Question 5: Get last n characters of a string
// Description: Write a function that returns the last n characters of a given string.
function getLastNChars(str, n) {
const result = str.slice(-n);
console.log(`Last ${n} characters of “${str}”: “${result}”`);
return result;
}
// Test cases for getLastNChars
getLastNChars(“Hello World”, 5); // Output: World (last 5 characters of “Hello World”)
getLastNChars(“JavaScript”, 3); // Output: ipt
// ****************************************************
// Question 6: Get first n characters of a string
// Description: Write a function that returns the first n characters of a given string.
function getFirstNChars(str, n) {
const result = str.slice(0, n);
console.log(`First ${n} characters of “${str}”: “${result}”`);
return result;
}
// Test cases for getFirstNChars
getFirstNChars(“OpenAI”, 4); // Output: Open (first 4 characters of “OpenAI”)
getFirstNChars(“GPT-3”, 2); // Output: GP
// ****************************************************
// Question 7: Find the position of one string in another
// Description: Write a function that finds the position of one string in another.
function findStringPosition(mainStr, subStr) {
const result = mainStr.indexOf(subStr);
console.log(`Position of “${subStr}” in “${mainStr}”: ${result}`);
return result;
}
// Test cases for findStringPosition
findStringPosition(“Hello World”, “World”); // Output: 6 (“World” starts at index 6 in “Hello World”)
findStringPosition(“JavaScript”, “Node”); // Output: -1 (“Node” is not found in “JavaScript”)
// ****************************************************
// Question 8: Extract first half of a string
// Description: Write a function that extracts the first half of a given string.
function extractFirstHalf(str) {
const halfIndex = Math.ceil(str.length / 2);
const result = str.slice(0, halfIndex);
console.log(`First half of “${str}”: “${result}”`);
return result;
}
// Test cases for extractFirstHalf
extractFirstHalf(“JavaScript”); // Output: Java (extract the first half of “JavaScript”)
extractFirstHalf(“OpenAI”); // Output: Open (extract the first half of “OpenAI”)
// ****************************************************
// Question 9: Remove last n characters of a string
// Description: Write a function that removes the last n characters from a given string.
function removeLastNChars(str, n) {
const result = str.slice(0, -n);
console.log(`After removing last ${n} characters from “${str}”: “${result}”`);
return result;
}
// Test cases for removeLastNChars
removeLastNChars(“Programming”, 4); // Output: Program (remove last 4 characters from “Programming”)
removeLastNChars(“GPT-3”, 2); // Output: GP
// ****************************************************
// Question 10: Return the percentage of a number
// Description: Write a function that calculates the percentage of a number.
function calculatePercentage(number, percentage) {
const result = (number * percentage) / 100;
console.log(`${percentage}% of ${number} is ${result}`);
return result;
}
// Test cases for calculatePercentage
calculatePercentage(80, 25); // Output: 20 (25% of 80 is 20)
calculatePercentage(50, 10); // Output: 5 (10% of 50 is 5)
// ****************************************************
// Question 11: Basic JavaScript math operators
// Description: Write a function that performs basic math operations (sum, difference, product, quotient).
function basicMathOperations(a, b) {
const sum = a + b;
const difference = a – b;
const product = a * b;
const quotient = a / b;
console.log(`Sum: ${sum}, Difference: ${difference}, Product: ${product}, Quotient: ${quotient}`);
return { sum, difference, product, quotient };
}
// Test cases for basicMathOperations
basicMathOperations(10, 5); // Output: { sum: 15, difference: 5, product: 50, quotient: 2 }
basicMathOperations(8, 2); // Output: { sum: 10, difference: 6, product: 16, quotient: 4 }
// ****************************************************
// Question 12: Check whether a string contains another string and concatenate
// Description: Write a function that checks if a string contains another string and concatenates them.
function containsAndConcat(str1, str2) {
const contains = str1.includes(str2);
const concatenated = str1 + str2;
console.log(`”${str1}” contains “${str2}”: ${contains}`);
console.log(`Concatenated string: “${concatenated}”`);
return { contains, concatenated };
}
// Test cases for containsAndConcat
containsAndConcat(“Hello”, “lo”); // Output: { contains: true, concatenated: “Hellolo” }
containsAndConcat(“JavaScript”, “Node”); // Output: { contains: false, concatenated: “JavaScriptNode” }
// ****************************************************
// Question 13: Check if a number is even
// Description: Write a function that checks if a given number is even.
function isEven(number) {
const result = number % 2 === 0;
console.log(`${number} is even? ${result}`);
return result;
}
// Test cases for isEven
isEven(7); // Output: false (7 is not even)
isEven(12); // Output: true (12 is even)
// ****************************************************
// Question 14: How many times does a character occur?
// Description: Write a function that counts the occurrences of a character in a string.
function countCharacterOccurrences(str, char) {
const result = str.split(char).length – 1;
console.log(`”${char}” occurs ${result} times in “${str}”`);
return result;
}
// Test cases for countCharacterOccurrences
countCharacterOccurrences(“programming”, “m”); // Output: 2 (“m” occurs twice in “programming”)
countCharacterOccurrences(“OpenAI”, “A”); // Output: 1 (“A” occurs once in “OpenAI”)
// ****************************************************
// Question 15: Check if a number is a whole number
// Description: Write a function that checks if a given number is a whole number.
function isWholeNumber(number) {
const result = Number.isInteger(number);
console.log(`${number} is a whole number? ${result}`);
return result;
}
// Test cases for isWholeNumber
isWholeNumber(7.5); // Output: false (7.5 is not a whole number)
isWholeNumber(10); // Output: true (10 is a whole number)
// ****************************************************
// Question 16: Multiplication, division, and comparison operators
// Description: Write a function that performs multiplication, division, and a comparison operation.
function complexOperations(a, b, c) {
const multiplication = a * b;
const division = a / b;
const comparison = a > c;
console.log(`Multiplication: ${multiplication}, Division: ${division}, Comparison: ${comparison}`);
return { multiplication, division, comparison };
}
// Test cases for complexOperations
complexOperations(10, 5, 8); // Output: { multiplication: 50, division: 2, comparison: true }
complexOperations(7, 3, 5); // Output: { multiplication: 21, division: 2.333, comparison: true }
// ****************************************************
Javascript array: 16 questions and answers:
// Question 1: Remove first n elements of an array
// Description: Write a function that removes the first n elements from a JavaScript array.
function removeFirstNElements(arr, n) {
const result = arr.slice(n);
console.log(`After removing first ${n} elements from [${arr}]: [${result}]`);
return result;
}
// Test cases for removeFirstNElements
removeFirstNElements([1, 2, 3, 4, 5], 2); // Output: [3, 4, 5] (remove first 2 elements)
removeFirstNElements([‘a’, ‘b’, ‘c’, ‘d’], 3); // Output: [‘d’] (remove first 3 elements)
// ****************************************************
// Question 2: Get last n elements of an array
// Description: Write a function that returns the last n elements from a JavaScript array.
function getLastNElements(arr, n) {
const result = arr.slice(-n);
console.log(`Last ${n} elements of [${arr}]: [${result}]`);
return result;
}
// Test cases for getLastNElements
getLastNElements([1, 2, 3, 4, 5], 3); // Output: [3, 4, 5] (last 3 elements)
getLastNElements([‘a’, ‘b’, ‘c’, ‘d’], 2); // Output: [‘c’, ‘d’] (last 2 elements)
// ****************************************************
// Question 3: Get first n elements of an array
// Description: Write a function that returns the first n elements from a JavaScript array.
function getFirstNElements(arr, n) {
const result = arr.slice(0, n);
console.log(`First ${n} elements of [${arr}]: [${result}]`);
return result;
}
// Test cases for getFirstNElements
getFirstNElements([1, 2, 3, 4, 5], 2); // Output: [1, 2] (first 2 elements)
getFirstNElements([‘a’, ‘b’, ‘c’, ‘d’], 3); // Output: [‘a’, ‘b’, ‘c’] (first 3 elements)
// ****************************************************
// Question 4: Return last n array elements
// Description: Write a function that returns the last n elements from a JavaScript array.
function returnLastNArrayElements(arr, n) {
const result = arr.slice(-n);
console.log(`Last ${n} elements of [${arr}]: [${result}]`);
return result;
}
// Test cases for returnLastNArrayElements
returnLastNArrayElements([1, 2, 3, 4, 5], 3); // Output: [3, 4, 5] (last 3 elements)
returnLastNArrayElements([‘a’, ‘b’, ‘c’, ‘d’], 2); // Output: [‘c’, ‘d’] (last 2 elements)
// ****************************************************
// Question 5: Remove a specific array element
// Description: Write a function that removes a specific element from a JavaScript array.
function removeArrayElement(arr, element) {
const index = arr.indexOf(element);
if (index !== -1) {
arr.splice(index, 1);
}
console.log(`After removing “${element}” from [${arr}]: [${arr}]`);
return arr;
}
// Test cases for removeArrayElement
removeArrayElement([1, 2, 3, 4, 5], 3); // Output: [1, 2, 4, 5] (remove element 3)
removeArrayElement([‘a’, ‘b’, ‘c’, ‘d’], ‘b’); // Output: [‘a’, ‘c’, ‘d’] (remove element ‘b’)
// ****************************************************
// Question 6: Count number of elements in JavaScript array
// Description: Write a function that counts the number of elements in a JavaScript array.
function countArrayElements(arr) {
const result = arr.length;
console.log(`Number of elements in [${arr}]: ${result}`);
return result;
}
// Test cases for countArrayElements
countArrayElements([1, 2, 3, 4, 5]); // Output: 5 (5 elements in the array)
countArrayElements([‘a’, ‘b’, ‘c’, ‘d’]); // Output: 4 (4 elements in the array)
// ****************************************************
// Question 7: Count number of negative values in array
// Description: Write a function that counts the number of negative values in a JavaScript array.
function countNegativeValues(arr) {
const result = arr.filter(item => item < 0).length;
console.log(`Number of negative values in [${arr}]: ${result}`);
return result;
}
// Test cases for countNegativeValues
countNegativeValues([-1, 2, -3, 4, -5]); // Output: 3 (3 negative values in the array)
countNegativeValues([1, -2, 3, -4, 5]); // Output: 2 (2 negative values in the array)
// ****************************************************
// Question 8: Sort an array of strings alphabetically
// Description: Write a function that sorts an array of strings alphabetically.
function sortAlphabetically(arr) {
const result = arr.slice().sort();
console.log(`Sorted alphabetically: [${result}]`);
return result;
}
// Test cases for sortAlphabetically
sortAlphabetically([‘banana’, ‘apple’, ‘orange’, ‘grape’]); // Output: [‘apple’, ‘banana’, ‘grape’, ‘orange’]
sortAlphabetically([‘cat’, ‘dog’, ‘elephant’, ‘ant’]); // Output: [‘ant’, ‘cat’, ‘dog’, ‘elephant’]
// ****************************************************
// Question 9: Sort an array of numbers in descending order
// Description: Write a function that sorts an array of numbers in descending order.
function sortDescending(arr) {
const result = arr.slice().sort((a, b) => b – a);
console.log(`Sorted in descending order: [${result}]`);
return result;
}
// Test cases for sortDescending
sortDescending([5, 2, 8, 1, 3]); // Output: [8, 5, 3, 2, 1] (sorted in descending order)
sortDescending([10, 3, 7, 1, 9]); // Output: [10, 9, 7, 3, 1] (sorted in descending order)
// ****************************************************
// Question 10: Calculate the sum of an array of numbers
// Description: Write a function that calculates the sum of an array of numbers.
function calculateSum(arr) {
const result = arr.reduce((sum, num) => sum + num, 0);
console.log(`Sum of [${arr}]: ${result}`);
return result;
}
// Test cases for calculateSum
calculateSum([1, 2, 3, 4, 5]); // Output: 15 (sum of the array)
calculateSum([10, 5, 8, 2, 7]); // Output: 32 (sum of the array)
// ****************************************************
// Question 11: Return the average of an array of numbers
// Description: Write a function that returns the average of an array of numbers.
function calculateAverage(arr) {
const sum = calculateSum(arr);
const result = sum / arr.length;
console.log(`Average of [${arr}]: ${result}`);
return result;
}
// Test cases for calculateAverage
calculateAverage([1, 2, 3, 4, 5]); // Output: 3 (average of the array)
calculateAverage([10, 5, 8, 2, 7]); // Output: 6.4 (average of the array)
// ****************************************************
// Question 12: Return the longest string from an array of strings
// Description: Write a function that returns the longest string from an array of strings.
function getLongestString(arr) {
const result = arr.reduce((longest, current) => (current.length > longest.length ? current : longest), ”);
console.log(`Longest string from [${arr}]: “${result}”`);
return result;
}
// Test cases for getLongestString
getLongestString([‘apple’, ‘banana’, ‘orange’, ‘grape’]); // Output: ‘banana’ (longest string)
getLongestString([‘cat’, ‘dog’, ‘elephant’, ‘ant’]); // Output: ‘elephant’ (longest string)
// ****************************************************
// Question 13: Check if all array elements are equal
// Description: Write a function that checks if all elements in a JavaScript array are equal.
function areArrayElementsEqual(arr) {
const result = arr.every(item => item === arr[0]);
console.log(`Are all elements in [${arr}] equal? ${result}`);
return result;
}
// Test cases for areArrayElementsEqual
areArrayElementsEqual([1, 1, 1, 1, 1]); // Output: true (all elements are equal)
areArrayElementsEqual([‘a’, ‘a’, ‘a’, ‘a’]); // Output: true (all elements are equal)
// ****************************************************
// Question 14: Merge an arbitrary number of arrays
// Description: Write a function that merges an arbitrary number of arrays.
function mergeArrays(…arrays) {
const result = [].concat(…arrays);
console.log(`Merged arrays: [${result}]`);
return result;
}
// Test cases for mergeArrays
mergeArrays([1, 2], [‘a’, ‘b’], [true, false]); // Output: [1, 2, ‘a’, ‘b’, true, false] (merged arrays)
mergeArrays([10, 20], [‘apple’, ‘orange’], [true, false, ‘banana’]); // Output: [10, 20, ‘apple’, ‘orange’, true, false, ‘banana’] (merged arrays)
// ****************************************************
// Question 15: Sort array by object property
// Description: Write a function that sorts an array of objects by a specific property.
function sortByObjectProperty(arr, property) {
const result = arr.slice().sort((a, b) => a[property].localeCompare(b[property]));
console.log(`Sorted by ${property}: [${result.map(obj => obj[property])}]`);
return result;
}
// Test cases for sortByObjectProperty
sortByObjectProperty([{ name: ‘John’, age: 30 }, { name: ‘Alice’, age: 25 }, { name: ‘Bob’, age: 35 }], ‘name’);
// Output: [{ name: ‘Alice’, age: 25 }, { name: ‘Bob’, age: 35 }, { name: ‘John’, age: 30 }] (sorted by ‘name’)
sortByObjectProperty([{ name: ‘John’, age: 30 }, { name: ‘Alice’, age: 25 }, { name: ‘Bob’, age: 35 }], ‘age’);
// Output: [{ name: ‘Alice’, age: 25 }, { name: ‘John’, age: 30 }, { name: ‘Bob’, age: 35 }] (sorted by ‘age’)
// ****************************************************
// Question 16: Merge two arrays with duplicate values
// Description: Write a function that merges two arrays and removes duplicate values.
function mergeArraysNoDuplicates(arr1, arr2) {
const result = Array.from(new Set([…arr1, …arr2]));
console.log(`Merged arrays without duplicates: [${result}]`);
return result;
}
// Test cases for mergeArraysNoDuplicates
mergeArraysNoDuplicates([1, 2, 3], [3, 4, 5]); // Output: [1, 2, 3, 4, 5] (merged arrays without duplicates)
mergeArraysNoDuplicates([‘apple’, ‘orange’], [‘orange’, ‘banana’, ‘grape’]);
// Output: [‘apple’, ‘orange’, ‘banana’, ‘grape’] (merged arrays without duplicates)
// ****************************************************
Javascript objects: 16 questions and answers:
// Question 1: Accessing object properties two
// Description: Write a function that accesses a specific property of a JavaScript object.
function accessObjectPropertyTwo(obj, property) {
const result = obj[property];
console.log(`Value of ${property} in the object: ${result}`);
return result;
}
// Test cases for accessObjectPropertyTwo
const person = { name: ‘John’, age: 30, city: ‘New York’ };
accessObjectPropertyTwo(person, ‘age’); // Output: 30 (value of ‘age’ in the object)
accessObjectPropertyTwo(person, ‘city’); // Output: ‘New York’ (value of ‘city’ in the object)
// ****************************************************
// Question 2: Accessing object properties three
// Description: Write a function that accesses a specific property of a JavaScript object.
function accessObjectPropertyThree(obj, property) {
const result = obj[property];
console.log(`Value of ${property} in the object: ${result}`);
return result;
}
// Test cases for accessObjectPropertyThree
const car = { make: ‘Toyota’, model: ‘Camry’, year: 2022 };
accessObjectPropertyThree(car, ‘model’); // Output: ‘Camry’ (value of ‘model’ in the object)
accessObjectPropertyThree(car, ‘year’); // Output: 2022 (value of ‘year’ in the object)
// ****************************************************
// Question 3: Check if property exists in object
// Description: Write a function that checks if a property exists in a JavaScript object.
function isPropertyExist(obj, property) {
const result = property in obj;
console.log(`Does the object have the property ${property}? ${result}`);
return result;
}
// Test cases for isPropertyExist
const computer = { brand: ‘Dell’, model: ‘Inspiron’, price: 800 };
isPropertyExist(computer, ‘model’); // Output: true (the object has the property ‘model’)
isPropertyExist(computer, ‘color’); // Output: false (the object does not have the property ‘color’)
// ****************************************************
// Question 4: Check if property exists in object and is truthy
// Description: Write a function that checks if a property exists in a JavaScript object and has a truthy value.
function isTruthyProperty(obj, property) {
const result = obj.hasOwnProperty(property) && obj[property];
console.log(`Is the property ${property} truthy in the object? ${result}`);
return result;
}
// Test cases for isTruthyProperty
const laptop = { brand: ‘HP’, RAM: 8, storage: ‘256GB SSD’ };
isTruthyProperty(laptop, ‘brand’); // Output: true (the property ‘brand’ is truthy)
isTruthyProperty(laptop, ‘graphics’); // Output: false (the property ‘graphics’ does not exist)
// ****************************************************
// Question 5: Creating Javascript objects one
// Description: Write a function that creates a JavaScript object with specified properties and values.
function createObjectOne(name, age, city) {
const result = { name, age, city };
console.log(‘Created object:’, result);
return result;
}
// Test cases for createObjectOne
createObjectOne(‘Alice’, 25, ‘London’); // Output: { name: ‘Alice’, age: 25, city: ‘London’ }
createObjectOne(‘Bob’, 30, ‘New York’); // Output: { name: ‘Bob’, age: 30, city: ‘New York’ }
// ****************************************************
// Question 6: Creating Javascript objects two
// Description: Write a function that creates a JavaScript object with specified properties and values.
function createObjectTwo(make, model, year) {
const result = { make, model, year };
console.log(‘Created object:’, result);
return result;
}
// Test cases for createObjectTwo
createObjectTwo(‘Honda’, ‘Civic’, 2021); // Output: { make: ‘Honda’, model: ‘Civic’, year: 2021 }
createObjectTwo(‘Ford’, ‘Escape’, 2022); // Output: { make: ‘Ford’, model: ‘Escape’, year: 2022 }
// ****************************************************
// Question 7: Creating Javascript objects three
// Description: Write a function that creates a JavaScript object with specified properties and values.
function createObjectThree(firstName, lastName, age) {
const result = { firstName, lastName, age };
console.log(‘Created object:’, result);
return result;
}
// Test cases for createObjectThree
createObjectThree(‘John’, ‘Doe’, 35); // Output: { firstName: ‘John’, lastName: ‘Doe’, age: 35 }
createObjectThree(‘Jane’, ‘Smith’, 28); // Output: { firstName: ‘Jane’, lastName: ‘Smith’, age: 28 }
// ****************************************************
// Question 8: Extract keys from Javascript object
// Description: Write a function that extracts keys from a JavaScript object.
function extractObjectKeys(obj) {
const result = Object.keys(obj);
console.log(`Keys of the object: [${result}]`);
return result;
}
// Test cases for extractObjectKeys
const phone = { brand: ‘Samsung’, model: ‘Galaxy’, color: ‘Black’ };
extractObjectKeys(phone); // Output: [‘brand’, ‘model’, ‘color’] (keys of the object)
// ****************************************************
// Question 9: Return nested object property
// Description: Write a function that returns a nested property from a JavaScript object.
function getNestedObjectProperty(obj, propertyPath) {
const result = propertyPath.split(‘.’).reduce((acc, key) => (acc ? acc[key] : undefined), obj);
console.log(`Value of nested property ${propertyPath}: ${result}`);
return result;
}
// Test cases for getNestedObjectProperty
const employee = { details: { name: ‘Alice’, department: { title: ‘Engineering’ } } };
getNestedObjectProperty(employee, ‘details.name’); // Output: ‘Alice’ (value of nested property ‘details.name’)
getNestedObjectProperty(employee, ‘details.department.title’); // Output: ‘Engineering’ (value of nested property ‘details.department.title’)
// ****************************************************
// Question 10: Sum object values
// Description: Write a function that calculates the sum of values in a JavaScript object.
function sumObjectValues(obj) {
const result = Object.values(obj).reduce((sum, value) => sum + value, 0);
console.log(`Sum of object values: ${result}`);
return result;
}
// Test cases for sumObjectValues
const expenses = { rent: 1200, groceries: 200, utilities: 150 };
sumObjectValues(expenses); // Output: 1550 (sum of object values)
// ****************************************************
// Question 11: Remove a property from an object
// Description: Write a function that removes a property from a JavaScript object.
function removeObjectProperty(obj, property) {
delete obj[property];
console.log(`Object after removing property ${property}:`, obj);
return obj;
}
// Test cases for removeObjectProperty
const student = { name: ‘Bob’, age: 25, grade: ‘A’ };
removeObjectProperty(student, ‘grade’); // Output: { name: ‘Bob’, age: 25 } (object after removing ‘grade’ property)
// ****************************************************
// Question 12: Merge two objects with matching keys
// Description: Write a function that merges two JavaScript objects by matching keys.
function mergeObjectsWithMatchingKeys(obj1, obj2) {
const result = { …obj1, …obj2 };
console.log(‘Merged object with matching keys:’, result);
return result;
}
// Test cases for mergeObjectsWithMatchingKeys
const personInfo = { name: ‘Alice’, age: 30 };
const addressInfo = { city: ‘New York’, zipCode: ‘10001’ };
mergeObjectsWithMatchingKeys(personInfo, addressInfo);
// Output: { name: ‘Alice’, age: 30, city: ‘New York’, zipCode: ‘10001’ } (merged object with matching keys)
// ****************************************************
// Question 13: Multiply all object values by x
// Description: Write a function that multiplies all values in a JavaScript object by a given factor.
function multiplyObjectValues(obj, factor) {
const result = {};
for (const key in obj) {
result[key] = obj[key] * factor;
}
console.log(`Object after multiplying values by ${factor}:`, result);
return result;
}
// Test cases for multiplyObjectValues
const quantities = { apples: 5, oranges: 3, bananas: 2 };
multiplyObjectValues(quantities, 2); // Output: { apples: 10, oranges: 6, bananas: 4 } (object after multiplying values)
// ****************************************************
// Question 14: Swap object keys and values
// Description: Write a function that swaps keys and values in a JavaScript object.
function swapObjectKeysAndValues(obj) {
const result = {};
for (const key in obj) {
result[obj[key]] = key;
}
console.log(‘Object after swapping keys and values:’, result);
return result;
}
// Test cases for swapObjectKeysAndValues
const colors = { red: ‘apple’, yellow: ‘banana’, orange: ‘orange’ };
swapObjectKeysAndValues(colors); // Output: { apple: ‘red’, banana: ‘yellow’, orange: ‘orange’ } (object after swapping keys and values)
// ****************************************************
// Question 15: Replace empty strings in object with null values
// Description: Write a function that replaces empty strings in a JavaScript object with null values.
function replaceEmptyStringsWithNull(obj) {
const result = {};
for (const key in obj) {
result[key] = obj[key] === ” ? null : obj[key];
}
console.log(‘Object after replacing empty strings with null:’, result);
return result;
}
// Test cases for replaceEmptyStringsWithNull
const formValues = { name: ‘John’, email: ”, phone: ‘123-456-7890’ };
replaceEmptyStringsWithNull(formValues);
// Output: { name: ‘John’, email: null, phone: ‘123-456-7890’ } (object after replacing empty strings with null)
// ****************************************************
// Question 16: Extracting information from objects
// Description: Write a function that extracts specific information from a JavaScript object.
function extractObjectInformation(obj) {
const { name, age } = obj;
console.log(`Extracted information: ${name}, ${age} years old`);
return { name, age };
}
// Test cases for extractObjectInformation
const personDetails = { name: ‘Alice’, age: 28, city: ‘London’ };
extractObjectInformation(personDetails); // Output: ‘Alice, 28 years old’ (extracted information)
// ****************************************************
Related topics