Objects in JavaScript (For Beginners)

Play with Objects

Objects in JavaScript (For Beginners)

Introduction

  • To learn JavaScript, As a beginner Just you need to have a good understanding of 'Objects' and 'Events'.

  • Objects in JavaScript are the most important concept.

  • In JavaScript, an object is a complex data type that represents a collection of key-value pairs, where the keys are strings (or symbols) and the values can be of any data type, including other objects. Objects are one of the fundamental data structures in JavaScript and are used extensively in the language.

Two ways to declare Objects in Javascript

  • Literal

  • Constructor

There is one concept of Singleton in Javascript Object.

Singleton

  • An object created by using a constructor is known as Singleton.

  • A singleton is an object that can only be instantiated once. It is a design pattern that ensures that there is only one instance of an object in a program.

  • Singletons can be used to control access to resources, to share data between objects, or to implement other design patterns.


Object Literals

  • Object Literals in Javascript are collections of key-value pairs, or properties, enclosed in curly braces.

  • The properties can be any valid JavaScript value, including strings, numbers, booleans, arrays, and functions.

NOTE : Try to code by yourself and understand the output

For Example

// Objects Literals

// Syntax
// const objectName = {
//     key: value
//    "name": "Harry" //By default system process KEY as STRING
// }

const User = {
    name: "Amelie",
    "full name": "Amelie Sierra",
    age: 22,
    location: "London",
    email: "amelieS@google.com",
    isLoggedIn: false,
    lastLoginDays: ["Monday", "Tuesday"]
}

// Access Object
console.log(User.email);
// console.log(User[email]);    // Error
console.log(User["email"]);    // By default 'key' in JS process as STRING

// How to access DEFAULT SYSTEM KEY ("full name")
console.log(User["full name"]);    // Can't access it by using (.) dot.

                        // <=======#######=======> //

// QUESTION (How to use SYMBOL as a key)
// Take any SYMBOL type variable, add it in objects key and print value.
const Sym = Symbol("key1");

const MyObj = {
    // Sym: "My Symbol",    // typeof key is STRING not SYMBOL
    [Sym]: "My Symbol",    // Syntax to access symbol 
}

// console.log(typeof MyObj.Sym);    // Datatype is STRING
console.log(typeof MyObj[Sym]);    // Datatype is SYMBOL

                        // <=======#######=======> //

// Modify Objects Value
User.email = "ame@gmail.com";
// freeze() object method
// Object.freeze(User);
User.email = "ame@microsoft.com";
console.log(User);

                        // <=======#######=======> //

// Add Functions in Object
// In JavaScript, Functions are treated as typeone (Function are treated 
// as variable) citizen types.

User.greeting = function(){
    console.log("Hello Javascript User");
}
console.log(User.greeting); // Output : Function (anonymous) <= function 
// return back not executed

console.log(User.greeting()); // Function will get execute.

                        // <=======#######=======> //

// Reference any object 'key' using 'this' keyword
// 'this' keyword to use as a object key reference
User.greetingTwo = function(){
    console.log(`Hello Javascript User, ${this.name}`);
    //console.log(`Hello `, ${this.name}); <= is known as String Interpolation
}

console.log(User.greeting());
console.log(User.greetingTwo());

Object Constructor (Object())

  • In JavaScript, there is a special constructor function known as Object().

  • Object() is used to create and initialize an object.

  • It needs to create an object 'type' that can be used multiple times without redefining the object multiple times.

  • Any constructor is created by using the 'new' keyword.

  • e.g.

    • const n = new Number(); // Number() constructor is created by using the 'new' Keyword of type Object.

For Example

const User = new Object();
// const User = {}; // exactly same as object constructor
console.log(User);    // output: {} <= empty object

                        // <=======#######=======> //

// Difference between object literals and object constructor
// => Only difference is Object Constructor is a 'Singleton Object' whereas
//    Object literals are the 'Non-singleton Object'.

                        // <=======#######=======> //

// Assign properties to the object
const NewUser = new Object();
NewUser.id = '1A';
NewUser.name = "Alexa";
NewUser.isLoggedIn = false;

console.log(NewUser);

Understand further more things in Object (Important)

//1. Object inside object
const User = {
    email: "amilie@gmail.com",
    fullname: {
        userfullname: {
              firstname: "amilie",
              lastname: "fernandez",      
        }
    }
}

// access values
console.log(User.fullname.userfullname.firstname);
console.log(User.fullname?.userfullname:.email); // Optional chaining

                        // <=======#######=======> //

//2. Merge Object
const obj1 = {1: "a", 2: "b"};
const obj2 = {3: "c", 4: "d"};

const obj3 = { obj1, obj2 }
console.log(obj3)    //output: objects inside object

//assign() method to merge object\
/*
syntax: 

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// Expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget === target);
// Expected output: true

*/
const obj4 = Object.assign(obj1, obj2);    //obj2 value combine in obj1
console.log(obj4);

const obj5 = Object.assing({}, obj1, obj2, obj3);//objects value combine in {}
// {} is target & obj1, obj2, obj3 are the source

                        // <=======#######=======> //

//3. Merge object by using Spread Operator(...)
// Highly used operator
const obj6 = {...obj1, ...obj2, obj3);    // same output as obj
console.log(obj6);

                        // <=======#######=======> //

// 4. Values come from Database
// Data from database comes in the form of array of objects
// for example
const data = [
    {
        id: 1,
        email: "hello@gmail.com",
    },
    {
        id: 1,
        email: "hello@gmail.com",
    },
    {
        id: 1,
        email: "hello@gmail.com",
    },
    {
        id: 1,
        email: "hello@gmail.com",
    },
]

// access value
console.log(data[1].email);
// Note : there is another method to access by using map() It is 
//        a advanced concept.

                        // <=======#######=======> //

//5. keys() and values() method

const Hello = {
    name: "hello",
    age: 18,
    isLoggedIn: false,
}

console.log(Object.keys(Hello));    // return values in array
// Expected output: [ 'name', 'age', 'isLoggedIn' ]

console.log(Object.values(Hello));
// Expected output: [ 'hello', 18, false ]

console.log(Object.entries(Hello));
// Expected output: [ ['name', 'hello'], ['age', 18], ['isLoggesIn', false] ]

                        // <=======#######=======> //

//6. hasOwnProperty() method
console.log(Hello.hasOwnProperty('isLoggedIn'); // output: true
console.log(Hello.hasOwnProperty('fullname');  // output: false

💡
RESOURCES

NOTE:

  1. This much of information about 'object' is enough for the beginner.

  2. Try to code by yourself and understand the output