JavaScript ReferenceError: Function Not Found Despite Being Declared

I’m having trouble with a JavaScript function that seems to be defined but throws a reference error when called. I have a script in my page header with this function:

function updateProductInfo() {
    document.getElementById("product_title").innerHTML = productTitle;
    document.getElementById("product_desc").innerHTML = productDescription; 
    document.getElementById('product_img').src = productImage;
    document.getElementById('product_link').href = productURL + trackingCode;
}

console.log("Product script loaded");

Later in the page body, after the HTML elements are rendered, I try to call this function:

<img id="product_img" src="" class="thumbnail" style="max-width: 120px;">
<h2 id="product_title">Default Title</h2>
<div id="product_desc">Default description</div>
<a id="product_link" href="" target="_blank" class="button">View Product</a>

<script>
updateProductInfo();
</script>

But I keep getting an “Uncaught ReferenceError” saying the function is not defined. The weird thing is that the console.log message appears, which means the script file is loading correctly. If the console shows the log message, shouldn’t that mean the function above it is properly defined? What am I missing here?

This sounds like a timing issue, not a scope problem. The console.log runs when the script loads, but that doesn’t mean the function is accessible everywhere. If your header script is wrapped in a DOMContentLoaded listener or another function, updateProductInfo won’t be in global scope. Could also be a JavaScript error happening between the function declaration and console.log that’s stopping the function from registering properly. Check your browser’s dev console for syntax errors or exceptions that might be failing silently before the log message. You can test by calling the function directly in the same script block where it’s defined to see if it works there.

Had this exact issue last month - turned out to be a parsing error. Console.log will still show up even when JavaScript fails to register your functions due to syntax errors. The engine skips function declarations when it hits malformed code but keeps running standalone statements like console.log. Check if your variables (productTitle, productDescription, productImage, productURL, trackingCode) are actually defined before your function declaration. If they’re undefined or declared after the function, your whole script block can act weird. Wrap your function call in a try-catch to get a better error message than just the reference error.

yea, could be a scope issue. might be inside a block or something so it’s not global, making it uncallable later. try adding it to the window like this: window.updateProductInfo = function() for it to work.