Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to print each element of the array using a for loop.
DSA Javascript
const arr = [1, 2, 3, 4]; for (let i = 0; i [1] arr.length; i++) { console.log(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' causes an out-of-bounds error.
Using '>' or '>=' will not enter the loop.
✗ Incorrect
The loop should run while i is less than arr.length to avoid going out of bounds.
2fill in blank
mediumComplete the code to sum all elements in the array using a for...of loop.
DSA Javascript
const numbers = [5, 10, 15]; let sum = 0; for (const [1] of numbers) { sum += [1]; } console.log(sum);
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inside the loop body.
Using index variables which are not available in for...of loops.
✗ Incorrect
The variable name inside the for...of loop can be any valid identifier; here 'num' is used consistently.
3fill in blank
hardFix the error in the code to correctly print elements in reverse order.
DSA Javascript
const arr = [10, 20, 30]; for (let i = arr.length - 1; i [1] 0; i--) { console.log(arr[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' excludes the first element at index 0.
Using '<=' or '<' will not work for reverse traversal.
✗ Incorrect
The loop should continue while i is greater than or equal to 0 to include the first element.
4fill in blank
hardFill both blanks to create an array of squares for numbers greater than 3.
DSA Javascript
const numbers = [1, 2, 3, 4, 5]; const squares = numbers.filter(n => n [1] 3).map(n => n [2] 2); console.log(squares);
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' in filter returns wrong numbers.
Using '*' instead of '**' for exponentiation in map.
✗ Incorrect
Filter selects numbers greater than 3, then map squares them using '**' operator.
5fill in blank
hardFill all three blanks to create an object mapping each word to its length if length is more than 4.
DSA Javascript
const words = ['apple', 'bat', 'carrot', 'dog']; const result = {}; for (const word of words) { if (word.length [3] 4) { result[[1]] = [2]; } } console.log(result);
Attempts:
3 left
💡 Hint
Common Mistakes
Using word.toUpperCase() as key changes keys unexpectedly.
Using '<' in filter returns wrong words.
✗ Incorrect
The object keys are words, values are their lengths, filtered by length > 4.
