Back to Explore
GuideVibeFix editorialUpdated Nov 20, 2026

Put the data in a labeled box first: objects and JSON, explained plainly

One order is one object: table, dishes, total, paid — all filed by label. This guide follows MDN's Working with objects, JSON, and Object references: object literals, dot vs bracket notation, adding and deleting properties, for...in with hasOwn, methods and this, getters and setters, references vs copies, Object.assign and friends, null-prototype objects, JSON's strict rules, and stringify and parse with their number-precision trap.

Real photo: top-down view of hands sorting handwritten index cards on a dark desk, with clipboards holding tables beside them

First, the boundaries. The site already has several JavaScript basics guides: array methods, destructuring, Map and Set, Promise and async/await, try/catch, DOM querying and traversal, module import/export, and localStorage. This guide covers none of them. It covers one thing: how data goes into an object, and how it becomes a JSON string to hand over. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. Earlier guides covered how its order page works, how its code is split into modules, and how it draws charts. This one is about the data itself: one order is one object, holding the menu, the table number, the dishes, the total, and whether it is paid; to store an order or send it to someone else, it first has to become JSON. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about objects and JSON syntax and behavior comes from three MDN pages — “Working with objects”, “JSON”, and “Object”. The sources are listed in this article's meta information and evidence record. The examples in the docs — the myHonda car, the Car constructor, the myCar Ford Mustang, the manager and the intern saying hello, the myObj getter and setter, the two fruits with the same name, the ages lookup — are the docs' own examples, not real services. This guide does not cover the full class syntax, the deep details of the prototype chain, or Proxy — only the most-used object set: how to write, read, change, walk through, and turn objects into JSON and back. By the end you should be able to do four things: pack a bundle of related data into an object, tell dot notation from bracket notation and when each applies, know that a reference is not a copy, and know where JSON differs from a JavaScript object literal.

Step 1: An object is a box with labels on it — start with the literal

JavaScript has two main ways to hold data: arrays line things up in order, and objects file things away by label. MDN's “Working with objects” opens with the first way to make an object: the object initializer, usually called an object literal — curly braces holding “name: value” pairs separated by commas: const myHonda = { color: "red", wheels: 4, engine: { cylinders: 4, size: 2.2 } };. A property name can be an identifier, a number, or a string, and a value can be any expression; a property name can also be an expression, but a computed key has to be wrapped in square brackets. A literal produces a new object every time it runs, and two identical-looking object literals are never equal to each other. MDN's myHonda example carries one more point: a property's value can itself be an object — engine is an object with cylinders and size inside it, a box inside a box. The cafe's order object is written the same way: const order = { id: "A12", table: 3, items: [{ name: "Latte", price: 28 }, { name: "Croissant", price: 18 }], total: 46, paid: false };, one order with five properties: the table number is a number, the total is a number, paid is a Boolean, and the dishes are an array in which each dish is itself a small object. Besides literals, MDN covers two more ways to make objects: write a constructor function first and call it with new, for example function Car(make, model, year) { this.make = make; this.model = model; this.year = year; }, then const myCar = new Car("Eagle", "Talon TSi", 1993); and Object.create(), which builds a new object with a prototype you choose, without writing a constructor first. Each way has its place; this guide's main line uses literals, because for the job of gathering a bundle of data on the fly, a literal is the handiest. The rule to remember: an object is a box filed by labels, a property is a “name: value” pair; a literal makes a new object every time it runs, and two that look alike are still not equal.

Step 2: Dot versus brackets — whether the name is legal decides

With the object made, the next step is reading and writing its properties. MDN's “Working with objects” gives two syntaxes: dot notation and bracket notation. myCar.make and myCar["make"] both read "Ford"; assignment works the same way, myCar.make = "Ford" and myCar["make"] = "Ford" having the same effect. Which one to use follows a clear rule from MDN: if the property name is a valid JavaScript identifier, dot notation works; if the name has a space, a hyphen, starts with a number, or lives inside a variable, only bracket notation works. MDN's example makes the rule concrete: myObj["date created"] has a space in its key, so dot notation cannot spell it; in myObj[str], str is a variable holding the string "myString", and what you read is myObj.myString; write myObj.str instead and you read the property literally named str, which comes back undefined. A variable as a key is the most common use of brackets: let propertyName = "make"; myCar[propertyName] = "Ford";, and changing propertyName lets you read and write different properties — dot notation cannot do that. Two more rules are easy to trip over. First, property names are only strings or Symbols — anything else gets converted to a string: in MDN's example, using an object anotherObj as a key calls its toString() method, so the key becomes "[object Object]"; using a random number as a key makes it the string "0.6398914448618778". Second, a property that does not exist reads as undefined, not null: myCar.nonexistentProperty is undefined. MDN adds one warning: beware of using square brackets to access properties whose names come from external input, since that can leave code open to object injection attacks — do not take a string a user typed and use it straight as a key. The rule to remember: a legal name takes a dot, an illegal name or a name held in a variable takes brackets; a variable used as a key goes inside brackets, while whatever follows a dot is always the literal name.

