Objects

Objects are a central part of JavaScript, not everything is an object. JavaScript has primitive data types as well, such as numbers, strings, booleans, null, and undefined. These primitive types are not objects, but JavaScript provides object wrappers for them, allowing you to access properties and methods as if they were objects.

For example, you can use properties and methods with a string primitive as if it were an object:

const greeting = "Hello, world!";
console.log(greeting.length);  // Accessing a property of the string
console.log(greeting.toUpperCase());  // Calling a method on the string

Behind the scenes, JavaScript temporarily converts the primitive value to an object, performs the property/method access, and then converts it back to a primitive.

Objects (non-primitive)

Objects are a complex data type that allows you to store and organize related data using key-value pairs. Each key in an object is a string (or a Symbol), and its associated value can be any data type, including other objects, primitive values (like strings, numbers, booleans), and even functions. This structure resembles a dictionary or a map in other programming languages.

For example, here's a simple object with key-value pairs:

const person = {
    name: "Dev",
    age: 23,
    isStudent: true
};

Using a constructor function to create an object:

The Car function is a constructor function. Constructor functions in JavaScript are used to create and initialize objects. They are typically named with an initial capital letter to indicate that they are intended to be used as constructors. Inside the Car constructor, this refers to the instance of the object being created. The constructor takes three parameters (make, model, and year) and assigns them as properties of the object being created.

The new keyword is used to create an instance of the Car object. When you call a constructor function with the new keyword, it creates a new object, sets the constructor's this to the newly created object, and then executes the constructor code. In this case, it assigns the provided values for make, model, and year as properties of the new object. This line of code creates a new Car instance with the make "Eagle", model "Talon TSi", and year 1993.

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const myCar = new Car("Eagle", "Talon TSi", 1993);
console.log(myCar.model)

Prototype-Based Nature of JavaScript

Objects can serve as prototypes for other objects. This means that an object can inherit properties and methods from another object. This concept is crucial to understanding JavaScript's object-oriented programming approach.

const Obj1 = {
    greet: function() {
        console.log("Hello!");
    }
};

Obj1.greet(); // Outputs: "Hello!"