1D0-735 practice question 10 of 15

Scarlet has the following code in her script: Var namesArr =[‘’Joseph’,’ Charlotte’’, ‘’Nicole’’]; She wants to add the name Hank to the end of the array so that its length is 4. What code should she use?

Full set: 55 questions
Answer options
A: namesArr [4] ''Hank'';
B: namesArr push (''Hank''); Correct answer
C: namesArr unshift (''Hank'');
D: namesArr .shift (''Hank'');
Correct Answer:
B. namesArr push (''Hank'');
Explanation

The push() method is the correct choice as it is specifically designed to add one or more elements to the end of an array. In this scenario, namesArr.push('Hank') will append the string 'Hank' to the namesArr array, modifying it in place. The original array ['Joseph', 'Charlotte', 'Nicole'] will become ['Joseph', 'Charlotte', 'Nicole', 'Hank'], and its length property will be updated from 3 to 4, fulfilling all requirements of the question.

Why Incorrect

A. namesArr [4] ''Hank''; is syntactically incorrect. Even if corrected to namesArr[3] = 'Hank';, using the push() method is the more standard and idiomatic approach for appending elements.
C. namesArr unshift (''Hank''); is incorrect because the unshift() method adds elements to the beginning of an array, not the end.
D. namesArr .shift (''Hank''); is incorrect. The shift() method removes the first element from an array and does not accept arguments to add an element.

References

1. MDN Web Docs (Mozilla): The Array.prototype.push() documentation explicitly states, "The push() method adds one or more elements to the end of an array and returns the new length of the array."

Source: Mozilla, Array.prototype.push(), MDN Web Docs, last modified Oct 2, 2023. Available at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/Array/push

2. MDN Web Docs (Mozilla): The documentation for Array.prototype.unshift() and Array.prototype.shift() confirms their incorrectness for this scenario. unshift() adds to the start, and shift() removes from the start.

Source: Mozilla, Array.prototype.unshift(), MDN Web Docs, last modified Oct 2, 2023. Available at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/Array/unshift

Source: Mozilla, Array.prototype.shift(), MDN Web Docs, last modified Oct 2, 2023. Available at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/Array/shift

3. University of Washington, CSE 154 Courseware: Course materials on JavaScript arrays describe push as the method for adding to the back of an array, contrasting it with unshift for adding to the front.

Source: University of Washington, CSE 154: Web Programming, Lecture 08: JavaScript Arrays, Section: "Adding/Removing from an Array". Available at: https://courses.cs.washington.edu/courses/cse154/19sp/lectures/08/lecture08-js-arrays.pdf (Page 21)

Scroll to Top