Step 3: Add, delete, change, check — objects are alive

An object is not frozen once made; properties can be added, changed, and deleted at any time. MDN's “Working with objects” says it plainly: assigning to a property that does not exist adds it, and assigning to one that exists changes it. car1.color = "black" adds a color property to car1 with the value "black", and no other Car object is affected; to give every Car object the property, change the Car definition itself. Deleting uses the delete operator: const myObj = { a: 5, b: 12 }; delete myObj.a;, and afterward myObj has only the b property, and "a" in myObj is false. Note that delete only removes an object's own properties; inherited ones cannot be deleted this way, a point step 8 returns to. Checking whether a property exists has two ways: the in operator and Object.hasOwn(). In MDN's example, "a" in myObj is true before the delete and false after it. The difference matters: in walks up the prototype chain, so an inherited property counts; Object.hasOwn() looks only at the object's own properties, and inherited ones do not count. The cafe's order object is maintained exactly this way: when a guest adds a dish, a new object is pushed into order.items and order.total is recomputed; when a dish is taken off, that item is removed and the total follows; to find out whether the order has a discount, Object.hasOwn(order, "discount") checks — present means discounted, absent means not. The rule to remember: assignment adds or changes, delete deletes; check existence with in or Object.hasOwn(), and only the latter looks at the object's own properties.

Step 4: Walking through properties — three ways, and do not count inherited ones

Once an object holds many properties, you need to walk through them. MDN's “Working with objects” lists three native ways: for...in loops, Object.keys(), and Object.getOwnPropertyNames(). A for...in loop traverses all enumerable string properties of an object as well as its prototype chain; Object.keys() returns an array holding only the object's own enumerable string property names, not those in the prototype chain; Object.getOwnPropertyNames() returns all of the object's own string property names, enumerable or not. MDN's showProps function is the model for for...in: for (const i in obj) { if (Object.hasOwn(obj, i)) { result += `${objName}.${i} = ${obj[i]}\n`; } }, with Object.hasOwn() inside the loop to keep prototype-chain properties out and print only the object's own. MDN also gives the equivalent Object.keys() version: Object.keys(obj).forEach((i) => { result += `${objName}.${i} = ${obj[i]}\n`; }), same result, straighter spelling. The cafe's “print receipt” feature works this way: Object.keys(order) lists each property name of the order, then each value is read in turn to build the receipt; Object.values(order) fetches the values, and Object.entries(order) fetches [key, value] pairs together. The easiest mistake in walking an object is a for...in without hasOwn(): prototype-chain properties get counted too, and the receipt gains lines that do not belong to this order. The rule to remember: for...in walks the prototype chain, so pair it with Object.hasOwn(); Object.keys() gives only the object's own enumerable keys; Object.values() fetches values, Object.entries() fetches keys and values together.

Step 5: A method is a function hanging off an object, and this is the object before the dot

A property's value can be anything, including a function. A property whose value is a function is called a method. MDN's “Working with objects” defines it plainly: a method is a function associated with an object — put differently, a method is a property of an object that is a function. There are two ways to write one: define an ordinary function first and assign it to the object's property, objectName.methodName = functionName; or write it straight in the literal with the shorthand, myOtherMethod(params) { }. The this inside a method is the key player: MDN's manager and intern example makes this clear — two objects each with their own name, age, and job, and the same sayHi function attached to both; manager.sayHi() prints "Hello, my name is Karina", and intern.sayHi() prints "Hello, my name is Tyrone". The same function, attached to whoever, and this is whoever it is attached to. MDN's own words are that this is a “hidden parameter” of a function call, passed in by specifying the object before the function that was called; in manager.sayHi(), this is the manager object, because manager comes before sayHi, and calling the same function from another object changes this as well. Methods are usually not written out per object; they are defined on the constructor's prototype object so all objects of the same type share them: Car.prototype.displayCar = function () { const result = `A Beautiful ${this.year} ${this.make} ${this.model}`; console.log(result); };, and then car1.displayCar() and car2.displayCar() each print their own year, make, and model. The cafe's order object has a total() method that adds up the price of every dish in items, and a summary() method that builds one line reading “Table 3, 2 dishes, 46 yuan total”. Both methods read their own properties through this, and the same pair of methods works again on the next order. The rule to remember: a method is a property whose value is a function; this is the object before the dot, and calling from another object moves this along with it.

