1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
9

JavaScript Objects

Updated on 06/08/2024227 Views

I believe that JavaScript objects are the backbone of JS programming. Any other JS developer would also agree with me on this. JavaScript objects allow us to package data and related functionality into neat, reusable units.

I wish to teach you how objects can streamline our code with this JavaScript objects tutorial. We will learn to create JavaScript objects, define their properties (data), and craft methods (actions).

Let us discover how objects make our JavaScript code more organized, efficient, and easier to manage.

What are Objects in JS?

Objects in JavaScript are like containers that store related data and actions. Think of them as boxes holding information (properties) and instructions on how to use it (methods).

For example, a "car" object might have properties like "color" and "model," along with methods like "start" and "stop". This keeps your code organized and makes it easier to model real-world things!

Now, let me quickly take you through JavaScript objects methods, properties, and values: 

  • Properties and values: Imagine properties as labels on the "box" we mentioned earlier. They hold specific pieces of data, like a car's "color" being "red" or a book's "title" being "The Hitchhiker's Guide to the Galaxy." These values can be simple text, numbers, or even other objects.
  • Methods: Methods are like the "instructions" inside the box. They're functions that act on the object's data. A car object's "start" method might prepare the engine, while a book object's "getDescription" method might return a summary of the story.

Types of Objects in JavaScript

There are two types of objects in JavaScript, built-in objects and user-defined objects. Let us learn more.

Built-in Objects

There are two types of built-in objects:

  1. Core Objects: These form the foundation of JavaScript. Examples include:
  • Date: Represents dates and time.
  • Array: Stores ordered collections of data.
  • Math: Provides mathematical constants and functions.
  • Set: Stores unique collections of values.
  • Map: Stores key-value pairs with flexible keys.
  • RegExp: Represents patterns for text searching and manipulation.
  • Error: Generic error object.
  • EvalError, SyntaxError, TypeError, etc: Specific errors related to code evaluation and syntax.
  • Function: The fundamental unit of executable code.
  • GeneratorFunction: A function that can pause and resume, yielding multiple values.
  • Global: Properties and functions available anywhere in your code.
  • Number: Represents numeric values and offers mathematical operations.
  • BigInt: Handles integers with precision beyond regular numbers.
  • String: Represents and manipulates text.
  • Boolean: Represents true/false values.
  • Symbol: Creates unique and immutable identifiers.
  • Object: The base-level object from which most others inherit properties.
  1. Browser Objects (BOM): These objects allow you to interact with the browser and webpage. They are:
  • Window: The top-level browser window object.
  • Document: Represents the loaded HTML document.
  • Location: Contains information about the current URL.
  • Navigator: Provides information about the browser.
  • XMLHttpRequest: Used for making asynchronous (AJAX) requests.

User-Defined Objects

There are two types of user-defined objects in JS:

  • Literal objects: You create these directly, with properties and methods wrapped in curly braces ({}). Think of them as blueprints for custom structures.
  • Constructor functions: These are like templates for creating multiple objects with a similar structure. You use the "new" keyword to create instances from constructor functions.

The exact JavaScript object type we need depends on the problem we are solving, and learning that is an essential part of JavaScript object programming. Built-in objects provide ready-to-use functionality, while user-defined objects give us the flexibility to model our custom data structures.

Now that we know more about JavaScript object types, let us explore some examples.

JavaScript Objects Examples

Here are some examples of common objects in jS:

  • Array: Think of an array as an ordered list. You can store different data types within it, like let shoppingList = ["milk", "eggs", 2, true];. Arrays offer methods like push(), pop() for addition/removal, and sort() for arranging the elements.
  • Date: Handles anything related to dates and times. You can get the current date (let today = new Date();), specific parts like the year (today.getFullYear()), or even perform calculations (tomorrow.setDate(today.getDate() + 1);).
  • Math: Here are some math examples:
    • Math.pow(2, 3) // Returns 8 (2 to the power of 3)
    • Math.sqrt(9) // Returns 3 (square root of 9)
    • Math.PI // The value of Pi (approximately 3.14159)
    • Math.E // Euler's number
    • Math.sin(Math.PI / 2) // Returns 1 (sine of 90 degrees)
    • Math.cos(0) // Returns 1 (cosine of 0 degrees)
  • User-defined objects: All the objects that are defined by users themselves. Here is an example of object literals:

let student = {

    name: "Alice",

    grade: 10, 

    passExam: function() { this.grade += 1; } 

};

In the above code snippet, the different properties store data about the student, and the passExam method models an action the student can take.

  • Constructor functions: Templates for creating multiple objects. Example: javascript function Book(title, author) { this.title = title; this.author = author; }

Now we can create multiple books: let favoriteBook = new Book("The Hobbit", "J.R.R. Tolkien");

Now, here is an example of me using the Math object for calculating the area of a circle:

Code:

let radius = 5;

let area = Math.PI * Math.pow(radius, 2);

console.log("The area of the circle is:", area); 

Creating a JavaScript Object

1. Using object literals

