push Returns Length, shift Returns Elements

push and unshift return the new length while pop, shift, and splice return removed elements — array mutator return values differ by design.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
const stack = [];

// push returns the NEW length, not the array
console.log('push returns:', stack.push('a'));
console.log('push returns:', stack.push('b', 'c'));

// pop returns the removed element (undefined when empty)
console.log('pop returns:', stack.pop());

// shift returns the first element; unshift returns the new length
console.log('shift returns:', stack.shift());
console.log('unshift returns:', stack.unshift('x', 'y'));

console.log('final array:', stack);

// splice returns the removed elements as a new array
const nums = [1, 2, 3, 4];
console.log('splice returns:', nums.splice(1, 2), 'left:', nums);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

push returns: 1
push returns: 3
pop returns: c
shift returns: a
unshift returns: 3
final array: [ 'x', 'y', 'b' ]
splice returns: [ 2, 3 ] left: [ 1, 4 ]

How it works

Demo state sits in top-level bindings: stack, nums.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Using it

The run emits 6 labeled sections — push returns:, pop returns:, shift returns:, unshift returns:, final array:, splice returns: — one per step.

The key statements, annotated

const nums = [1, 2, 3, 4];
const stack = [];

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `stack`, `nums`.