Step 6: Getters and setters — do a little math on the way in and out

Sometimes a property's value is not stored but worked out. MDN's “Working with objects” covers getters and setters for exactly that: a getter is a function that runs when a property is read, and a setter is a function that runs when a property is written; together they can indirectly represent the value of a property. Inside an object literal, prefix the method with get or set: const myObj = { a: 7, get b() { return this.a + 1; }, set c(x) { this.a = x / 2; } };. Reading myObj.b runs get b() and returns a + 1, which is 8; writing myObj.c = 50 runs set c(x) and sets a to 50 / 2, which is 25. A getter must not expect a parameter, and a setter expects exactly one — the new value coming in. MDN also covers a second spelling: after the object exists, add getters and setters with Object.defineProperties(), whose first parameter is the object to add to and whose second is an object describing the getter and setter functions. Both spellings do the same thing, and the choice depends on the situation: if you know at creation time, write them in the literal — the most compact and natural form; if the object came from someone else and you only think of it later, Object.defineProperties() is the only possible form. The cafe's order object uses a getter: total is not stored but added up from the price of every dish in items whenever it is read, so when items change, total follows without being rewritten by hand; it also uses a setter: writing a discount in automatically recomputes total at the discounted rate. The rule to remember: a getter computes on read, a setter computes on write; write get and set in the literal, or add them later with Object.defineProperties().

Step 7: A reference is not a copy — changing the “copy” changes the original

The easiest place to fall over with objects is the reference. MDN's “Working with objects” states it directly: in JavaScript, objects are a reference type; two distinct objects are never equal, even if they have the same properties; only comparing the same object reference with itself yields true. MDN's example is plain: const fruit = { name: "apple" }; const anotherFruit = { name: "apple" };, and fruit == anotherFruit is false and fruit === anotherFruit is false, because these are two distinct objects; but with const anotherFruit = fruit;, anotherFruit is just another name for the same object, fruit == anotherFruit is true, and after fruit.name = "grape", anotherFruit reads { name: "grape" } as well. That is what “assignment passes a reference, not a copy” means: assigning an object to another variable only adds one more name pointing at the same object, and changing one place changes both. The cafe order page has tripped on this: to keep a “before changes” copy of an order, someone wrote const backup = order;, and when the waiter changed dishes on order, backup changed along with it and the backup was worthless. The fix is to really copy it: Object.assign({}, order) copies order's property values into a new object, or use the spread syntax { ...order }; change the copy afterward and the backup stays put. But stay alert: Object.assign copies property values, so when a property's value is itself an object, what gets copied is still the reference, and the nested layer stays shared. The rule to remember: assigning an object passes a reference; to keep a backup, really copy it — and remember the nested layer is still shared.

Step 8: The Object toolbox — and the spellings to stop using

Most of the tools for working with objects hang off the Object global object. MDN's “Object” reference page lists a long run of static methods; here are the ones the order page uses most. Object.keys(), Object.values(), and Object.entries() were covered in step 4: fetch keys, fetch values, fetch key-value pairs. Object.fromEntries() is the reverse of Object.entries(): give it a run of [key, value] pairs and it builds an object back. Object.assign() copies the values of all enumerable own properties from one or more source objects to a target object — the backup in step 7 is built with it. Object.create() makes a new object with a prototype you specify; MDN's “Working with objects” animal example does exactly this, starting from an animalProto holding a type and a displayType method, then Object.create(animalProto) makes animal and fish, fish changing type to "Fishes", each calling displayType() to print its own type. Object.create(null) makes an object with a “null prototype”, and MDN's “Object” page explains what that is good for: an ordinary object inherits a pile of methods from Object.prototype, and using an object as a dictionary can collide with them — with ages = { alice: 18, bob: 27 }, hasPerson("hasOwnProperty") comes back true and getAge("toString") returns a function; with a null-prototype object from Object.create(null), hasPerson("hasOwnProperty") is false and getAge("toString") is undefined, and the collision hazard is gone. Three more methods govern whether an object can change: Object.freeze() freezes an object so other code cannot delete or change its properties; Object.seal() stops properties from being deleted; Object.preventExtensions() stops new properties from being added. Finally, two “stop using these” notes: __proto__ is deprecated — use Object.getPrototypeOf() to read a prototype and Object.setPrototypeOf() to change one; and do not call obj.hasOwnProperty() directly any more, use the static Object.hasOwn(), because the object itself may carry an own property of the same name that covers the original method. The rule to remember: keys, values, entries, and fromEntries are one set; assign copies property values; create(null) makes a null-prototype dictionary; __proto__ and hasOwnProperty() are the old spellings — stop using them.

