Cribsheet for JavaScript Coding Interview

Cribsheet for JavaScript Coding Interview

The coding interviews / coding challenges are designed to assess how productive someone can be with the language. In contrast to the algorithm whiteboarding interview, which assesses how the candidate go about solving a problem, or the architecture design interview, which assesses how the candidate’s experience in system engineering and product design, the coding interview is is utilized by the company interviewing you to answer one question:

The coding interviews / coding challenges are designed to assess how productive someone can be with the language. In contrast to the algorithm whiteboarding interview, which assesses how the candidate go about solving a problem, or the architecture design interview, which assesses how the candidate’s experience in system engineering and product design, the coding interview is is utilized by the company interviewing you to answer one question:

Can you be productive with JavaScript? You are usually given the flexibility of choosing the language you are most comfortable with to complete the coding challenge. Thus it’s expected you know how to take advantage of all the language specific features and deal with the language specific idiosyncrasies (JavaScript has a lot) to solve problems.

These tests are also designed to gauge your knowledge of computer science fundamentals like various data structures (e.g., arrays, strings, object/dictionaries), logic building blocks (e.g., loops, if-statements, functions), and problem solving patterns (e.g., recursion, pattern matching, higher order functions).

For coding challenges, there’s always a time limit. The faster you can solve a problem correctly, the better. Thus, this post introduces JavaScript features, best practices, to leverage and common pitfalls to avoid to help you get productive with JavaScript and get the right result quickly.

Working with Strings

Regex

In a nutshell, regular expression, or regex for short, are patterns you specify to test a string. There are whole books written about Regexes. We are going to focus on the most likely problem we’re going to need to solve with regex during a coding challenge:

Does the string contain this pattern? If so, how many times does this pattern appear? Where does it appear? Let’s consider this coding challenge: Given a string, determine if the string is a url. We can assume we only want to test for websites with the .com and .org top level domains. We don’t care if the website actually exists or not.

Input and expected output:

  • “google.com” → true
  • www.icann.org" → true
  • “google.foobar” → false
const isStrUrl = str => {
  const matchTld = /(\.com|\.org)$/i
  return matchTld.test(str);
};

