29.
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
JavaScript: Appending Element to the Array**
let arr = [1, 2, 3];
// complete the missing Javascript code on this line
console.log(arr); // outputs [1, 2, 3, 4]
Pick ONE option
Show answer & explanation
Answer: B. `arr[arr.length] = value`
In JavaScript, array indices are zero-based and contiguous. To append a new element, assign it to the index equal to the current array length. Since arr = [1, 2, 3] has length 3, arr[3] = 4 correctly adds 4 at the next valid position. Option A would skip an index (creating a sparse array), C overwrites the last element, and D attempts string concatenation rather than array manipulation.
Step-by-step Derivation:
Step-by-step:
- Initial array:
arr = [1, 2, 3]with indices [0, 1, 2] - Array length:
arr.length = 3 - To append, use the next valid index:
arr[arr.length] = arr[3] = 4 - Result:
arr = [1, 2, 3, 4]✓
Why other options fail:
- Option A:
arr[arr.length + 1]=arr[4]creates a sparse array [1, 2, 3, undefined, 4] - Option C:
arr[arr.length - 1]=arr[2]overwrites the last element, resulting in [1, 2, 4] - Option D:
arr + valueperforms string concatenation, not array append