
Overview
JavaScript object properties can be displayed according to name, within a loop, using Object.values(), or using JSON.stringify().
Displaying the Object Itself
HTML Code (where the result will be placed):
<p id="demo"></p>
JavaScript:
// object
const car = {
type: "Maserati",
model: "Quattroporte",
color: "white"
};
// display the object itself
document.getElementById("demo").innerHTML = car;
Displaying a JavaScript object will output [object Object].
[object Object]
Displaying the Object Properties
HTML Code (where the result will be placed):
<p id="demo"></p>
JavaScript:
// object
const car = {
type: "Maserati",
model: "Quattroporte",
color: "white"
};
// display the object properties as a string
document.getElementById("demo").innerHTML =
car.color + " " + car.type + " " + car.model;
Displaying the JavaScript object properties as a string.
white Maserati Quattroporte
Displaying the Object Properties Using a Loop
HTML Code (where the result will be placed):
<p id="demo"></p>
JavaScript:
// object
const car = {
type: "Maserati",
model: "Quattroporte",
color: "white"
};
// build the text from the properties
let text = "";
for (let x in car) {
text += person[x] + " ";
};
// display the object properties as a string
document.getElementById("demo").innerHTML = text;
Displaying the JavaScript object properties as a string.
Maserati Quattroporte white
Using JSON.stringify()
JavaScript objects can be converted to a string with the JSON method JSON.stringify(), which is included and supported in all browsers.
<p id="demo"></p>
JavaScript:
// object
const car = {
type: "Maserati",
model: "Quattroporte",
color: "white"
};
// convert object to JSON
let text = JSON.stringify(car);
// display the object properties as a string
document.getElementById("demo").innerHTML = text;
Displaying the JavaScript object properties in JSON format.
{"type":"Maserati","model":"Quattroporte","color":"white"}
JavaScript Notes:
- When using JavaScript, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
- JavaScript is a case-sensitive language; firstName is NOT the same as firstname
- JavaScript variables are case sensitive (x is not the same as X)
- Arrays count starting from zero NOT one; so item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on
- JavaScript variables must begin with a letter, $, or _
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.