Hi folks.
It’s me again, with a new JavaScript Corner’s article.
I apologise again, but as I mentioned in my latest note, sometimes life gets busy, and finding free time to write articles is a bit more difficult.
As mentioned in the note, for the foreseeable future, I will be writing a new article biweekly.
Now, without further ado, let’s get into today’s article, in which I will be covering Objects in JavaScript.
Understanding Objects and Constructors in JavaScript
As a Front-End Engineer or Web Developer, mastering JavaScript objects and constructors is crucial for building robust web applications. Let's dive into these fundamental concepts with detailed explanations and code samples.
What are Objects in JavaScript?
Objects in JavaScript are complex data types that allow us to store collections of key-value pairs. They can hold various data types, including numbers, strings, booleans, arrays, functions, and even other objects.
Here's a basic example of an object:
const person = {
name: "John Doe",
age: 30,
city: "London"
};
Creating Objects
There are different ways to create objects in JavaScript:
1. Object Literal Notation:
const car = {
brand: "Tesla",
model: "Model 3",
year: 2024
};
2. Using the `new` Keyword with `Object()`:
const book = new Object();
book.title = "JavaScript: The Good Parts";
book.author = "Douglas Crockford";
book.year = 2008;
Constructor Functions
Constructor functions are a powerful way to create multiple objects with the same structure and behaviour. They act as blueprints for creating objects.
Here's how you define and use a constructor function:
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
}
const john = new Person("John Doe", 30, "London");
const emma = new Person("Emma Smith", 28, "Manchester");
john.greet(); // Output: Hello, my name is John Doe
emma.greet(); // Output: Hello, my name is Emma Smith
In this example, `Person` is a constructor function. When called with the `new` keyword, it creates a new object and sets the `this` keyword to refer to that new object[3]. The function then initialises the object's properties and methods.
The `new` Keyword
The `new` keyword is crucial when using constructor functions. It does the following:
Creates a new empty object.
Sets the `this` value of the constructor function to the new object.
Executes the constructor function.
Returns the new object (unless the constructor explicitly returns a different object).
Prototypes and Constructor Functions
Constructor functions in JavaScript use prototypes to share methods across all instances, which is more memory-efficient:
function Animal(species, sound) {
this.species = species;
this.sound = sound;
}
Animal.prototype.makeSound = function() {
console.log(this.sound);
};
const dog = new Animal("Dog", "Woof");
const cat = new Animal("Cat", "Meow");
dog.makeSound(); // Output: Woof
cat.makeSound(); // Output: Meow
In this example, the `makeSound` method is added to the prototype of `Animal`, so all instances share the same function, rather than each having its own copy.
ES6 Classes
ES6 introduced the `class` syntax, which is syntactic sugar over the prototype-based constructor functions:
class Vehicle {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
getInfo() {
return `${this.brand} ${this.model}`;
}
}
const myCar = new Vehicle("Tesla", "Model S");
console.log(myCar.getInfo()); // Output: Tesla Model S
This `class` syntax achieves the same result as constructor functions but with a more familiar syntax for developers coming from class-based languages.
The `constructor` Property
Every object in JavaScript has a `constructor` property, which references the function that was used to create the object:
console.log(john.constructor === Person); // Output: true
console.log(myCar.constructor === Vehicle); // Output: true
This property can be useful for checking the type of an object or creating new instances of the same type.
Conclusion
Constructor functions and the class syntax in JavaScript provide powerful ways to create and manage objects with shared properties and methods. In Web Development, understanding these concepts will help you write more organised, efficient, and maintainable code.
Remember, while the `class` syntax might look more familiar, JavaScript remains prototype-based under the hood. Mastering both the traditional constructor function approach and the modern class syntax will make you a more versatile JavaScript developer.
With that said, I will catch you all again in the next articles, in the next two weeks.
Until then take care and happy coding.