Introduction:
JavaScript object methods are powerful tools for organizing and manipulating data within your JavaScript applications. In this comprehensive guide, you’ll learn everything you need to know about working with object methods in JavaScript, including how to define, access, and utilize them effectively.
In JavaScript, objects are a data type used to store collections of key-value pairs. They can also have methods, which are functions associated with the object.
we can define methods within JavaScript objects as the following:
// Define an object let car = { brand: "Toyota", model: "Camry", year: 2020, // Define a method start: function() { return "The " + this.brand + " " + this.model + " has started."; }, // Another method drive: function() { return "The " + this.brand + " " + this.model + " is being driven."; } }; // Access object properties console.log(car.brand); // Output: Toyota console.log(car.year); // Output: 2020 // Call object methods console.log(car.start()); // Output: The Toyota Camry has started. console.log(car.drive()); // Output: The Toyota Camry is being driven.
In this example, start and drive are methods of the car object. They are defined as functions inside the object literal. When called, these methods can access other properties of the object using the this keyword.
Also we can define object methods using the ES6 shorthand syntax:
let car = { brand: "Toyota", model: "Camry", year: 2020, // Method definition using ES6 shorthand start() { return "The " + this.brand + " " + this.model + " has started."; }, drive() { return "The " + this.brand + " " + this.model + " is being driven."; } };
This shorthand syntax gives a quick way to define methods inside objects.
Here’s a step-by-step guide to creating JavaScript object methods:
by creating an object literal using curly braces {}.
Inside the braces,we define key-value pairs that represent the properties of the object.
let car = { brand: "Toyota", model: "Camry", year: 2020 };
To define a method within the object, we can create a key whose value is a function.
This function will be our method.
let car = { brand: "Toyota", model: "Camry", year: 2020, start: function() { console.log("The " + this.brand + " " + this.model + " has started."); } };
Within our method, we can access other properties of the object using the this keyword.
let car = { brand: "Toyota", model: "Camry", year: 2020, start: function() { console.log("The " + this.brand + " " + this.model + " has started."); } }; car.start(); // Output: The Toyota Camry has started.
To execute the method, simply we call it using dot notation (object.method()).
car.start(); // Output: The Toyota Camry has started.
That’s it! You’ve created a JavaScript object with a method. You can follow similar steps to add more methods or properties to your object. Remember that methods are just functions attached to objects, allowing you to encapsulate functionality related to that object.
Here’s a complete example of a web page with JavaScript object methods, along with explanations for each part:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Information</title> </head> <body> <h1>Car Information</h1> <p id="carInfo"></p> <script> // Step 1: Define the object let car = { brand: "Toyota", model: "Camry", year: 2020, // Step 2: Define the method start: function() { return "The " + this.brand + " " + this.model + " has started."; }, // Another method drive: function() { return "The " + this.brand + " " + this.model + " is being driven."; } }; // Step 3: Access Object Properties and Call the Method let carInfoElement = document.getElementById("carInfo"); carInfoElement.textContent = car.start(); // Display car starting message // Call another method console.log(car.drive()); // Output: The Toyota Camry is being driven. </script> </body> </html>
Explanation:
We start with the HTML structure for a basic web page.
Inside the <body> tag, we have an <h1> heading and a <p> paragraph element with the id “carInfo” where we’ll display information about the car.
Inside the <script> tag:
We define an object named car with properties like brand, model, and year.
We define two methods within the car object: start() and drive(). The start() method returns a string indicating that the car has started, and the drive() method returns a string indicating that the car is being driven.
We access the <p> element with the id “carInfo” using document.getElementById().
We set the text content of the <p> element to the result of calling the start() method of the car object. This displays the message “The Toyota Camry has started.” on the web page.
We also call the drive() method of the car object and log the result to the console.
This example demonstrates how to create a JavaScript object with methods and use them within a web page to display information.
Here’s another example of a web page with JavaScript object methods, along with explanations for each part:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book Information</title> </head> <body> <h1>Book Information</h1> <div id="bookInfo"></div> <script> // Step 1: Define the object let book = { title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925, // Step 2: Define the method getInfo: function() { return "The book '" + this.title + "' was written by " + this.author + " in " + this.year + "."; } }; // Step 3: Access Object Properties and Call the Method let bookInfoElement = document.getElementById("bookInfo"); bookInfoElement.textContent = book.getInfo(); // Display book information </script> </body> </html>
Explanation:
This example demonstrates how to create a JavaScript object with a method and use it within a web page to display information about a book.
In JavaScript, the this keyword is a special identifier that refers to the current instance of the object in which it’s used. The meaning of this depends on how it is used:
In a Method: Inside a method of an object, this refers to the object itself.
let person = { name: "John", greet: function() { console.log("Hello, my name is " + this.name); } }; person.greet(); // Output: Hello, my name is John
Here, this.name refers to the name property of the person object.
In a Constructor Function: Inside a constructor function (used with the new keyword), this refers to the specific instance of the object that is created.
function Person(name) { this.name = name; this.greet = function() { console.log("Hello, my name is " + this.name); }; } let john = new Person("John"); john.greet(); // Output: Hello, my name is John
In this example, this.name refers to the name property of the Person instance (john).
In a Global Context: In the global context (outside of any function or object), this refers to the global object (window in browsers, global in Node.js).
console.log(this === window); // Output: true (in a browser environment)
In an Event Handler: In event handlers, this typically refers to the element that triggered the event.
<button id=”myButton”>Click Me</button>
<script>
document.getElementById(“myButton”).onclick = function() {
console.log(this.id); // Output: myButton
};
</script>
In this example, this.id refers to the id attribute of the button element.
Understanding and correctly using this is crucial for writing object-oriented JavaScript code and ensuring that methods and properties are appropriately scoped and referenced within objects.
Here we will create a complete example of a web page showing the use of the this keyword in JavaScript language , along with explanations for each part:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>'this' Keyword Example</title> </head> <body> <h1>'this' Keyword Example</h1> <button id="myButton">Click Me</button> <p id="output"></p> <script> // Step 1: Define an object with a method using 'this' let myObject = { message: "Hello, ", name: "World", greet: function() { // 'this' refers to the object 'myObject' in this context return this.message + this.name; } }; // Step 2: Access object method using 'this' document.getElementById("myButton").addEventListener("click", function() { // Inside the event listener, 'this' refers to the button element document.getElementById("output").textContent = myObject.greet(); }); </script> </body> </html>
Explanation:
I have a simple HTML structure with an <h1> heading, a <button> element with the id “myButton”, and a <p> paragraph element with the id “output” where I’ll display the output.
Inside the <script> tag:
I define an object named myObject with properties message and name, along with a method greet(). Inside the greet() method, this is used to refer to the current object (myObject). It concatenates the message and name properties of the object.
I add an event listener to the button with the id “myButton”. Inside the event listener callback function, this refers to the button element itself. I then access the greet() method of myObject using myObject.greet(). Since this inside greet() refers to myObject, it returns “Hello, World”, which is displayed in the paragraph with the id “output” when the button is clicked.
Accessing object methods in JavaScript includes calling the method on the object using dot notation.
// Defining an object with methods let calculator = { add: function(x, y) { return x + y; }, subtract: function(x, y) { return x - y; } }; // Calling the methods using dot notation let result1 = calculator.add(5, 3); let result2 = calculator.subtract(10, 4); console.log("Addition Result:", result1); // Output: Addition Result: 8 console.log("Subtraction Result:", result2); // Output: Subtraction Result: 6
In this example:
I define an object named calculator with two methods: add and subtract.
To call the add method, we use dot notation (calculator.add()), passing the required arguments.
Similarly, we call the subtract method using dot notation (calculator.subtract()).
The methods perform the respective operations and return the results, which I store in variables (result1 and result2).
Finally, I log the results to the console.
Remember, when accessing object methods, you use the object name followed by a dot (.) and the method name, then provide any necessary arguments within parentheses.
we will create a complete example of a web page showing how to access object methods in JavaScript language , along with explanations for each part:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Accessing Object Methods</title> </head> <body> <h1>Accessing Object Methods</h1> <p id="result"></p> <script> // Step 1: Defining an object with methods let calculator = { // Method to add two numbers add: function(x, y) { return x + y; }, // Method to subtract two numbers subtract: function(x, y) { return x - y; } }; // Step 2: Calling the methods using dot notation let result1 = calculator.add(5, 3); // Calling add method let result2 = calculator.subtract(10, 4); // Calling subtract method // Step 3: Displaying the results on the webpage let resultElement = document.getElementById("result"); resultElement.innerHTML = "Addition Result: " + result1 + "<br>"; resultElement.innerHTML += "Subtraction Result: " + result2; </script> </body> </html>
Explanation:
I have a simple HTML structure with an <h1> heading and a <p> paragraph element with the id “result” where we’ll display the results.
Inside the <script> tag:
I define an object named calculator with two methods: add and subtract. These methods perform addition and subtraction operations, respectively.
I call the add method of the calculator object, passing two numbers (5 and 3) as arguments, and store the result in the variable result1.
Similarly, I call the subtract method of the calculator object, passing two numbers (10 and 4) as arguments, and store the result in the variable result2.
I access the <p> element with the id “result” using document.getElementById().
I set the inner HTML of the <p> element to display the results of the addition and subtraction operations using string concatenation (+=).
This example demonstrates how to define object methods, call them using dot notation, and display the results on a web page.
Adding a method to a JavaScript object involves simply assigning a function to a property of the object. Here’s how you can do it:
// Define an object let person = { firstName: "John", lastName: "Doe", }; // Adding a method to the object person.fullName = function() { return this.firstName + " " + this.lastName; }; // Calling the method console.log(person.fullName()); // Output: John Doe
In this example:
I have an object person with properties firstName and lastName.
I add a method named fullName to the person object by assigning a function to the fullName property of the object.
Inside the method, this refers to the person object, so this.firstName and this.lastName access the properties of the object.
I call the fullName method using dot notation (person.fullName()), which returns the full name of the person.
You can add methods to objects dynamically in this manner, which is one of the powerful features of JavaScript’s flexibility.
we will create complete example of a web page showing how to add a method to a JavaScript object, along with explanations for each part:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Adding a Method to a JavaScript Object</title> </head> <body> <h1>Adding a Method to a JavaScript Object</h1> <p id="fullName"></p> <script> // Step 1: Defining an object let person = { firstName: "John", lastName: "Doe" }; // Step 2: Adding a method to the object person.fullName = function() { return this.firstName + " " + this.lastName; }; // Step 3: Calling the method let fullNameElement = document.getElementById("fullName"); fullNameElement.textContent = "Full Name: " + person.fullName(); // Display the full name </script> </body> </html>
Explanation:
I have a simple HTML structure with an <h1> heading and a <p> paragraph element with the id “fullName” where we’ll display the full name of the person.
Inside the <script> tag:
I define an object named person with properties firstName and lastName.
I add a method named fullName to the person object by assigning a function to the fullName property of the object. This method concatenates the firstName and lastName properties to form the full name.
I access the <p> element with the id “fullName” using document.getElementById().
We set the text content of the <p> element to display the full name of the person by calling the fullName method of the person object using dot notation (person.fullName()).
This example shows how to add a method to a JavaScript object and use it to perform some operation, such as returning the full name of a person, and display the result on a web page.
JavaScript provides a variety of built-in methods that are available for different types of objects, such as arrays, strings, numbers, etc. These methods offer convenient functionalities to manipulate and work with data. Here’s a brief overview along with examples of using some built-in methods:
push() and pop(): Add/remove elements from the end of an array.
let arr = [1, 2, 3]; arr.push(4); // arr is now [1, 2, 3, 4] let lastElement = arr.pop(); // lastElement is 4, arr is now [1, 2, 3]
shift() and unshift(): Add/remove elements from the beginning of an array.
let arr = [2, 3, 4]; arr.unshift(1); // arr is now [1, 2, 3, 4] let firstElement = arr.shift(); // firstElement is 1, arr is now [2, 3, 4]
splice(): Add/remove elements from any position in an array.
let arr = [1, 2, 3, 4, 5]; arr.splice(2, 1); // Removes one element starting from index 2, arr is now [1, 2, 4, 5]
toUpperCase() and toLowerCase(): Convert a string to uppercase or lowercase.
let str = "Hello World"; let upperCaseStr = str.toUpperCase(); // "HELLO WORLD" let lowerCaseStr = str.toLowerCase(); // "hello world"
split() and join(): Split a string into an array of substrings or join an array of substrings into a single string.
let str = "apple,banana,orange"; let arr = str.split(","); // arr is ["apple", "banana", "orange"] let newStr = arr.join(";"); // newStr is "apple;banana;orange"
toFixed(): Format a number with a fixed number of decimal places.
let num = 10.345; let formattedNum = num.toFixed(2); // "10.35"
parseInt() and parseFloat(): Parse a string and return an integer or float.
let str = "123"; let intNum = parseInt(str); // 123 let floatNum = parseFloat("3.14"); // 3.14
These are just a few examples of the many built-in methods available in JavaScript. You can explore more in the JavaScript documentation or various online resources. These methods are powerful tools for manipulating data and performing various operations in JavaScript programs.
Below is an example of a project that demonstrates JavaScript object methods. In this project, we’ll create a simple task manager application where we can add tasks, mark them as completed, and display all tasks.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Task Manager</title> </head> <body> <h1>Task Manager</h1> <div> <input type="text" id="taskInput" placeholder="Enter a new task"> <button onclick="addTask()">Add Task</button> </div> <h2>Tasks:</h2> <ul id="taskList"></ul> <script src="script.js"></script> </body> </html>
// Define an object to manage tasks let taskManager = { tasks: [], // Method to add a task addTask: function(taskName) { this.tasks.push({ name: taskName, completed: false }); }, // Method to mark a task as completed completeTask: function(index) { if (index >= 0 && index < this.tasks.length) { this.tasks[index].completed = true; } }, // Method to display all tasks displayTasks: function() { let taskListElement = document.getElementById("taskList"); taskListElement.innerHTML = ""; // Clear previous tasks this.tasks.forEach(function(task, index) { let listItem = document.createElement("li"); listItem.textContent = task.name; if (task.completed) { listItem.style.textDecoration = "line-through"; } listItem.onclick = function() { taskManager.completeTask(index); taskManager.displayTasks(); }; taskListElement.appendChild(listItem); }); } }; // Function to add task (called from HTML button) function addTask() { let taskInput = document.getElementById("taskInput"); let taskName = taskInput.value.trim(); if (taskName !== "") { taskManager.addTask(taskName); taskManager.displayTasks(); taskInput.value = ""; // Clear input field } } // Initial display of tasks taskManager.displayTasks();
Explanation:
This function is called when the “Add Task” button is clicked.
It gets the value of the task input field, adds the task using the addTask method of taskManager, and then displays all tasks using displayTasks.
Initial Display:
After the JavaScript code, we call taskManager.displayTasks() to initially display any existing tasks when the page loads.
This project demonstrates the use of object methods in JavaScript to create a simple task manager application. It show cases how to organize code using object-oriented principles and encapsulate related functionality within objects.
Here’s a multiple-choice quiz about JavaScript object methods:
A) The parent object
B) The global object
C) The current instance of the object
D) The prototype object
A) push()
B) pop()
C) shift()
D) unshift()
A) start.car()
B) car.start()
C) car.method(start)
D) method.start(car)
A) toUpper()
B) toUpperCase()
C) upperCase()
D) toUpperCaseCase()
A) Converts a string to lowercase
B) Joins elements of an array into a string
C) Splits a string into an array of substrings
D) Adds elements to the beginning of an array
Explanation:
Answer: C) The current instance of the object
In JavaScript, the this keyword refers to the current instance of the object in which it is used.
Answer: A) push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Answer: B) car.start()
To call a method named start of an object named car, you use dot notation: car.start().
Answer: B) toUpperCase()
The toUpperCase() method converts a string to uppercase letters.
Answer: B) Joins elements of an array into a string
The join() method joins all elements of an array into a string and returns the resulting string.
Test your understanding of JavaScript object methods by answering these questions!