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