0

I am trying to create a function that returns true or false depending on the condition, but for some reason, It doesn't return true or false, and when I am trying to print what the function returned it says "undefined". What am I doing wrong? I will appreciate any help!

function get_likes(post_id) {
    fetch(`posts/${post_id}`).then(response => response.json()).then(post => {
        let user = JSON.parse(document.getElementById('user_id')
            .textContent);
        if (post.likes.includes(user)) {
            return true;
        } else {
            return false;
        }
    })
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Maya Twik
  • 27
  • 6
  • 1
    Any function which has no `return` statement, such as `get_likes` will return `undefined` (unless it uses the `async` keyword, in which case it will return `undefined` wrapped in a Promise). – Quentin May 11 '23 at 11:04
  • Use a code formatter, I've applied one to your code and edited it into the question; sensible whitespace helps you spot when `return` statements belong to nested functions. – Quentin May 11 '23 at 11:06
  • Note that `Array.prototype.includes` returns a boolean, so you can just use its value directly instead of wrapping it in `if/else`. – Quentin May 11 '23 at 11:07

0 Answers0