Step 9: JSON is not JavaScript — learn the differences one by one

Objects covered, the next step is JSON. MDN's “JSON” reference page opens by saying what JSON is: a syntax for serializing objects, arrays, numbers, strings, booleans, and null; it is based upon JavaScript syntax, but is distinct from JavaScript — most of JavaScript is not JSON. Where it differs, MDN lists several hard rules. First, property names must be double-quoted strings. Second, trailing commas are forbidden. Third, numbers cannot have leading zeros, a decimal point must be followed by at least one digit, and NaN and Infinity are unsupported. Fourth, JSON has no undefined and no comments. So the following is a legal JavaScript object literal but not legal JSON: { name: 'Latte', price: 28, } — single quotes fail, the trailing comma fails, and an unquoted key fails. Legal JSON looks like this: { "name": "Latte", "price": 28 }, keys and string values in double quotes, no trailing comma. MDN also records a piece of history: any JSON text is a valid JavaScript expression, but only after the JSON superset revision; before it, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR were allowed in JSON string literals and property keys, while the same use in JavaScript string literals was a SyntaxError. The J in JSON stands for JavaScript, but it only borrows JavaScript's looks — its rules are stricter. The cafe's order goes to the kitchen printer as a JSON string; the object literal the order page itself uses may leave keys unquoted, hold functions as values, and carry comments, but before it goes out it has to pass the JSON test. The rule to remember: JSON keys must be double-quoted, no trailing commas, no undefined, no comments, no NaN or Infinity; looking like JavaScript is not the same as being JavaScript.

Step 10: stringify and parse — swapping objects and strings back and forth

Swapping between objects and JSON strings rests on two static methods of the JSON object. MDN's “JSON” page is clear about the setup: unlike most global objects, JSON is not a constructor — you cannot use it with the new operator or invoke the JSON object as a function; all of its properties and methods are static, just like the Math object. JSON.stringify() returns a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner. JSON.parse() parses a piece of string text as JSON, optionally transforming the produced value and its properties, and returns the value. MDN's example is a JSON text holding Firefox browser data: first a string describing the browser, then JSON.parse(jsonText) turns it back into a JavaScript object. The cafe's order is stored the same way: the order object first goes through JSON.stringify(order) to become a string and is stored in localStorage; next time the page opens, JSON.parse() turns it back into an object to carry on with. Stringify before storing, parse after fetching — that line comes from the localStorage guide and is only borrowed here, not expanded. Each method has one pitfall to remember. The first is number precision: JSON can contain number literals of arbitrary precision, but JavaScript numbers are fixed-precision floating point; MDN's example is 12345678901234567890, which in JavaScript has the same floating point representation as 12345678901234567000, so JSON.parse("12345678901234567890") reads back as 12345678901234568000, and by the time a reviver function sees the value it is already rounded; to keep precision, either pass the big number as a string, use JSON.rawJSON() to keep it as a number in the JSON, or re-parse it yourself from context.source inside the reviver. The second pitfall is BigInt: MDN's example is a gross_gdp of 12345678901234567890n, which stringify would lose precision on; the fix is to give BigInt a toJSON method that turns it into a string, or return JSON.rawJSON(value.toString()) from the replacer so it stays a number in the JSON. The rule to remember: stringify turns an object into a string, parse turns a string back into an object; decide how big numbers and BigInt keep their precision before you start.

Step 11: Counting the mistakes — six ways to go wrong cover everything

