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!
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.
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.
To access the properties of an object, you can use either dot notation (.) or bracket notation ([]).
console.log(myObject.name); // Output: John Doeconsole.log(myObject['name']); // Output: John DoeWhat will the following code log?
You can add properties to an existing object using the dot notation and the bracket notation.
myObject.newProperty = 'Hello World';
console.log(myObject.newProperty); // Output: Hello WorldmyObject['newProperty'] = 'Hello World';
console.log(myObject['newProperty']); // Output: Hello WorldWhat will the following code log?
You can modify or delete properties in an object using the assignment operator (=) and the delete keyword, respectively.
myObject.age = 31;
console.log(myObject.age); // Output: 31delete myObject.isStudent;
console.log(myObject.isStudent); // Output: undefined (property no longer exists)What will the following code log?
Remember that object properties can hold values of different data types, such as:
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! š