Challenge - 5 Problems
Array Length Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
What is the output of this code?
Consider the following JavaScript code. What will be logged to the console?
Javascript
const arr = [1, 2, 3, 4]; arr.length = 2; console.log(arr.length, arr);
Attempts:
2 left
π‘ Hint
Changing the length property can truncate the array.
β Incorrect
Setting arr.length to 2 cuts off elements after index 1, so arr becomes [1, 2] and length is 2.
β Predict Output
intermediate2:00remaining
What is the output of this code?
What will this code print to the console?
Javascript
const arr = []; arr[3] = 'hello'; console.log(arr.length);
Attempts:
2 left
π‘ Hint
Array length is one more than the highest index.
β Incorrect
Assigning to index 3 sets length to 4 because length is highest index + 1.
β Predict Output
advanced2:00remaining
What is the output of this code?
What will this code output?
Javascript
const arr = [1, 2, 3]; arr.length = 5; console.log(arr[3], arr[4], arr.length);
Attempts:
2 left
π‘ Hint
Increasing length adds empty slots, but does not add values.
β Incorrect
Setting length to 5 adds empty slots at indexes 3 and 4, which are undefined.
β Predict Output
advanced2:00remaining
What error does this code raise?
What happens when this code runs?
Javascript
const arr = [1, 2, 3]; Object.defineProperty(arr, 'length', {writable: false}); arr.length = 1; console.log(arr.length);
Attempts:
2 left
π‘ Hint
Trying to change a non-writable property causes an error.
β Incorrect
Setting length when it is non-writable throws a TypeError in strict mode.
π§ Conceptual
expert2:00remaining
How many elements does this array have?
Given this code, how many elements does the array have?
Javascript
const arr = [,,]; console.log(arr.length);
Attempts:
2 left
π‘ Hint
Empty slots count towards length.
β Incorrect
The array has two empty slots, so length is 2.