Question on the printing those products exercise in the JavaScript Arrays tutorial

I have a question regarding the printing those products exercise in the JavaScript array tutorial JavaScript Arrays tutorial. In the starting code and solution code provided, itemText was used but never declared with let or var. I am confused. Isn’t it a variable? If it is, how come the code works when the variable is used without ever being created first?

The solution code looks like this:

const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';

let products = ['Underpants:6.99',
 'Socks:5.99',
 'T-shirt:14.99',
 'Trousers:31.99',
 'Shoes:23.99'];

for(let i = 0; i < products.length; i++) {
 let subArray = products[i].split(':');
 let name = subArray[0];
 let price = Number(subArray[1]);
 total += price;
 itemText = name + ' — $' + price;

 let listItem = document.createElement('li');
 listItem.textContent = itemText;
 list.appendChild(listItem);
}

totalBox.textContent = 'Total: $' + total.toFixed(2);

As you can see, itemText appeared in this line:

 itemText = name + ' — $' + price;

but was never declared with let or var

@saralin10co that’s a mistake - it should have been declared with let (or const still would have worked…)

It still works, but when you initialize variables with no var or let keyword, they automatically become globals, which may cause unexpected/wrong results. So it’s a best practice to always use them.

I’ve fixed this now; thanks for pointing it out!

I’ve got a follow-up question. listItem didn’t appear in a function, so even if we did use let or var to declare it first, wouldn’t it still be a global variable?

Yes, correct. The difference is only observed with variables initialized inside function scopes.

1 Like

Oh so in this case, it actually makes no difference then. Thanks!