Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Push input value to array - JavaScript


The Array.push() method is very useful for a database-like structure, where things are being updated all the time and the UI have to reflect the changes happening behind.

For instance, in the comment section on a popular website like YouTube, comments keep coming in by the minute, these comments are saved on the cloud in an array-like structure. The database could contain an array of comments like this:

Note that it has to be first handled behind the scenes before it is displayed on the scene as that is a good practice as opposed to just rendering your comment on your screen. If comments are not routed from behind-the-screen to on-the-screen, there wouldn't be a way to keep track across users and all times. This means that you could post a comment on your device and it will show on your device, but will not be displayed on the other person's device or at other times, because comments are fetched from the database, but your comment did not get pushed to the database (the behind-the-scene).


Then whenever a user writes in a new comment and clicks the 'Post comment' button, the value of the input field where the comment was written is saved to a variable and then sent to the database and a function is run featuring the Array.push() method:

The comments array is updated and a new array is returned reflecting the change. Like so:

The Array.push() method is very simple to understand. I have created a simple pen here and a better pen here, but here is a demo for faster understanding:


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.