Topic 62 of 87
Object Basics
Overview
Objects are the most important data type in JavaScript. While primitive types (like Strings or Numbers) can only hold a single value, Objects are complex collections that can hold multiple values as 'Key-Value pairs'.
Objects are used to represent real-world entities (like a User, a Car, or a Product), keeping all their related data and behaviors neatly bundled together.
Syntax
Object Literal Syntax (Preferred)
javascript
const user = {
// Key: Value
firstName: "Kartik",
lastName: "Rai",
age: 22,
// Methods (Functions stored in properties)
fullName: function() {
return this.firstName + " " + this.lastName;
}
};Accessing and Modifying
javascript
// Dot Notation (Standard, clean)
console.log(user.firstName); // "Kartik"
// Bracket Notation (Dynamic keys!)
// Used when the key name is stored in a variable
const dynamicKey = "age";
console.log(user[dynamicKey]); // 22
// Modifying and Adding new properties
user.age = 23;
user.isAdmin = true;Common Pitfalls
- Forgetting that Object keys are ALWAYS strings (or Symbols). Even if you type
1: 'hello', JavaScript silently converts the number1into the string'1'under the hood. - Trying to use Dot Notation with dynamic variables:
user.dynamicKeywill look for a literal string property named 'dynamicKey', not the variable's value! Always use bracketsuser[dynamicKey]for variables.
Interview Questions
Q:
What is the difference between Dot notation and Bracket notation?
A:
Dot notation is cleaner but requires you to know the exact literal string name of the property at coding time. Bracket notation allows you to evaluate expressions and use variables to dynamically access keys at runtime.
Real-World Example
Defining a configuration object for an API request.
example
javascript
const requestConfig = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};Check Your Knowledge
Test your understanding of Object Basics with these quick questions.