Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRobert Paauwe
2,077 PointsWhat's the difference between an object literal and JSON? When do you use which?
Hi all! Loving the course so far. I've seen that object literals appear similarly to JSON files. What's the difference? And how do you choose when to use which? :D
1 Answer
Joshua Ordehi
4,648 PointsHey Robert,
Happy to hear you're loving the course, best of lucks in your journey!
An Object literal is when you declare an Object in JavaScript code which is a variable that stores data in key-value pairs, while JSON stands for JavaScript Object Notation and it's a language-agnostic format for storing and transferring data that is based on JavaScript Objects.
You'd use Object literals in your code when you need to create an object such as a user profile so you can later read and write its properties, or when you're working with classes which is something you'll see later in the course.
JSON is used when you want to store data and transfer it across different platforms and programming languages. One easy way to spot JSON is that you'll see its property names are always inside quotation marks:
{
"firstName": "Robert",
"lastName": "Paauwe"
}
While Object literals don't use quotation marks for their property names:
let myObject = {
firstName: "Robert",
lastName: "Paauwe"
};
You'll often see JSON data stored as a separate file from JavaScript (.json) while Object literals appear right in JS code.
There's more on that here: https://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object And here: https://medium.com/@easyexpresssoft/object-literal-vs-json-7a2084872907
Robert Paauwe
2,077 PointsRobert Paauwe
2,077 PointsThanks for the clear explanation!