0 ratings0% found this document useful (0 votes) 56 views42 pagesJS Interview QA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
6
JavaScript:
Interview Questions
& Challenges
30 questions and challenges you will
find in most interviews.Welcome to "JavaScript: Interview Questions &
Challenges"!
This ebook is designed to help you prepare for
JavaScript job interviews, you will find a collection of
30 commonly asked interview questions and
challenges that will help you practice and master your
JavaScript skills.
These challenges and questions are designed to not
only test your knowledge but also to help you improve
your problem-solving skills.
Whether you are a beginner or an experienced
developer, this ebook is a valuable resource for
anyone who wants to excel in JavaScript interviews.
I'm confident that by working through the challenges
and questions in this book, you will gain confidence in
your skills and be better prepared to impress potential
employers.
So, if you are ready to take your JavaScript skills to
the next level and land your dream job, let's get
started!O| OBJECT KEYS VALUES
atl)
Display all the keys and values of a nested object
function keyValuePrinter(obj) {
cyan GU taal CoV SD an
if (typeof obj[key] =© “object") {
console.log("[" + key +": "+ obj[key] + "]");
} else {
keyValuePrinter(obj[key]);
ss
t
7
STOUT
1. Base case: If the type of a value (under a key) is
different from an object, then we print the key-value
rex
2. If the value is an object, call the function again with
that object (obj[key])
Ol OBJECT KEYS VALUESOAT SSRN
ae)
Swap 2 integers present in variables num1 and num2
without using temporary variable.
let numl = 10, num2 = 20;
[num1, num2] = [num2, num1];
SC
It is possible with simple destructuring assignment using
UNA
1. Create an array with [num2, num1]
2. Assign num1 to first position of newly created array,
num2 to second position, using array destructuring.
02 VARIABLES SWAPORY] mai
dT
Create a function that given an integer it console logs a
step shaped stair with ‘n° levels using the # character.
e.g. steps(2) => # e.g. steps(3) => #
Sd cad
cana
Cx)
of aes) CD
Array.from({ length: n }, (_, i) > i + 1)
-map((x) = '#'.repeat(x))
-map((x) => console.log(x));
Solution:
1. Create an array with n length using Array.from
2. Fill it with numbers from 0 to n with callback fn
3. Map over the array and create another array
with # char repeated from 0 to n.
4. Iterate over the array and console log the
results
03 STAIRS PROBLEMOT Nae e 4
ae)
How do you check if a variable holds an array?
if (Array.isArray(arrayList)) {
// arrayList is an array!
a
SUT
You can use Array.isArray() method
4 ARRAY CHECK05 AGE DIFFERENCE
Problem:
Given the following array of objects, find the difference in
age between the oldest and youngest family members,
and return their respective ages and the age difference.
eee
Uae hae
{
[i= Le tTe
Tt ay
Io
{
[Tl
14a
},
{
[iT ea Cl -8
1+ a oo
},
{
name: ‘Nate’,
\ 4 a
on
]
// Output: [13, 67, 54]
AGE DIFFERENCE05 AGE DIFFERENCE
Cry)
const ages = input.map((person) = person.age)
Ce Gee LEGO CLL Gee CL eee tO
ATC
1. Save only the ages into an array. [13, 56, 45, 67]
2. Math.min() and Math.max() functions accepts an array
of numbers, so create an array where the first position
is the minimum value of the array of ages and the
second position the max age.
3. The last position is the difference between the
Math.min(...) and Math.max(...)
AGE DIFFERENCEOT
dT
(CIN Z-Tae-Tae-TaeNVOd MLNS LC aL a CO SY ne (ML NV
function flatten(arr) {
Pe see rc Ter ast MGs eee Ciacci
oa aClaec Uc Levee eee es Gea 1ac eee es alae ead
Yo Wp
i
BPC
. call reduce array helper method and have the
accumulator (flat) be an empty array that will always be
flat. toFlatten is the current item of the array.
. On each iteration we concatenate the flat array with the
result of calling flatten again if current item is an array,
otherwise concat that value.
. The base case for the recursive call will be when the
toFlatten value is not an array, in which case we just
add it to the array.
O6 FLAT ARRAYOd BL Lt) =
Problem:
A palindrome is a word, phrase, number, or other sequence of
characters which reads the same backward or forward.
Return true if the given string is a palindrome. Otherwise, return
ln
Cx
function palindrome(str) {
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re, ‘');
Pea lie dee) P01 11
eae Chay
+
~ 5
ST UTE
. Lowercase the string and use the RegExp to remove
unwanted characters from it.
2. Use the same chaining methods with built-in functions
from the previous article ‘Three Ways to Reverse a
String in JavaScript’
3. Check if reverseStr is strictly equals to lowRegStr and
return a Boolean
07 PALINDROME08 VOWELS
dT
Given a string of text containing 0 or more vowels, count
the number of vowels that can be found within the text.
function countVowel(str) {
const count = str.match(/[aeiou]/gi). length;
return count;
ATUL
1. The match() method retrieves the result of matching a
string against a regular expression.
2. We are looking for the vowels [aeiou].
3. ‘i in a regular expression is meant to ignore the case,
so it will match both a and A for example.
4. g stands for global, and it tells the match fn to perform
a global search.
08 VOWEIOR RRS salts
dT
What is the difference between null and undefined in
JavaScript?
ATC
1. Undefined: means a variable has been declared but has
not yet been assigned a value.
2. Null: Is an assignment value. It can be assigned to a
variable as a representation of no value.
A-Team t3 8 C- Tay
alert(testVar);
alert(typeof testVar);
var testVar = null;
EV a a-ha
Feed G7 lle al
09 NULL VS UNDEFINEDeS SRS e
Problem:
Given the string ‘XWZ’ return ‘ZWX’
function reverseStr(str) {
return str.split('').reverse().join('');
a
BUC
1. split(”) when applied to a string returns a new array
with each char of the string on a position of the array
like [‘X’, ‘W’, ‘Z’].
2. reverse() function when applied to an array it reverses
the string values like ['Z’, ‘W’, ‘X’]
3. join(”) returns a new string by concatenating all of the
elements in an array, separated by the specified
separator string like ZWX
10 REVERSE A STIRNGWa 2a Ua
Problem:
Write a function that logs the numbers from 1 to n, but
for multiples of 3 prints “fizz” and for multiples of 5
prints “buzz”. For numbers that are multiples of both (3 &
5) prints “fizzbuzz”.
function fizzBuzz(n) {
for (let i = 1; i <=n; i++)
{ if (i % 15 Cane
console. log( 'fizzbuzz' )
} else if (i % 3 === 0) {
console. log( 'fizz')
} else if (i %5 === 0) {
console. log( 'buzz' )
} else {
console. log(i)Wa 2a Ua
Problem:
Write a function that logs the numbers from 1 to n, but
for multiples of 3 prints “fizz” and for multiples of 5
prints “buzz”. For numbers that are multiples of both (3 &
5) prints “fizzbuzz”.
BPC
. If the current number is a multiple of both 3 and 5, it
means that it has to be multiple of 3*5 = 15 (i % 15 === 0),
we print "FizzBuzz".
2. If the current number is only a multiple of 3 (i % 3 === 0),
Ve daa Pea
3. If the current number is only a multiple of 5 (i % 5 === 0),
ce ldiiiaVAL Se
dT
eae EY MVE H MR UNL TTeX es oY 10 CTO Le Le
in JavaScript.
is itblock creates a global is it rmie
BT eg PELE Cag reassignable? redeclarable?
° ) v) (v)
i) c) iv) °
i) od tx x]
| var |
tet |
Subtle use cases to have in mind:
1. var is function scoped when is declared inside a
function
2. const is not reassignable but will accept changes in
NZTIV Som (kel melee) M-TaLe Mol) [Lele]
3. let can be redeclared outside of the scope it was
Cl To -Te-foRU ea
Problem:
Given an array and a chunk size, divide the array into
many subarrays with each subarray being of the chunk
size.
e.g. chunk([1,2,3,4,5], 2) -> [[1,2], [3,4], [5]
re
Cx
function chunk(arr, size) {
CofoT ame nT < a
let index = 0;
NANI G+) aT ele Ld
let chunk = arr.slice(index, index + size);
chunked. push( chunk) ;
index += size;
i
return chunked;
13 CHUNK PROBLEMRU ea
Problem:
Given an array and a chunk size, divide the array into
many subarrays with each subarray being of the chunk
size.
e.g. chunk([1,2,3,4,5], 2) -> [11,2], [3,4], [5]]
re
STM CTE
. create an auxiliary array.
m1 e-L- UP dL Lee
Mae le-h CM UM Tae Neelam at -MO LekT1 Clo
. create the first chunk by slicing the array from the
index until the size parameter. (e.g. chunk = [1,2])
. Increase the index by the size param.
. e.g. index=0+2=2
. repeat the process with new index. This time the new
chunk will be arr.slice(2, 4) = [3,4]ee Ar Aae [hs
dT
Create a function that given a string, it capitalizes the
first letter of the words in a sentence.
e.g. capitalize(“hello world”) -> Hello World
function capitalize(str) {
const words = []
for (let word of str.split(' ')) {
words.push(~${word[0].toUpperCase()}${word.slice(1)}°)
a
return words.join(' ')
}
STC
1. create an auxiliary words array and iterate through
each word in the string.
2. capitalize each word by accessing its first letter and
calling the toUpperCase function.
3. join the words on the auxiliary array with a space
between them.
14 CAPI E WORDSPa ae ata
Problem:
Create a function that given an integer, it returns an
integer that is the reverse ordering of numbers.
e.g. reverselntegers(7364) -> 4637
reverselntegers(-15) -> -51
reverselntegers(-90) -> -9
Ce)
function reverseInteger(num) {
const reversed = num.toString().split('').reverse().join('');
return parseInt(reversed) * Math.sign(num);
+
SC
1. Convert the integer into a string and split the string so
that every number is in a position of the array.
Ve CNTY ma Tae Nr] tTe UTA TE-10 OM TLL 1 Uatele
3. Convert the array back to string and convert it into an
integer and multiply it by it’s original sign.
15 REVERSE INTEGERS16 FIRST NON REPEATING
LT ee
dT
How could you find the first non repeating char ina
string?
e.g. firstNonRepeatingChar(“This is an example sentence”) -> h
function firstNonRepeatingChar(str) {
SU Sl eee ha leh
ii ate ee
let charCount = {};
eG ae aC Oecd eee ee
Cranes AO Pee Rol ote tT
if (charCount[char]) {
charCount[char] ++;
Pa Led
charCount[char] = 1;
+
+
for (let j in charCount) {
if (charCount[j] === 1) {
rere
+
+
}
16 FIRST NON REPEATING CHARACTER16 FIRST NON REPEATING
LT ee
dT
How could you find the first non repeating char ina
string?
e.g. firstNonRepeatingChar(“This is an example sentence”) -> h
SC
1. create a char auxiliary variable to store each charater
Coleen Lae
2. create a charCount object to store a key value map of
each character and the amount of times it exists on the
sentence. Something like { ‘s’: 2, ‘j’: 1 ...}
3. iterate through each letter on the sentence.
4. store each character on a temp auxiliary variable.
5. If that character doesn't exist on the charCount object
we add it with an occurrence of 1, otherwise we just
CTalol kX ML Moe C Uo
6. Finally we iterate over the charCount object and return
the first key (character) which occurrence count is 1.
16 FIRST NON REPEATING CHARACTER17 HIGHEST OCCURRENCE
dT
Given an array, get the element with the highest
occurrence in an lech
CROC erate EPA R A ee
Saat Mn caeete ante laa Na ne A
if (array.length == 0) {
xtc te
+
NE Ven tele cyte 1) eae Ot
var maxEl = array[0], maxCount = 1;
Saran eee Oear Ta Vea 1c ee)
a
var el = array[i];
if (occurrenceMap[el] =:
occurrenceMap[el]
pet ad
occurrenceMap[el]++;
Liao eg
ao)
+
if (occurrenceMap[el] > maxCount) {
maxEl = el;
maxCount = occurrenceMap[el];
}
+
ion ie
(7 HIGHEST OCCURRENCE17 HIGHEST OCCURRENCE
dT
Given an array, get the element with the highest
occurrence in an lech
CROC erate EPA R A ee
2 STM OTB
elie M On mime
2. create auxiliary variables for the amount of element
occurrences, the current max element, and the max
count an element has been repeated.
3. iterate through the array and store each element on the
CNC)
4. if our occurrence map object has already a count for
that element, we increase its value, otherwise we
TN ieeN 4 Tana ae Molen ela rex mereLe La) LG
mmol lec aa al emolecel eee mere MeL Ua)
the max count, we set the current element as the
element with maximum count, and we update our
maxCount variable with the element's count.
CT MEl CG tM aaa eae Cate aCe)
Lm UCELEE) A
(7 HIGHEST OCCURRENCEeM SY
Problem:
Given two arrays of primitives, return the elements that
are included in both arrays (intersection).
e.g. intersection([1,2,3], [2,3,4,5]) -> [2, 3]
function intersection(arri1, arr2) {
paLe aint BRS OV NNT eM bo woe -S1 OI TEUT-D DY
}
SC
Se licrar-l ated Tat nm cee Na) UCM §
included in the second array.
PPe Colm MOSM TMi Tme- TN a) TARA Uae are aCe]
is that the current value of the array has to be included
in the second array.
18 INTERSECTIONa Cad Gh
dT
Write a method that given an object with key value pairs,
returns a deep array like [[key, value]]
e.g. makePairs({ a: 1, b: 2 }) -> [['a’, 1], ['b’, 2]
bias CMC bell sD aed
return Object.keys(obj).map((key) = [key, obj[key]]);
t
SC
1. Object.keys returns an array with all the keys of the
object.
2. we iterate over those, and for each key, we return an
array that has the key in the first position and the value
of that key (obj[key]) in the second position.
19 MAKE PAIRS20 TOTAL PRICE
Problem:
Create a function that takes an array of objects
(groceries) which calculates the total price and returns it
as a number. A grocery object has a product, a quantity
and a price, for example:
e.g. getTotalPrice([ { product: "Milk", quantity: 3, price: 1.50 },
{ product: "Cereals", quantity: 2, price: 2.50} ]) 4 9.5
Saree Nel ee LK h e-NM oe Rel co eee D eS
return groceries.reduce((acc, curr) > {
acc += curr.price * curr.quantity;
Bataan Lototy
nD)
os
20 TOTAL PRICE20 TOTAL PRICE
Problem:
Create a function that takes an array of objects
(groceries) which calculates the total price and returns it
as a number. A grocery object has a product, a quantity
and a price, for example:
e.g. getTotalPrice([ { product: "Milk", quantity: 3, price: 1.50 },
{ product: "Cereals", quantity: 2, price: 2.50} ]) 4 9.5
SUC
1. we use reduce array helper and create an accumulator
value that starts from 0.
2. On each iteration we increment the accumulator by the
rectal Clann dX Mem Ol ee TALULA
3. we return the accumulator on each iteration
20 TOTAL PRICEARS
Problem:
An array is positive dominant if it contains strictly more
unique positive values than unique negative values. Write
a function that returns true if an array is positive
dominant.
e.g. isPositiveDominant(|1, 1,-2,-3]) -> false
PORTA LeU (ia a) eo COT
eee
STC KL eR ALP tS
const positives = new Set(arr.filter(n > n > 0));
a Sta A Ue Lee Se DD
return positives.size > negatives.size;
21 POSITIVE DOMINANTARS
Problem:
An array is positive dominant if it contains strictly more
unique positive values than unique negative values. Write
a function that returns true if an array is positive
dominant.
e.g. isPositiveDominant(|1,1,-2,-3]) -> false
isPositiveDominant([1,2,3,-1,-2]) -> true
SUC
1. we create two Sets, one with an array of positive values
from arr, and the other with negatives values from arr.
2. because a value in the Set may only occur once, we
CeLUEsTe-TaN tom UOT ard aT LULSME- Te Te [OL
3. .size attribute of a set returns the size of the set, how
many values does it hold. Is positive dominant if the
size of the positive set is larger than the size of the
negative set.
21 POSITIVE DOMINANT22 TWO DISTINCT ELEMENTS
Problem:
In each input array, every number repeats at least once,
except for two. Write a function that returns the two
unique numbers.
e.g. returnUnique([1, 9, 8, 8, 7, 6, 1, 6]) > [9, 7]
function returnUnique(arr) {
ae se chee SC ae seen SOC ee meee en Sie Dr
7
STC
1. We filter the array using the following condition; the
first index position of the element in the array has to be
the same as the last index position of the element. This
guarantees that the element is unique, because it
doesn’t occur again in the array.
22 TWO DISTINCT ELEMENTS23 REVERSE THE ODD LENGTH
PUTS
eae) Te
CCT -TaMe-Meod Cn ne PDA -1 EXT AT-M OLSEN Tal Cel am a-hole Le]
length. The even length words are not changed.
e.g. reverseOdd("Bananas") — "sananaB"
function reverseOdd(str) {
return str.split(" ")
-map(w => w.Length%2 ? [...w].reverse().join(""
CC ee
BOC
1. we convert the string into an array of words by using
str.split(““).
2. we check if the word has odd characters by checking
the remainder of w.length/2. If the remainder is 0 it
means the word has even characters, otherwise it has
(ofele Rela e-lol ee
3. if it has odd characters, we split the words characters
into a new array and we reverse it to return the
reversed word.
4, last, we join the words with a space between them
23 REVERSE THE ODD LENGTH WORDS24 HOURS PASSED
Problem:
Vitter Colma Lene- Lm Tm ae Lm VARTA)
returns the numbers of hours passed between the two
scale
e.g. hoursPassed("3:00 AM", "9:00 AM") + "6 hours”
ciLasCUM TCT eseoe Et
eee me een)
roe Gees ean)
eet Gn ESS Pere LEG
).replace(' PM','+12').replace(':00"
Se oR este) ee Ot Oe
Solution:
1. we replace AM or PM with an empty string or with +12
respectively.
2. we also replace :00 with an empty string as we only
oFTie-Lefe lL ment -MtTel Ee
3. if after doing so, t1 == t2 we set t1 to 0 and return the
difference between t1 and t2. We return no time has
passed if t1 == t2.
24 HOURS PASSED25 WHITE SPACES
Problem:
Write a function that inserts a white space between
every instance of a lower character followed immediately
by an upper character.
e.g. whiteSpaces(“HelloMyNamelsGeorge”) -> Hello My Name Is George
ORME C Rat ae Cc eee)
ieee eee arse ee SRE a
SC
1. we use the replace function against a regular
expression to solve this.
2. /([a-z][A-Z])/g will match all the lower case letters
followed immediately by an uppercase letter. e.g. oM,
iN
3. the second parameter of the replace function can take
a callback function with the maches from the regular
expression, in our case lower is the lowercase (0,y,e,s)
and the upper is the uppercase letter (M,N,Y,G)
4. we replace those by adding a space between them.26 PRIME NUMBERS
dT
Create a function that returns true if there's at least one
prime number in the given range (n1 to n2 (inclusive)),
false otherwise.
e.g. primelnRange(10, 15) — true // Prime numbers in range: 11, 13
ceo
aCe meme
for (let i = 2; i < num; i += 1) if (num % i == Q) return false;
sara ea
A
const primeInRange = (low, high) => {
Gta SC
SOC SU CCUDD Mestad aa Ts
t
Sar TE
26 PRIME NUMBERS26 PRIME NUMBERS
Problem:
ere N ol MUD Ge mL Lee (aod
prime number in the given range (n1 to n2 (inclusive)),
false otherwise.
e.g. primelnRange(10, 15) — true // Prime numbers in range: 11, 13
SUC
1. we iterate from n1 (low) to n2 (high), and we call an
aux function isPrime() on each number. It there is one
number that is prime we return true.
2. to check if a number is prime, we check the remainder
of dividing the number by num. If the remainder is 0
then it means the number is not prime, otherwise it’s
fede
26 PRIME NUMBERSAV |
STRING
Problem:
Given a word, create an object that stores the indexes of
Yel (1c
+ Make sure the letters are the keys.
+ Make sure the letters are symbols.
+ Make sure the indexes are stored in an array and
those arrays are values.
e.g. mapLetters("dodo") — { d: [0, 2], 0: [1, 3] }
const mapLetters = (str) =>
Array.from(str).reduce((accumulator, currValue, index) => {
return { ...obj, [char]: [...(obj[char] || []), index] }
3, {})
SC
1. we create an array from the string and we apply the
reduce function with an object as the accumulator.
PROM -r Ceol MCAT EM ol)
before (...obj) and then in the char key ([char]) we
Ry olcrTe male leo ee eon Roe Ode
add the index to the array like [...(obj[char] || []), index]
27 MAP THE LETTERS IN A STRING28 MULTIPLICATION TABLE
dT
Create N x N multiplication table, of size n provided in
exelent
For example, when n is 5, the multiplication table is:
+ 1,2,3,4,5
Cre ae Pa)
+ 3,6, 9, 12, 15
+ 4,8, 12, 16, 20
Satan |e yard ar)
iran eet eke rete ens
Array.from({length: n}, (_, i) >
Array.from({length: n},(_, 3) = (i + 1) * (j + 1)));
28 MULTIPLICATION TABLE28 MULTIPLICATION TABLE
dT
Create N x N multiplication table, of size n provided in
exelent
For example, when n is 5, the multiplication table is:
+ 1,2,3,4,5
Cre ae Pa)
+ 3,6, 9, 12, 15
+ 4,8, 12, 16, 20
Satan |e yard ar)
BUC
1. we use Array.from function that takes a callback fn as
second parameter to initialize each element.
2. we also use Array.from to create another array for the
nested arrays.
3. On each iteration we use the index of the first array (i)
as base number for multiplication.
4. On each iteration we use the index of the second array
(j) as the multiplier which will always range between (0-
iD)
28 MULTIPLICATION TABLEPa IY emu lt),
ELEMENTS
Problem:
Create a function that takes two "sorted" arrays of
numbers and returns an array of numbers which are
common to both the input arrays.
commonElements(I-1, 3, 4, 6, 7, 9], [1, 3]) > [3]
commonElements({1, 3, 4, 6, 7, 9], [1, 2, 3, 4, 7, 10]) — [1, 3, 4, 7]
function commonElements(arri,arr2) {
Paes ose Rete samen ant Ce)
7
ST
1. we filter the second array by the following condition: if
Re a MLC) UL) A
we return that element, because it means it’s in both
Eee
29 FINDING COMMON ELEMENTSSTO Mma ee
Nei
dT
Create a function that returns the Nth number in the
Fibonacci sequence
fibonacci(10) + "55"
fibonacci(20) + "6765"
function fib(n) {
chan Car
return n
t
return fib(n - 1) + fib (n - 2)
i
SO
1. the base case for fibonacci is when the number is less
Ur -A OeV aor Lo
2. for the remaining cases we return the result of running
fib(n - 1) + fib(n - 2) because for any given number the
result of a fibonacci sequence is the sum of the last
Aa oe
30 NTH FIBONACCI NUMBERThank you for taking the time to go through my
Javascript interview questions and challenges.
| hope that my content has provided you with valuable
insights and knowledge that can help you improve
your skills as a Javascript developer.
If you found it helpful and want to take your skills to
the next level, | highly recommend checking out my
content on HTML and CSS, UX/UI and more here:
https://georgemoller.gumroad.com/.
Thank you once again for your interest in my
Javascript interview questions and challenges, and |
wish you all the best in your learning journey.