Functions can utilize push() to build arrays incrementally based on certain conditions or iterations.
function generateEvenNumbers(count) {
let evenNumbers = [];
for (let i = 0; i < count; i++) {
if (i % 2 === 0) {
evenNumbers.push(i);
}
}
return evenNumbers;
}
console.log(generateEvenNumbers(10)); // Output: [0, 2, 4, 6, 8]
In this example, the generateEvenNumbers() function generates an array of even numbers up to a specified count. It uses push() to add each even number to the array.
Stack Operations:
push() is often used in stack implementations. Stacks are data structures that follow the Last-In-First-Out (LIFO) principle. push() can add elements to the top of the stack.
let stack = [];
function pushToStack(item) {
stack.push(item);
}
function popFromStack() {
return stack.pop();
}
pushToStack('a');
pushToStack('b');
console.log(stack); // Output: ['a', 'b']
console.log(popFromStack()); // Output: 'b'
console.log(stack); // Output: ['a']
In this example,** pushToStack()** adds elements to the stack using push(), and popFromStack() removes elements from the stack using pop(), following the LIFO principle.
These are just a few examples of how the push() method can be used within functions in JavaScript to manipulate arrays. It's a versatile method that is commonly employed for array manipulation tasks.
Top comments (0)