Join our community to see how developers are using Workik AI everyday.
Q6: What is the difference between == and === in JavaScript?
==
(Abstract Equality):
Compares two values for equality, performing type conversion if necessary.
===
(Strict Equality):
Compares two values for equality without performing type conversion. Both the value and the type must be the same.
console.log(5 == '5'); // true (type conversion happens)
console.log(5 === '5'); // false (no type conversion)
Q7: Explain the concept of Prototypal Inheritance in JavaScript.
Prototypal Inheritance is a feature in JavaScript where objects can inherit properties and methods from other objects. Each object has a private property (prototype) that holds a link to another object called its prototype. This chain of prototypes is known as the prototype chain.
const animal = {
eat: function() {
console.log('Eating...');
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log('Barking...');
};
dog.eat(); // Eating... (inherited from animal)
dog.bark(); // Barking...
Q8: What is a Higher-Order Function in JavaScript?
A Higher-Order Function is a function that can take other functions as arguments and/or return functions as its result. These are used extensively in functional programming.
function higherOrderFunction(callback) {
return function(x) {
return callback(x);
};
}
const double = higherOrderFunction(function(x) {
return x * 2;
});
console.log(double(5)); // 10
Q9: What is the
this
keyword, and how is it used in JavaScript?
The
this
keyword refers to the object it belongs to. Its value is determined by how a function is called:
function showThis() {
console.log(this);
}
const obj = {
method: showThis
};
showThis(); // Window (or global object in Node.js)
obj.method(); // obj
Q10: What is the difference between synchronous and asynchronous code in JavaScript?
Synchronous Code: Executes sequentially, blocking further execution until the current operation completes.
Asynchronous Code: Executes independently of the main program flow, allowing other operations to run while waiting for an asynchronous operation to complete.
// Synchronous
console.log('Start');
console.log('End');
// Asynchronous
console.log('Start');
setTimeout(() => {
console.log('Middle');
}, 1000);
console.log('End');
Request question
Please fill in the form below to submit your question.
Q11: What are arrow functions, and how do they differ from regular functions in JavaScript?
Arrow functions are a shorthand syntax for writing function expressions in JavaScript. They differ from regular functions in several key ways:
this
Binding:
Arrow functions do not have their own
this
context; they inherit this from the enclosing scope.
arguments
Object:
Arrow functions do not have their own
arguments
object.
// Regular function
function regularFunction(a, b) {
return a + b;
}
// Arrow function
const arrowFunction = (a, b) => a + b;
Q12: What is the difference between
null
and undefined in JavaScript?
null
:
Represents the intentional absence of any object value. It is an assignment value that indicates a variable points to no object.
undefined
:
Indicates that a variable has been declared but has not yet been assigned a value.
Q13: Explain the concept of currying in JavaScript.
Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument. This allows partial application of a function's arguments.
function curryFunction(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}
const curried = curryFunction(1)(2)(3); // 6
Q14: What is event delegation in JavaScript?
Event delegation is a technique where a single event listener is added to a parent element to manage events for its child elements. This is useful for handling events efficiently when dealing with many child elements.
Q15: What are JavaScript promises, and why are they useful?
Promises are objects representing the eventual completion or failure of an asynchronous operation. They are useful for managing asynchronous code in a more readable and maintainable way compared to callbacks, avoiding callback hell.
let promise = new Promise((resolve, reject) => {
// asynchronous operation
let success = true;
if (success) {
resolve('Operation was successful');
} else {
reject('Operation failed');
}
});
promise
.then((message) => console.log(message))
.catch((error) => console.error(error));
Request question
Please fill in the form below to submit your question.
Q16: What are the main differences between
forEach
,
map
, and
filter
methods in JavaScript?
forEach
:
Iterates over array elements, executing a provided function once for each element. It does not return a new array.
map
:
Iterates over array elements, executing a provided function for each element and returning a new array with the results.
filter
:
Iterates over array elements, executing a provided function for each element, and returns a new array containing only the elements that pass the test implemented by the function.
Q17: Explain the concept of
async
and
await
in JavaScript.
async
and
await
are syntactic sugar for working with Promises, making asynchronous code look and behave more like synchronous code.
async
:
Declares an asynchronous function, which implicitly returns a Promise.
await
:
Pauses the execution of an async function until the Promise is resolved, returning the resolved value.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
Q18: What is the
bind
method in JavaScript, and how is it used?
The
bind
method creates a new function that, when called, has its
this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
const person = {
name: 'John',
greet: function(greeting) {
console.log(greeting + ', ' + this.name);
}
};
const greetJohn = person.greet.bind(person, 'Hello');
greetJohn(); // Hello, John
Q19: Explain the concept of debouncing and throttling in JavaScript.
Debouncing: Ensures that a function is not called again until a certain amount of time has passed since it was last called. Useful for limiting the rate at which a function is executed.
function debounce(func, wait) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), wait);
};
}
Throttling: Ensures that a function is called at most once in a specified time period. Useful for controlling the execution rate of an event handler.
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
Q20: What is the event loop, and why is it important in JavaScript?
The event loop is a fundamental part of JavaScript's concurrency model. It allows JavaScript to perform non-blocking operations by offloading operations to the browser (or Node.js) and running a loop that checks for tasks, executes them, and then waits for more tasks.
Request question
Please fill in the form below to submit your question.
(Basic)
function sumArray(arr) {
let sum = 0;
for (let i = 0; i <= arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(sumArray([1, 2, 3, 4])); // Expected output: 10
The loop should iterate until
i < arr.length
instead of
i <= arr.length
.
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(sumArray([1, 2, 3, 4])); // Output: 10
(Intermediate)function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Expected output: 120
Use an iterative approach to avoid stack overflow.
function factorial(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // Output: 120
(Basic)
function findLargest(arr) {
let largest = -Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
console.log(findLargest([1, 2, 3, 4, 5])); // Expected output: 5
Use the
Math.max
method combined with the spread operator for better performance and readability.
function findLargest(arr) {
return Math.max(...arr);
}
console.log(findLargest([1, 2, 3, 4, 5])); // Output: 5
(Basic)
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString('hello')); // Output: 'olleh'
(Medium)
var a = 10;
function foo() {
console.log(a);
var a = 20;
console.log(a);
}
foo();
The output will be:
undefined
20
Explanation:
The variable
a
inside the function is hoisted but not initialized, so the first
console.log(a)
prints
undefined
. After the initialization, the second
console.log(a)
prints
20
.
(Basic)
function removeDuplicates(arr) {
return [...new Set(arr)];
}
console.log(removeDuplicates([1, 2, 3, 2, 4, 3, 5])); // Output: [1, 2, 3, 4, 5]
(Basic)
function concatenateArrays(arr1, arr2) {
return arr1.concat[arr2];
}
console.log(concatenateArrays([1, 2], [3, 4])); // Expected output: [1, 2, 3, 4]
function concatenateArrays(arr1, arr2) {
return arr1.concat(arr2);
}
console.log(concatenateArrays([1, 2], [3, 4])); // Output: [1, 2, 3, 4]
(Intermediate)
function findSecondLargest(arr) {
let largest = -Infinity;
let secondLargest = -Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] < largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
console.log(findSecondLargest([1, 2, 3, 4, 5])); // Expected output: 4
The code is already efficient, but it can be slightly refactored for better readability.
function findSecondLargest(arr) {
let [largest, secondLargest] = [-Infinity, -Infinity];
for (let num of arr) {
if (num > largest) {
[secondLargest, largest] = [largest, num];
} else if (num > secondLargest && num < largest) {
secondLargest = num;
}
}
return secondLargest;
}
console.log(findSecondLargest([1, 2, 3, 4, 5])); // Output: 4
(Intermediate)
let x = 10;
function bar() {
console.log(x);
if (false) {
var x = 20;
}
console.log(x);
}
bar();
The output will be:
undefined
undefined
Explanation: The variable
x
inside the function is hoisted but not initialized, so both
console.log(x)
statements print
undefined
.
(Intermediate)
let x = 10;
function bar() {
console.log(x);
if (false) {
var x = 20;
}
console.log(x);
}
bar();
The output will be:
undefined
undefined
Explanation: The variable
x
inside the function is hoisted but not initialized, so both
console.log(x)
statements print
undefined
.
(Advanced)
function flattenArray(arr) {
return arr.reduce((flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
}, []);
}
console.log(flattenArray([1, [2, [3, [4]], 5]])); // Output: [1, 2, 3, 4, 5]
Request question
Please fill in the form below to submit your question.