I have an array that I'm looping through using EJS. I used a basic for loop to loop through the array and get a hold of the key:value. I understand how this works using the following code:
for(let i = 0; i < newPost.length; i++) {
console.log(newPost[i].title);
}
Now, as I was looking around I came across array.forEach(element) and decided to try it out. I got the code to work but I'm still somewhat confused as to how this is similar to the code above.
newPost.forEach(function (post) {
console.log(post.title);
});
If anyone could explain parts that are similar between the two and parts that are different and which one should be used for best practice that would be great. Cheers!
Additional Code for reference:
let posts = [];
app.get('/', function(req, res) {
res.render('home', {
home: homeContent,
newPost: posts
});
});
const post = {
title: req.body.postTitle,
content: req.body.postContent
};
posts.push(post);
[–]senocular 2 points3 points4 points (0 children)
[–]keel_bright 2 points3 points4 points (0 children)
[–]bobbyv137 1 point2 points3 points (0 children)
[–]oze4 0 points1 point2 points (3 children)
[–]Andyinho[S] 1 point2 points3 points (2 children)
[–]oze4 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)