This is the most straightforward way when it comes to creating JavaScript objects. When using object literals, properties are defined as name: value pairs. We define the methods (functions within an object) as methodName: function() { ... }.

Example:

let car = {

    make: "Honda",

    model: "Civic",

    year: 2022,

    startEngine: function() {

        console.log("Vroom!");

    }

};

2. Using constructor functions

Using constructor functions is like using blueprints for creating objects. When using constructor functions, we use the new keyword to create instances of the object. Then, we use this inside the constructor for referring to the new object being created.

Example:

function Book(title, author, pages) {

    this.title = title;

    this.author = author;

    this.pages = pages;

}

let myBook = new Book("The Hobbit", "J.R.R. Tolkien", 300);

3. The Object.create() Method

This JavaScript objects method is used for more control over an object's inheritance. This method is less common for everyday object creation.

Example:

let personProto = {

    greet: function() {

        console.log("Hello!");

    }

};

let john = Object.create(personProto);

john.name = "John";

In the above code, personProto acts as a JavaScript object prototype for john.

JavaScript Objects Examples in Programs

Example 1: Representing a Product

Code:

const product = {

    name: "Wireless Headphones",

    price: 129.99,

    brand: "Acme",

    inStock: true,

    description: "Noise-canceling headphones with Bluetooth connectivity."

};

// Accessing properties:

console.log("Product Name:", product.name); 

console.log("Price:", product.price); 

Example 2:  Student Record Management

Code:

function createStudent(name, grade, courses) {

    return {

        name: name,

        grade: grade,

        courses: courses,

        addCourse: function(newCourse) {

            this.courses.push(newCourse);  

        }

    };

}

let student1 = createStudent("Alice", 11, ["Calculus", "Chemistry"]);

student1.addCourse("History");

Example 3:  Modeling a UI Element (Button)

Code:

const button = {

    text: "Click Me",

    width: 150,

    color: "blue",

    onClick: function() {

        alert("You clicked the button!");

    } 

};

JavaScript object to JSON Strings

JavaScript provides a super simple way to convert your JavaScript objects into JSON strings using JSON.stringify(). Here is how:

  • First, we make a JavaScript object:

const myObject = {

    name: "Alice",

    age: 30,

    city: "New York" 

};

  • Then, we use JSON.stringify():

const jsonString = JSON.stringify(myObject);

console.log(jsonString); 

// Output: {"name":"Alice","age":30,"city":"New York"} 

If you wish to learn web development and software engineering technologies such as JavaScript, you can check out upGrad’s full stack development courses.

Benefits of Objects

Using objects keeps your code organized. Instead of having separate variables for each piece of data about a car, you group everything together. This makes your code cleaner and easier to understand, especially when dealing with complex things.

Objects offer these powerful benefits:

  • Encapsulation: Objects bundle related data and the actions that can be performed on that data into a single entity. This keeps parts of your code neatly self-contained, making everything easier to manage.
  • Modularity: Think of objects as building blocks. Once you create an object like "car", you can reuse it throughout your program, reducing code duplication and making changes much simpler.
  • Abstraction: Objects let you hide implementation details. You can use a car object's "start" method without worrying about the intricate steps of how the engine actually starts –  simplifying how you use complex systems.

Wrapping up

Objects form the foundation of well-structured JavaScript code. They help you model real-world entities, organize data, and encapsulate behavior. By understanding JavaScript objects, you gain the ability to write more modular, maintainable, and expressive code.

According to me, when it comes to user-defined objects, object literals are the simplest for most use cases. Constructor functions are useful when we need to create multiple similar objects.

If you continue exploring JavaScript objects and their applications, you'll unlock cleaner and more powerful ways to solve problems with JavaScript. To master JavaScript and other programming tools, you can check out upGrad’s software engineering courses.

Frequently Asked Questions

1. What are the JavaScript objects?
Objects are containers that store properties (data) and methods (actions) related to a specific entity.

2. What are the two types of objects in JavaScript?
The two types are:

  • Built-in objects: Provided by the language (e.g., Array, Date, Math)
  • User-defined objects: Created by the developer (using object literals or constructor functions).

3. What is data object in JavaScript?
Any object primarily used to store and represent data (as opposed to an object with lots of methods for complex behavior).

4. What is the object model in JavaScript?
The object model is the underlying way JavaScript represents data and functionality, where nearly everything is an object with properties and methods.

5. What is an object example?
Here is a JavaScript objects example:
let car = { make: "Toyota", model: "Camry", color: "blue" }; 

6. Why use objects in JavaScript?

  • Organization: Group related data and code together.
  • Reusability: Create reusable templates for representing similar entities.
  • Abstraction: Simplify complex systems into manageable units.

7. How to create an object?

  • Object literals: let obj = { prop: "value" };
  • Constructor functions: function ObjectName(...) { ... }; let myObj = new ObjectName(...);

8. Why do we use an object?
We use objects to model real-world entities and concepts, leading to structured, readable, and maintainable code.

9. What is object in programming?
An object is a self-contained unit encapsulating data (variables) and the operations that act on that data (functions/methods).

image

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...