Understanding Basic JavaScript Objects and Arrays

Understanding Basic JavaScript Objects and Arrays

ยท

2 min read

In today's coding journey, we delved into the world of JavaScript objects and arrays, unraveling some fundamental concepts that pave the way for efficient coding practices. Let's break down what we've learned into digestible bits:

Objects in JavaScript:

JavaScript objects are collections of key-value pairs. We can create objects using curly braces {} or new Object(). For instance:

/

const jsUser1 = {}; // Singleton object
const user = {
    name: "pashuapti",
    email: "bansode@gmail.com",
    age: 23,
    isLogged: false,
    newUser: {
        loginTime: "10am",
        logeOutTime: "6pm",
        jsUser: {
            activity: "js development",
            role: "developer"
        }
    }
};

Accessing Object Properties:

We can access the properties of an object using dot notation or square brackets. For example:

console.log(user.newUser.loginTime); // Accessing nested properties
console.log(user.newUser.jsUser.role);

Merging Objects:

We can merge two or more objects using the spread operator (...). If there are common properties, values from the latter object will overwrite the former. For instance:

const obj4 = {...obj1, ...obj2};

Arrays Inside Objects:

Arrays can also be elements of an object. Accessing values within such arrays involves using array methods. For example:

const reactUser = [
    { id: 1, email: "banssode@gmail.com" },
    { id: 2, email: "banssode1@gmail.com" },
    // Other objects...
];
console.log(reactUser[1].id); // Accessing array elements

Working with Object Keys and Values:

We can retrieve all keys or values of an object using Object.keys() and Object.values() respectively. For example:

console.log(Object.keys(user)); // Output: [name, email, age, isLogged, newUser]
console.log(Object.values(user)); // Output: ["pashuapti", "bansode@gmail.com", 23, false, { loginTime: "10am", logeOutTime: "6pm", jsUser: { activity: "js development", role: "developer" } }]

Checking Property Existence:

We can determine if a property exists in an object using hasOwnProperty() method, which returns a boolean value. For example:

console.log(user.hasOwnProperty("isLogged")); // Output: true/false

Understanding these basics lays a solid foundation for more advanced JavaScript programming. Happy coding! ๐Ÿš€

ย