I’m working through a JavaScript exercise where I need to fill HTML table cells with random numbers. The cells have IDs like “cell0”, “cell1”, etc. My code works but I’m confused about two things:
window.onload = generateNumbers;
function generateNumbers() {
for(var j=0; j<24; j++){
fillCell( j )
}
function fillCell (cellIndex) {
var targetCell = "cell" + cellIndex;
var randomValue = Math.floor(Math.random()*75 )+1
document.getElementById(targetCell).innerHTML = randomValue;
}
}
First question: Why doesn’t JavaScript throw an error when fillCell is called before it’s defined in the code? I thought functions had to be declared before they could be used.
Second question: In the line var targetCell = "cell" + cellIndex;, I’m just creating a string by combining “cell” with a number. How does document.getElementById(targetCell) work if targetCell is just a variable containing a string? There’s no actual element with the ID “targetCell” in my HTML.
Yeah, these two things tripped me up when I first started with JavaScript too. For your first question - that’s called “hoisting.” JavaScript basically moves function declarations to the top of their scope when it compiles, so even though fillCell shows up after you call it in your code, it’s actually available throughout the entire generateNumbers function. Just heads up though - this only works with function declarations, not function expressions or arrow functions. For your second question - document.getElementById() expects a string that represents the ID you’re looking for. When you pass targetCell to it, JavaScript uses whatever value is stored in that variable (like “cell0” or “cell5”) instead of literally looking for an element called “targetCell.” It just searches the DOM for whatever string you give it, whether that’s from a variable or typed out directly. That’s why your concatenation approach works great for hitting different cells dynamically.
I had the same confusion when I started with JavaScript. Function declarations do get hoisted, but they still execute top-to-bottom. Your generateNumbers function won’t run fillCell until the loop actually runs - hoisting just makes the function definition available early. This can mess you up if you’re not watching your variable scoping.
For getElementById - think of it like this: JavaScript evaluates targetCell first. If cellIndex is 5, targetCell becomes “cell5” before it hits getElementById. The method doesn’t know you used string concatenation - it just gets “cell5” and looks for that ID. Pretty handy for working with multiple similar elements without copying code everywhere.
both concepts make sense once u get it. javascipt hoists functions, so u can call em anytime within their scope no matter where u put the function. for getElementById - it doesn’t matter if u use a string or variable. same outcome anyway.