xSKILLby Infirals
Register

JavaScript for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Objects and arrays

Objects, arrays and data15 min readLesson 1 of 4

1.1 Objects hold named values

An object groups related values under keys. Each key is a string or a symbol, and each value can be anything: a number, a string, an array, another object or a function. Objects describe one thing, such as a user with a name, a city and a score.

An object literal writes the pairs inside braces. Commas separate entries, and the last comma is optional. Property names that are valid identifiers can be written without quotes; keys with spaces or odd characters need quotes.

javascript
const user = {
  name: "Aarav",
  city: "Delhi",
  greet() {
    return `Hi, ${this.name}`;
  },
};

console.log(user.name);
console.log(user["city"]);
console.log(user.greet());

Output

Aarav
Delhi
Hi, Aarav

Dot access reads a property by its identifier, and bracket access takes a string expression. Dot access is shorter and clearer when the key is fixed. Bracket access is required when the key is stored in a variable, comes from user input, or contains characters a dot cannot handle.

Writing to a missing key creates it. Reading a missing key returns undefined, which is easy to confuse with a key whose value is undefined. Use the in operator or Object.hasOwn when the difference matters, and a default when the value may be absent.

1.2 Methods and this

A function stored on an object is a method. Inside a method written with the method shorthand, this refers to the object, so this.name reads the property on the same object. That only works when the method is called through the object, as in user.greet().

Detaching a method loses the connection. const greet = user.greet; greet(); calls the function with no object, so this is undefined in strict mode and the property read throws. Pass a wrapper arrow function when a callback needs to call the method with the object attached.

1.3 Nested objects

Objects nest naturally. A user can have an address object, and the address can have a city and a postcode. Reading a nested path means following each key in turn, and a missing middle link throws unless the chain is guarded.

Optional chaining is the compact guard: user.address?.city returns undefined when address is missing. It is useful at the edge of the program where data arrives, and it should not hide a property that the code expects to exist later.

javascript
const profile = {
  name: "Meera",
  address: { city: "Chennai", pin: "600001" },
};

console.log(profile.address.city);
console.log(profile.contact?.email);
console.log(profile.contact);

Output

Chennai
undefined
undefined

1.4 Arrays hold ordered values

An array is an ordered list. Each item has a numeric index starting at zero, and the length property reports how many items the array holds. Arrays can contain any mix of values, though homogeneous arrays are easier to process.

Add to the end with push, remove from the end with pop, add to the front with unshift, and remove from the front with shift. Splicing rewrites a middle range, and join turns the list into a string. All of these methods mutate the original array except join, which returns a new string.

javascript
const cart = ["pen", "book"];
cart.push("bag");
cart.unshift("note");

console.log(cart.length);
console.log(cart[0]);
console.log(cart[cart.length - 1]);
console.log(cart.join(", "));

Output

4
note
bag
note, pen, book, bag

Reading past the end returns undefined rather than an error, which is convenient and dangerous. A loop that uses <= against length reads one hole past the last item and silently processes undefined. The safe upper bound is index < array.length.

Arrays are objects, so typeof [] is "object". Use Array.isArray to check for an array. A length of zero is a real array, while a missing value is not, so check the array before reading its length when data arrives from outside.

1.5 Arrays of objects

Most real data is an array of objects: a list of users, orders or tasks. Each object has the same keys, and the array preserves order. This shape is the basis for rendering a list, filtering a search and passing data to an API.

Because objects hold references, an array of objects shares those objects with any other variable that points at them. Copying the array with spread copies the list, not the objects inside, a distinction the next lessons make heavy use of.

javascript
const users = [
  { name: "Aarav", score: 88 },
  { name: "Meera", score: 74 },
];

users[0].score = 90;

console.log(users[0].score);
console.log(users.length);
console.log(JSON.stringify(users));

Output

90
2
[{"name":"Aarav","score":90},{"name":"Meera","score":74}]

1.6 Iterating objects

for of does not work directly on a plain object because an object is not iterable in the array sense. The Object helpers return arrays that can be looped: Object.keys gives property names, Object.values gives values, and Object.entries gives [key, value] pairs.

Use entries when both sides are needed. for (const [key, value] of Object.entries(scores)) destructures each pair inside the loop, which reads cleanly and avoids a second lookup. The order follows property creation order for string keys, with integer-like keys sorted first, so a stable report should sort the keys explicitly.

Object.hasOwn(object, key) checks whether a key belongs to the object itself rather than its prototype. The in operator checks the whole chain, which includes inherited properties such as toString. For data objects, hasOwn is the precise test.

1.7 Copying arrays and objects

A shallow copy creates a new outer container but shares the values inside. [...array] copies an array's items, { ...object } copies an object's properties, and Object.assign({}, object) does the same thing with function syntax. None of these methods copy nested objects.

A deep copy duplicates every level. structuredClone(value) handles plain objects, arrays, dates, maps and sets, and it fails on functions. A JSON round trip is a quick deep copy for plain data but drops values JSON cannot represent. Choose the copy depth by asking who owns the nested objects after the copy.

1.8 Choosing a shape

Use an object when values are identified by a name and the order does not matter. Use an array when the values are a sequence and position matters. A list of records is an array of objects: the array carries order, and each object carries the fields of one record.

When a key repeats across records, an object keyed by that field can replace a search loop. A map from id to record answers a lookup in one step, while an array requires scanning until the match. Convert once when the data is loaded, and read the lookup many times.

1.9 Common mistakes

  • Reading a missing property and treating undefined as a real value.
  • Using dot access with a key that is stored in a variable.
  • Detaching a method from its object and losing this.
  • Reading array[array.length] and getting undefined.
  • Using for in on an array and expecting index numbers.
  • Assuming a copied array also copies the objects inside it.

Exam

Data questions usually print one property or one array operation. Track the reference: a dot access reads, an assignment creates or replaces a key, and push or pop changes the array in place. If two names point at the same object, a change through one is visible through the other.

  • Create an object with three properties and read one with bracket access.
  • Push and pop on an array and log the length after each call.
  • Build an array of two objects and update one property.
  • Explain what `array[array.length]` returns before running it.