peek operation in stack using javascript
To check the topmost element unfortunately you must explicitly index it
var top = stack[stack.length-1];
the syntax stack[-1]
(that would work in Python) doesn't work: negative indexes are valid only as parameters to slice
call.
// The same as stack[stack.length-1], just slower and NOT idiomatic
var top = stack.slice(-1)[0];
To extract an element there is however pop
:
// Add two top-most elements of the stack
var a = stack.pop();
var b = stack.pop();
stack.push(a + b);
var stack = [];
stack.push("id1");
stack.push("id2");
console.log(stack[stack.length-1]); // the top element
console.log(stack.length); //size