Sometimes the hardest part of programming is not writing code, but understanding what needs to be done. In this exercise, your task is to think through the problem before coding.
Problem:
Given a sentence, return the longest word.
Before writing any code, do the following:
For example:
findLongestWord("I love programming")// returns "programming"
findLongestWord("Hi there")// returns "there"
findLongestWord("")// what should this return?
Sometimes data is already sorted, and checking every value one by one is not the best approach. In this exercise, you will learn about binary search and use it to solve a problem efficiently.
Problem:
Given a sorted array of numbers and a target value, return the index of the target using binary search. If the value does not exist, return -1.
Before writing the solution, make sure you understand how binary search works. You can explore this by searching on Google or YouTube for explanations and visual examples, and then apply what you learn to solve the problem.
For example:
binarySearch([1,3,5,7,9],5)// returns 2
binarySearch([1,3,5,7,9],1)// returns 0
binarySearch([1,3,5,7,9],9)// returns 4
binarySearch([1,3,5,7,9],4)// returns -1
Think about:
When writing code, it’s important to understand how the amount of work changes as the data grows. Look at the code snippets below and think about how many operations happen when the array becomes larger.
For each snippet, answer:
// A
const firstItem = arr[0];
// B
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// C
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
console.log(i, j);
}
}
Think about what happens if the array has:
It’s important to understand what your code is doing step by step. Look at the function below, which calculates the sum of numbers in an array.
function sum(numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
Add console.log statements to:
total after each additionRun the function with different inputs and carefully observe the output.
The function below is meant to return the result of multiplying all numbers in an array, but it contains a bug.
function multiply(numbers) {
let result = 1;
for (let i = 0; i <= numbers.length; i++) {
result *= numbers[i];
}
return result;
}
Find the issue and fix it.
Test your solution with different arrays to make sure it works correctly.
Sometimes code looks correct, but testing reveals problems. Look at the function below:
function isEven(number) {
return number % 2 === 0;
}
Write test cases by describing:
Include test cases for:
Think about how this function should behave in each situation.

Found a mistake or have a suggestion? Let us know in the feedback form.