JS Object Properties šŸŽÆ

beginner
17 min

JS Object Properties šŸŽÆ

Welcome to our deep dive into JavaScript (JS) Object Properties! This tutorial is designed to help you understand, explore, and master this essential concept. Let's get started!

Understanding Object Properties šŸ“

An object in JavaScript is a collection of key-value pairs, where each key (or property name) is unique, and its corresponding value can be of any data type.

javascript
const myObject = { name: 'John Doe', age: 30, isStudent: true, hobbies: ['reading', 'coding', 'music'], };

In the example above, we have created an object named myObject with four properties: name, age, isStudent, and hobbies.

šŸ’” Pro Tip: Property names in JavaScript are case-sensitive, so make sure they are consistent throughout your code.

Accessing Object Properties āœ…

To access the properties of an object, you can use either dot notation (.) or bracket notation ([]).

  • Dot notation:
javascript
console.log(myObject.name); // Output: John Doe
  • Bracket notation:
javascript
console.log(myObject['name']); // Output: John Doe
Quick Quiz
Question 1 of 1

What will the following code log?

Creating Object Properties šŸŽÆ

You can add properties to an existing object using the dot notation and the bracket notation.

  • Dot notation:
javascript
myObject.newProperty = 'Hello World'; console.log(myObject.newProperty); // Output: Hello World
  • Bracket notation:
javascript
myObject['newProperty'] = 'Hello World'; console.log(myObject['newProperty']); // Output: Hello World
Quick Quiz
Question 1 of 1

What will the following code log?

Changing and Deleting Object Properties šŸ’”

You can modify or delete properties in an object using the assignment operator (=) and the delete keyword, respectively.

  • Modifying a property:
javascript
myObject.age = 31; console.log(myObject.age); // Output: 31
  • Deleting a property:
javascript
delete myObject.isStudent; console.log(myObject.isStudent); // Output: undefined (property no longer exists)
Quick Quiz
Question 1 of 1

What will the following code log?

Object Property Types šŸ“

Remember that object properties can hold values of different data types, such as:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Function
javascript
const myObject = { number: 42, string: 'Hello, World!', boolean: true, array: [1, 2, 3], object: { name: 'John Doe' }, function: function() { console.log('Hi!'); }, };

By learning about JS object properties, you're building a solid foundation for working with complex data structures and real-world projects. Happy coding! šŸš€