t1a12 — JavaScript Objects by Innes

JavaScript Objects

Objects are variables that can store multiple related pieces of information as named properties. Each property has a name and a value.

Good reference to objects in JavaScript

Creating an empty object

We can create an object using the new Object() constructor:

							const myPerson = new Object();
						

Example: Working Objects Code

Click the button to create a person object and display its properties.

Your object will appear here...

Changing Object Properties

Object properties can be changed after the object has been created. Try changing the person's age!

Click a button to interact with the object.

Local and Global Variables

Let's talk about local and global variables. Why might it be best to declare the object in the script tag?

If an object is declared inside a function using let or const, it is normally only accessible inside that function. Trying to access it outside the function will cause a ReferenceError.

Declaring an object outside a function allows multiple functions to access it. This is useful when several buttons need to interact with the same object.

However, global variables can cause naming conflicts. Keeping variables inside functions or using a shared object in a controlled scope is often better for larger projects.

Challenge

Add a new property called favouriteGame to the object. Display it in showPerson(), then create a button that changes it.

\n