Function is returning undefined but should be returning a matched object from array in JavaScript

38 Views Asked by At

I'm very new to JS. I'm trying to return a matched value from user input from a global array (aStoreItems) for a theoretical online book store. The array consists of objects passed through a constructor.

// Function to find object by ID value

function getBookById(id) {
            console.log("Variable being passed in(in getbookbyid function)= " + id)
            console.log(" type Variable being passed in(ingetbookbyid function)= " + typeof (id))
            for (var i = 0; i < aStoreItems.length; ++i) {
                if (aStoreItems[i].bID == id) {
                    return aStoreItems[i];
                    selectedBook = aStoreItems[i];
                }
            } 
};

// Sample of object in array

var ID23 = new StoreItem("ID23", "The Slow Regard of Silent Things", 12.99, 50, 1, "Fiction", 1.99, ["Great story", 5], "Desc", "<img src='./imgs/the_slow_regard_of_silent_things.jpeg' />");
        

Now I'm trying to implement an add to cart function that passes a user typed value and passes it through the getBookById() function.

Right now I'm just trying to pass the variable created by the users input to find the book that they want to add to cart

function addToCart() {
            var bookSelection = document.getElementById("pID").value;

            console.log("user typed (in add to cart function) " + bookSelection);

            getBookById(bookSelection);
            console.log("return is(in add to cart function) " + selectedBook);
};

console output shows this: user typed (in add to cart function) ID23 Variable being passed in(in get book by id function)= ID23 type Variable being passed in(in get book by id function)= string return is(in add to cart function) undefined

I don't know where I'm going wrong and other solutions researched are not fairing any better

Thanks to all for you help!

1

There are 1 best solutions below

2
trincot On BEST ANSWER

selectedBook = aStoreItems[i]; is never executed. It is dead code. When return is executed, the function exits and no other statements in that function are executed.

You should just not have that selectedBook variable. Instead use what the function returns at the calling side. So in the second part of your code do:

    const selectedBook = getBookById(bookSelection);
    console.log("return is(in add to cart function) " + selectedBook);

As a side note, this also defines selectedBook as a local variable, which is preferable over global variables.