Ten steps covered the techniques; this step counts the most common mistakes. The Greenstone Cafe order page is a fictional practice project, and the numbers below are invented examples matched against the pitfalls in the ten steps above — they are not statistics from any real project. In one month of object and JSON work on the order page, things went wrong 158 times, in six ways. Single quotes, trailing commas, or unquoted keys inside JSON: 40 times, 25.3%. JSON.parse called without try/catch, so bad data blew up the page: 32 times, 20.3%. Changing a “copy” that was really the original, so the backup changed along with it: 28 times, 17.7%. Mixing up dot and bracket notation, so a variable name was used as a property name: 24 times, 15.2%. The in operator treating an inherited property as an own property: 22 times, 13.9%. Big-number precision lost without anyone noticing: 12 times, 7.6%. 40 + 32 + 28 + 24 + 22 + 12 = 158, and 25.3 + 20.3 + 17.7 + 15.2 + 13.9 + 7.6 = 100.0%, so the books balance. The top two are JSON rules not remembered, the middle three are object basics not yet practiced, and the last one is the quiet precision trap.

Bar chart of the causes behind 158 object and JSON mistakes in one month

When you read this chart, do not just look at the longest bar — look at which earlier step each bar belongs to. Single quotes and trailing commas are the step 9 pitfall, parse without try/catch is step 10, changing a copy is step 7, mixing up dot and brackets is step 2, in counting wrong is step 3, and big-number precision is step 10. A mistake is not scary; not knowing which step it came from is. Trace the bar back to its step and the fix gets fast.

Step 12: Two traps and a checklist — run through it before shipping object code

Last come the two traps most likely to bite in a real project. The first is the chain reaction from “keys are strings”: property names are only strings or Symbols, number keys get converted to strings, an object used as a key becomes "[object Object]", and a string typed by a user and used straight as a key can open the door to object injection attacks. Step 2 already covered MDN's example: the key of myObj[anotherObj] ends up as "[object Object]", not the object itself. When writing code, think about where each key comes from — written by hand, held in a variable, or typed by a user — three sources, three spellings, and do not mix them. The second trap is that JSON.parse must always sit inside try/catch: parse throws on a string that is not JSON, and the try/catch guide already covered how to catch it; the point here is simply that any string arriving from outside gets a try/catch around its parse, and a failed parse falls back to spare logic instead of taking the whole page down. Before shipping object and JSON code, run this checklist: one, does every property name in the literal match its value, and are all nested objects closed with braces; two, is everything after a dot a legal identifier, with everything else switched to brackets; three, when a variable is the key, did you write obj[key] and not obj.key; four, was adding a property deliberate, and did delete remove only an own property; five, does the for...in loop carry Object.hasOwn(); six, does this inside a method mean the object before the dot; seven, when keeping a backup, did you really copy it, and is the nested layer still shared; eight, in the JSON going out, are all keys double-quoted and all trailing commas gone; nine, is parsing an outside string wrapped in try/catch; ten, have big numbers and BigInt got a plan for keeping precision. Pass all ten, then look at the result. Plenty is left unexpanded here: the full class syntax, the deeper details of the prototype chain, property descriptors with Object.defineProperty, the special behavior of Symbol keys, structured cloning and deep copies, and more forgiving formats such as JSON5 and YAML — MDN has a dedicated page for each, and the next guide will take them up one by one.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: a woman in an office sticking colorful sticky notes in rows on a white wall, holding a pink note in her hand
Guide
Stop shimming with margins: Flexbox one-dimensional layout, explained plainly

Flexbox lays things out in one direction at a time, and when it is done right, the nav bar, the card wall, and the cart rows all behave. This guide follows MDN's Basic concepts of flexbox, Aligning items in a flex container, and Controlling ratios of flex items along the main axis: the two axes, containers and items, direction and wrapping, free space, the three flex properties, alignment on both axes, and gaps and auto margins.

Developer WorkflowFrontend EngineeringAI Coding
Real photo: hands typing on a MacBook Pro showing JavaScript code that changes HTML content, with a white mouse, papers, and binders on a white desk
Guide
Functions without the confusion: JavaScript functions, parameters, and arrow functions, explained plainly

You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.

Tool TipsFrontend EngineeringAI Coding
Real photo: a laptop, tablet, and phone on a wooden table showing the same green-leaf website, the phone view with navigation in one column, a potted plant nearby
Guide
Squashed on phones? Responsive layout and media queries, explained plainly

One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.

Mobile AppsDesign ExperienceFrontend Engineering