The matchTld is the regex that specifies that we are looking for a string that ends with .com or .org. The \. escapes the dot (.). The ```The coding interviews / coding challenges are designed to assess how productive someone can be with the language. In contrast to the algorithm whiteboarding interview, which assesses how the candidate go about solving a problem, or the architecture design interview, which assesses how the candidate’s experience in system engineering and product design, the coding interview is is utilized by the company interviewing you to answer one question:

Can you be productive with JavaScript? You are usually given the flexibility of choosing the language you are most comfortable with to complete the coding challenge. Thus it’s expected you know how to take advantage of all the language specific features and deal with the language specific idiosyncrasies (JavaScript has a lot) to solve problems.

These tests are also designed to gauge your knowledge of computer science fundamentals like various data structures (e.g., arrays, strings, object/dictionaries), logic building blocks (e.g., loops, if-statements, functions), and problem solving patterns (e.g., recursion, pattern matching, higher order functions).

For coding challenges, there’s always a time limit. The faster you can solve a problem correctly, the better. Thus, this post introduces JavaScript features, best practices, to leverage and common pitfalls to avoid to help you get productive with JavaScript and get the right result quickly.

Working with Strings

Regex

In a nutshell, regular expression, or regex for short, are patterns you specify to test a string. There are whole books written about Regexes. We are going to focus on the most likely problem we’re going to need to solve with regex during a coding challenge:

Does the string contain this pattern? If so, how many times does this pattern appear? Where does it appear? Let’s consider this coding challenge: Given a string, determine if the string is a url. We can assume we only want to test for websites with the .com and .org top level domains. We don’t care if the website actually exists or not.

Input and expected output:

  • “google.com” → true
  • www.icann.org" → true
  • “google.foobar” → false
const isStrUrl = str => {
  const matchTld = /(\.com|\.org)$/i
  return matchTld.test(str);
};

The matchTld is the regex that specifies that we are looking for a string that ends with .com or .org. The \. escapes the dot (.). The `` at the end of the regex means this pattern should appear at the end of the string. In summary:

const matchApple = /^apple$/
matchApple.test(‘apple’); //> true
matchApple.test(‘orange’); //> false
matchApple.test(‘apples’); //> false
matchApple.test(‘Apple’); //> false

As illustrated with the above example, regex is case sensitive.

If you want to match a sequence of characters regardless of whether the letters are upper case or lower case, you could convert every letter in the string to lowercase, then do the pattern matching:

const str = ‘Apple’.toLowerCase();
matchApple.test(str); //> true

String manipulation

Suppose we have a string containing alphanumeric characters sprinkled with some illegal characters, in particular, angle brackets, forward slash, backward slash, and quote. We want to remove the illegal characters and retain just the letters. How would we go about this string manipulation?

Using regex:

const dirtyStr = "<script>window.location=\"http://evil.com\"</script>";
const matchIllegals = /<|>|\\|\/|"/g;
const cleanStr = dirtyStr.replace(matchIllegals, "");
console.log(cleanStr); //> scriptwindow.location=http:evil.comscript

We are using the JavaScript built-in function for string, i.e., replace, to replace every angle bracket, slash, and quote in the string with empty string, effectively removing them from the string.

Get Characters from String

str.chartAt(i) gives us the character at a index i from str.

let str = 'hello'
str.charAt(0) //> 'h'
str.charAt(str.length-1) //> 'o'
str.charAt(str.length) //> ''

What happens if we do the following?

str.charAt(str.length) //> ''

It returns an empty string! You don’t get any help like the index out of bounds error that people who work with a statically typed language with a compiler like Java would be familiar with. This could be a really nasty bug. A similar thing happens with arrays when you access an index out of bound array element: arr[arr.length] gives you undefined.

Getting Multiple Characters (Substrings)

Say we have “hello world” as our string but we only want “world”. What do we do? Slice recursively. “hello” plus space is 6 characters.

“hello world”.slice(6) //> “world”

Using slice works because a string is really just an array of characters.

A more general function for obtaining the substring is appropriately called substring and it takes two arguments: where to start (inclusive) and where to stop (exclusive). Here’s how you use substring:

'hello'.substring(0, 2); //> 'he'

However, using slice and substring for extracting the sub-string requires knowing exactly where is the starting index is. Usually, the substring we want to extract are delimited by a space or a special character such as a slash. Suppose we have the following problem:

Get the username from the Medium url for user profile. Usually, webpages for user profile pages on social networking websites have the following form:

https://<domainName>/<route>/<username>

What we want is the username at the end. SincedomainName and route could be arbitrarily long, we can’t use slice to solve our problem. What we can do is this:

const getUsername = url => {
  return url.split(‘/’).pop().slice(1);
};
getUsername('https://medium.com/@xiaoyunyang') //> xiaoyunyang

getUsername function has a one-liner solution but there are few things going on:

  1. split('/') splits the url string into an array of substrings using the slash (/) as delimiter. The output of the split('/') operated on our example url becomes [ 'https:', '', 'medium.com', '@xiaoyunyang' ], which gets piped into the next operation pop().
  2. pop() is a built-in function for arrays we will discuss later. What it does is it returns the last element of the array and in the process, mutating the original array. pop() could get us in hot water (we will discuss later in the arrays section) because it’s mutating the original array but in this case, it’s okay because the array we got from split is an intermediate throw-away data structure that we are only using for deriving the final result. The pop() operation gives us @xiaoyunyang, which we pipe into the next operation.
  3. slice(1), as discussed above, returns the substring starting from index 1 until the end of the array. This effectively chops off the @ and gives us xiaoyunyang, which is the username.

    Working with Arrays

When we work with arrays in JavaScript, we have a whole suite of built-in functions we can use. This section discusses those functions that returns arrays or mutates the original array. A later section will discuss how to use JavaScript built-in functions for arrays to transform the array to other data types.

Add things to an array and combine arrays

Mutable

  • array.push(elem) — adds elem to the end of array
  • array.unshift(elem) — adds elem to the beginning of array

Example:

const mutatingAdd = [1, 2, 3];
mutatingAdd.push(4); //> [1, 2, 3, 4]
mutatingAdd.unshift(0); //> [0, 1, 2, 3, 4]
console.log(mutatingArr); //> [0, 1, 2, 3, 4]

Immutable

  • array.concat(elem) — adds elem to the front or back of an array without mutating the original array
  • [...arr1, …arr2] — ES6 Spread operator to merge two arrays
  • [elem, ...arr2] — ES6 add elem to head of the array
  • [...arr1, elem] — ES6 add elem to tail of the array

Example with concat:

const arr0 = [0];
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = arr1.concat(arr2); //> [1, 2, 3, 4]
const arr4 = arr0.concat(arr3); //> [0, 1, 2]
const arr5 = arr0.concat(arr1, arr2) //> [0, 1, 2, 3, 4]

Example with spread operator

const arr0 = [0];
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [...arr1, ...arr2]; //> [1, 2, 3, 4]
const arr4 = [...arr0, ...arr1]; //> [0, 1, 2]
const arr4_altern = [0, ...arr1]; //> [0, 1, 2]
const arr5 = [...arr0, ...arr1, ...arr2]; //> [0, 1, 2, 3, 4]

Extract and remove things from an array

We can access elements in the array using the index. This pattern is commonly used in many other programming elements. This section goes into more details about how to take advantage of JavaScript-specific built-in function to speed up problem solving.

A common thing we need to do with arrays is to remove the last thing in the array. Since the goal is to mutate the original array, one convenient function helps us do exactly that:

array.splice(-1) — return the tail of array as an array and mutates array.

Example:

const arr = [0, 1, 2];
const tailArr = arr.splice(-1);
console.log(tailArr) //> [2]
console.log(arr) //> [0, 1]

One gotcha with using splice in this way is arr.splice(-1) returns the tail element of arr wrapped in an array. If you just want elem, you can use ES6 destructuring:

const [tail] = tailArr;
console.log(tail); //> 2

Unfortunately, ES6 destructuring does not support extraction of last element of an array. However, ES6 destructuring and rest operator is very useful for returning the head of the array as elem instead of an array containing an elem without mutating the rest of the array:

const arr = [0, 1, 2];
const [head, ...rest] = arr;
console.log(head); //> 0
console.log(rest); //> [1, 2]
console.log(arr); //> [0, 1, 2]

In fact, you can use ES6 destructuring to get extract more than one elements from the array starting from the head of the array:

const arr = [0, 1, 2, 3, 4, 5];
const [first, second, third, ...rest] = arr;

If you just want to return the last element of the array without mutating the original array, we can use arr.slice(-1):

const arr = [0, 1, 2];
const tailArr = arr.slice(-1);
console.log(tailArr); //> [2]
console.log(arr); //> [0, 1, 2]

slice and splice are useful for extracting any part of the array, not just the tail. The general way you use these functions is arr.slice(from, until) and arr.splice(from, until) where from and until are indices. The sub-array returned from these operations includes the element at index from until the element that precedes index until. For example:

const numbers = [0, 1, 2, 3, 4];
const lessThanThree = numbers.slice(0, 3); //> [0, 1, 2]
const moreThanTwo = numbers.splice(2, numbers.length); //> [2, 3, 4]
console.log(numbers); //> [0, 1]

Beware! If you reversed the order in which you use slice and splice, in the code above, the code will not have any run-time errors but you’re going to have some nasty logic bugs:

const numbers = [0, 1, 2, 3, 4];
const moreThanTwo = numbers.splice(2, numbers.length); //> [2, 3, 4]
const lessThanThree = numbers.slice(0, 3); //> [0, 1]
console.log(lessThanThree); //> [0, 1] …not [0, 1, 2] as we expect

Therefore, when you are trying to quickly solve a programming problem correctly, be absolutely disciplined about using immutable functions like slice and ES6 destructuring so you’re not spending 10 minutes of your 30 minute coding challenge time debugging this bug.

Sorting things in Array

Suppose we have the following numbers we would like to sort:

const nums = [3, 2, 7, 1, 2, 0];

Sort in ascending order:

nums.sort((a,b) => {
  return a-b
});
console.log(nums); //> [ 0, 1, 2, 2, 3, 7 ]

Sort in descending order

nums.sort((a,b) => {
  return b-a
})
console.log(nums); //> [ 7, 3, 2, 2, 1, 0 ]

It’s important note that the sort function mutates the original array!

If you don’t pass in a function, sort will by default give you the mutated array in ascending order.

const letters = ['c', 'r', 'a', 'b', 'a', 't']
letters.sort()
letters //> [ 'a', 'a', 'b', 'c', 'r', 't' ]

Working with Objects

JavaScript Objects are used to store key-value pairs and can nest other objects as deep as you want. In JavaScript, arrays are actually objects where the keys are numbers. I can make an array using an object notation:

const arr1 = {
  0: 0,
  1: 1,
  2: 2
}
const arr2 = [0, 1, 2];

The syntax I use to access the elements from the object and array are indistinguishable:

arr1[1] //> 1
arr2[1] //> 1

This is how I remember the rules for accessing the value of an object using the key — it looks just like the way you access the element of an array at a given index!

const basket = {
  'apple': 1,
  'pear': 2
};
const numApple = basket['apple']; //> 1
const numPear = basket['pear']; //> 2

Size of object

Object.keys(dict).length gives you the number of entries in the object called dict (short for dictionary).

For example:

let basket = {};
Object.keys(basket).length; // 0
basket = {apple: 2}
Object.keys(basket).length; // 1

Merging two objects

Use spread operator.

There’s a more verbose way of doing it but we are using ES6’s spread operator here:

const foo = {a: 'a', b: 'b'}
const bar = {c: 'c', d: 'd'}
const foobar = {...foo, ...bar} //> {a: 'a', b: 'b', c: 'c', d: 'd'}

you can also use the spread operator to make a deep copy of the object.

const foobarCpy = {...foobar} //> {a: 'a', b: 'b', c: 'c', d: 'd'}

Consistent with the tip above for preferring slice over splice for array operations, we want to err on the side of immutability. We want to make deep copies of things before we start changing things in arrays and objects to avoid nasty bugs and side effects. Assigning objects to another variable does not make a copy of the object, rather, it creates a new reference to the original object:

const basket = {
  apple: 1,
  pear: 2
};
basket2 = basket;
basketCpy = {...basket};
console.log(basket === basket2); //> true
console.log(basket === basketCpy); //> false

Add and remove things from object

Add to object (functional way):

const addToDict = (dict, newKey, newVal) => {
  if (dict[newKey]) return dict;
  const newDict = {...dict};
  newDict[newKey] = newVal;
  return newDict;
};

Delete from object (functional way):

const deleteFromDict = (dict, newKey, newVal) => {
  if (!dict[key]) return dict;
  const newDict = {…dict};
  newDict[key] = newVal;
  return newDict;
};

Sometimes for performance reasons, it’s desirable to add/delete from object by mutating the object:

const foobar = {'foo': 'foo', 'bar': 'bar'};
delete foobar['bar'];
foobar['baz'] = 'baz';
console.log(foobar); //> { foo: 'foo', baz: 'baz' }

Compare two objects

What if you have two dictionaries and you want to see if they are equal? The trick is to use JSON.stringify.

let dict1 = {};
dict1['a'] = 1;
dict1['b'] = 2;
let dict2 = {};
dict2['a'] = 1;
dict2[“b”] = 2;
JSON.stringify(dict1) === JSON.stringify(dict2); //> true
dict1['a'] = 2;
JSON.stringify(dict1) === JSON.stringify(dict2); //> false

Making A Deep Copy of Object

Once again the trick is to use JSON.stringify along with JSON.parse.

const makeDeepCopy = obj => {
  return JSON.parse(JSON.stringify(obj))
}

# Conversion Between Data Types

We can use functions to transform between these data types as depicted in the graph below:

Generating a Random Number

The following function returns a random number between min (inclusive) and max (exclusive):

function getRandomNumber(min, max) {
  return Math.random() * (max — min) + min;
}

If we want to generate a random integer between min (inclusive) and max (exclusive):

function getRandomInteger(min, max) {
  return Math.floor(Math.random() * (max — min)) + min;
}

Shortcuts

Initialize Array

let arr = Array(10);
console.log(arr); //> [ <10 empty items> ]

Find Max

const arr = [1, 2, 3];
Math.max(...arr)

There’s a few gotchas associated with Math.max. Consider if you have an array in which contains null or undefined:

console.log(Math.max(...[null, null])); //> 0
console.log(Math.max(...[null, 1])); //> 1
console.log(Math.max(...[undefined, undefined])); //> NaN
console.log(Math.max(...[undefined, null, 1])); //> NaN

Empty elements in the array is the same as undefined:

const foo = Array(3);
foo[0] = 2;
console.log(Math.max(...foo)) //> NaN

Generating a sequence

const indices = Array.from(Array(10).keys());
console.log(indices); //> (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Use Splice to insert into array

Let’s write a function that insert a new element into a sorted array. splice is very handy in this situation.

function insertIntoSorted(newItem, sortedItems) {
  let arr = sortedItems
  for(let i in arr) {
    let curr = arr[i];
    if(newItem<curr) {
      arr.splice(i, 0, newItem);
      return arr;
    }
}

Optional Parameter

ES6 shortcut using default value:

function foo(fruit='apple') {
  let toPrint = fruit
  console.log('word:', toPrint)
}

As opposed to the old way of doing it using ternary operator:

function foo(fruit) {
  let toPrint = fruit ? fruit : 'apple'
  console.log('word:', toPrint)
}

Quickly convert string to number

Prepending + to the string is a shorthand for converting the string to a number.

const [a, b, c] = [+'1', +'1.5', +'foo']
console.log(a); //> 1
console.log(b); //> 1.5
console.log(c); //> NaN

Different kinds of loop

Suppose we have the following data we want to loop through:

let colors = ['red', 'blue', 'green', 'purple', 'yellow'];

We could do a simple for-loop:

for(let i=0; i<colors.length; i++) {
  console.log(colors[i]);
}

There’s a less verbose way of achieving the same thing:

for(let i in colors) {
  console.log(colors[i]);
}

If we don’t are about the index but just the value, we could use forEach:

colors.forEach(color => {
  console.log(color)
});

For some algorithms, we may need to use the while-loop:

while(colors.length > 0) {
  let color = colors.shift();
  console.log(color);
}

Note, the while-loop operation above mutates the original array!

To loop through an object, we could do the following:

let keycodeMapping = {
  65: 'a',
  66: 'b',
  187: '=',
  191: '/'
};
Object.keys(keycodeMapping).forEach(key => {
  console.log('keycode, value:', key, keycodeMapping[key]);
});

More Study material for JavaScript interviews

  • Coding Challenges and Solutions — GitHub repo updated frequently with algorithm problems from Cracking the Coding Interview, Leetcode, and actual coding interviews.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Java vs. JavaScript: Know The Difference

Java vs. JavaScript: Know the Difference, Java vs. JavaScript: What's the Difference? Java vs. JavaScript: Major Similarities and Differences. pros and cons of JavaScript and Java.