Object Basics

An employee has a name and an age. These two values belong together. An array is good for a list of similar things. To describe one thing with several parts, JavaScript has the object.

const person = { name: "Alice", age: 34 };
console.log(person.name);
console.log(person.age);

Output:

Alice
34

You write an object with curly braces { }. Inside are key: value pairs, separated by commas. Each pair is called a property. The key is the name (name, age), and the value is the data ("Alice", 34). To read a property, write the object, a dot, and the key.

You use the same dot to change a property. If the property already exists, its value is replaced. If it does not exist, JavaScript creates it.

<!-- continues -->
person.age = 35;
person.dept = "HR";
console.log(person);

Output:

{ name: 'Alice', age: 35, dept: 'HR' }

console.log prints the whole object, with every key and value. This helps when you want to check what is inside an object.

Notice that person is a const, but we still changed it. It works the same way as with arrays. const means the variable always points to the same object. The properties inside that object can still change.

A value does not have to be written directly. It can come from a variable or a calculation:

const name = "Bob";
const age = 41;
const worker = { name: name, age: age + 1 };
console.log(worker);

Output:

{ name: 'Bob', age: 42 }

What happens if you read a property that does not exist?

<!-- continues -->
console.log(worker.salary);
console.log(worker.nmae);

Output:

undefined
undefined

There is no error. You just get undefined, which means "no value was set". This also happens when you make a typo, like nmae instead of name. So if a property is undefined when you expect a value, check the spelling of the key first.

In the exercise, build an employee object from the input, then add a new property to it.