I'am javascript beginner trying to code to improve myself, at the moment trying to learn 'template literals' and for some reason getting different answer by putting inside 'template literals'. Here is my code :
const foodArray = [
{ name: 'Burrito' },
{ name: 'Pizza' },
{ name: 'Burger' },
{ name: 'Pasta' }
];
for (let i = 0; i < foodArray.length; i++) {
console.log(`i value: ${i} | Food Name:`, foodArray[i]);
}
<p id="demo"></p>
so now i'm putting 'foodArray[i]' inside 'template literals' like this ' ${foodArray[i] ' but it is giving me '[object Object]', shouldn't it give same result ? maybe i'm doing something wrong here
const foodArray = [
{ name: 'Burrito' },
{ name: 'Pizza' },
{ name: 'Burger' },
{ name: 'Pasta' }
];
for (let i = 0; i < foodArray.length; i++) {
console.log(`i value: ${i} | Food Name: ${foodArray[i]}`);
}
<p id="demo"></p>
console.log
is going to do things differently than the template literal. the console.log
will send the actual object reference to the console client and the particular console client will decide from there how to present that object, they all do it slightly differently. template literals will always call the objects .toString()
method. some console clients just call the .toString()
method as well, some use JSON.stringify
, some use sophisticated object explorers, the SO console client uses some method to produce "pretty" JSON.
you can get it closer to the console representation or at least make it consistent by using JSON.stringify
:
console.log(`i value: ${i} | Food Name: ${JSON.stringify(foodArray[i])}`);
but generally, in real world programming, you won't be sending objects to a template literal, so this isn't a huge concern in most applications.