In today’s world JavaScript versatile & been widely-used as a programming language that plays an important role in modern web development. Being a JavaScript developer, It’s very important to understand the language’s fundamentals and also adept solving real-world problems. In JS job interviews, JavaScript Interview Questions is been often asked from basic syntax to advanced concepts.
In this article, We will dive into 11 JavaScript questions that are commonly asked in interviews. Each question will be explained in detailed with solution, complete with source code examples where required.
If are you getting prepared for you next job interview or simple learning to enhance your JS skill, this article will have practical solution with code example for better understanding.
5 Interview Questions for JavaScript Job preparation
1. Implement a function that serializes a JavaScript value into a JSON string.
In JS we have a In-Built method i.e. JSON.stringify()
using which we can easily convert javascript object or value into JSON string.
function serializeToJsonString(value) { try { const jsonString = JSON.stringify(value); return jsonString; } catch (error) { console.error('Serialization error:', error); return null; } } // Example JS Object: const data = { name: 'John Doe', age: 30, city: 'Example City' }; const jsonString = serializeToJsonString(data); console.log(jsonString);
In Above example we have a function which accept a data object
and return a jsonString
.
2. Write a JS function which performs a deep copy of a value, and also handles circular references.
Before going in above question let’s understand what is shallow copy and deep copy.
Shallow and Deep copy are concept in JS which is been used while working with object or array in javascipt:
Shallow Copy in JavaScript:
In below source code, I am creating a copy of originalObject using Assignment Operator (=) and then the copyed object shallowCopy is modified…
const originalObject = { a: 1, b: { c: 2 } }; // Shallow Copy using assignment operator const shallowCopy = originalObject; console.log('Original Object: Before', originalObject); console.log('Shallow Copy: Before', shallowCopy); // Modifying the Shallow Copy shallowCopy.b.c = 99; console.log('Original Object:', originalObject); console.log('Shallow Copy:', shallowCopy);
In Shallow Copy when you create a new object using originalObject, actually the shallowCopy points to same address to which originalObject is, Now when we modify shallowCopy the modification is made at address level, due to which originalObject will also get altered.
// OUTPUT Original Object: Before { a: 1, b: { c: 2 } } Shallow Copy: Before { a: 1, b: { c: 2 } } __________________________________________ Original Object: { a: 1, b: { c: 99 } } Shallow Copy: { a: 1, b: { c: 99 } }
Deep Copy in JavaScript:
In below example, JSON.stringify()
is used to serialize the original object into a JSON string, and then JSON.parse()
is used to parse it back into a new object.
Doing this will create a deep copy, making sure that original data is not modified when copy is modified.
// Original Object const originalObject = { a: 1, b: { c: 2 } }; // Deep Copy using JSON.stringify() and JSON.parse() const deepCopy = JSON.parse(JSON.stringify(originalObject)); // Modifying the Deep Copy deepCopy.b.c = 99; console.log('Original Object:', originalObject); console.log('Deep Copy:', deepCopy);
Now, Let’s performs a deep copy of a value, and also handles circular references
Note: We are using NodeJS circular-json
library to handle circular references with deep clone.
const CircularJSON = require('circular-json'); function deepCopyWithCircularHandling(obj) { try { const jsonString = CircularJSON.stringify(obj); const copy = CircularJSON.parse(jsonString); return copy; } catch (error) { console.error('Deep copy error:', error); return null; } } // Example usage: const originalObject = { prop1: 'value1', prop2: { prop3: 'value3' } }; originalObject.circularReference = originalObject; const copiedObject = deepCopyWithCircularHandling(originalObject); console.log(copiedObject);
In this example, the circular-json
library is used to stringify and parse the object with circular references.
3. Create a Function in JS then accepts any numbers of arguments and returned memorized version
To Implement Memorization of data or we can say it as creating a cache of the data returned by a javascript function can be achieved by using caching technique.
Below Code example uses simple cache object.
function memoize(func) { const cache = {}; return function (...args) { const key = JSON.stringify(args); if (cache[key]) { console.log('Fetching from cache'); return cache[key]; } else { console.log('Calculating result'); const result = func(...args); cache[key] = result; return result; } }; } // Example usage: const sum = memoize((...args) => args.reduce((acc, val) => acc + val, 0)); console.log(sum(1, 2, 3)); // Calculating result console.log(sum(1, 2, 3)); // Fetching from cache
4. How do you stop a setInterval() function
We can easily stop setInterval()
function of javascript, by making use of clearInterval(intervalId)
method. The clearInterval method accept a parameter i.e. the ID of setInterval() method by which be can stop further executions of setInterval() func.
var i = 0; const intervalId = setInterval(()=>{ console.log("i=> ",i) i++; if(i===5){ clearInterval(intervalId) } },1000);
The above code will stop execution of setInterval() when i
value is 5.
5. How to Merge Two Object in JavaScript
There are many ways to merge or cancat two object into one, i.e. by using spread operator (...)
or by uisng Object.assign()
method.
The below example to merge two object using spread operator (...)
.
function mergeObjects(obj1, obj2) { return { ...obj1, ...obj2 }; } // Example usage: const obj1 = { a: 1, b: 2 }; const obj2 = { c: 4 }; const mergedObject = mergeObjects(obj1, obj2); console.log(mergedObject); // result: { a: 1, b: 2, c: 4 }
The below example to merge two object using Object.assign() method.
function mergeObjects(obj1, obj2) { // Create a new object and use Object.assign to merge obj1 and obj2 const mergedObject = Object.assign({}, obj1, obj2); return mergedObject; } // Example usage: const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const mergedObject = mergeObjects(obj1, obj2); console.log(mergedObject); // result: { a: 1, b: 3, c: 4 }