முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 3 · பாடம் 2 இன் 4பாடத்திட்டத்தில் 10/32~10 min
தொகுதி பாடங்கள் (2/4)

பொருள்கள்: முக்கிய மதிப்பு வரைபடம்

An object in JS is an unordered collection of key → value pairs. Keys are strings (or Symbol), values are anything: numbers, strings, arrays, other objects, functions. It's the most-used data structure in the language: every "record" in your domain will typically be an object.

JS
const utente = {
  nome: 'Anna',
  eta: 28,
  attivo: true,
  ruoli: ['admin', 'editor'],
};

Reading properties: dot vs bracket

There are two equivalent notations:

JS
utente.nome; // 'Anna'    (dot — the normal form)
utente['nome']; // 'Anna'    (bracket — equivalent)

// Brackets are MANDATORY when:
// 1) the key is not a valid identifier
const tag = { 'codice-fiscale': 'ABC123' };
tag['codice-fiscale']; // OK
// tag.codice-fiscale;      // syntax error

// 2) the key is computed (variable/expression)
const campo = 'eta';
utente[campo]; // 28

A missing property returns undefined, without errors:

JS
utente.telefono; // undefined

Adding, modifying, removing

JS
const u = { nome: 'Anna' };
u.eta = 28; // adds
u.nome = 'Anna B.'; // modifies
delete u.eta; // removes the property

delete is a keyword. It will turn out to be a rare use case: most of the time you'll want to produce a new object without that key (we'll see this with spread).

Shorthand: keys named like the variable

When the key name matches the variable name, you can omit the duplication:

JS
const nome = 'Anna';
const eta = 28;

const u1 = { nome: nome, eta: eta }; // explicit form
const u2 = { nome, eta }; // shorthand, equivalent

Checking the presence of a property

Three options, in order of preference:

JS
'nome' in utente; // true   ← in operator
utente.nome !== undefined; // true   ← works almost always
Object.hasOwn(utente, 'nome'); // true   ← modern, safe

Try it

உடற்பயிற்சி#js.m3.l2.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Create the object user = { name: 'Sara', age: 22 }, then add the 'active' property set to true and return the object as the last expression.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

You can add properties after the fact with dot notation.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m3.l2.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Given `product = { code: 'A1', price: 9.9 }` and the string `key = 'price'`, return the price using bracket notation (the last expression must evaluate to 9.9).

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

With brackets you can pass a variable as the key.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்