Back to: JavaScript Tutorial For Beginners and Professionals
JavaScript Object Methods with Examples
In this article, I am going to discuss JavaScript Object Methods with Examples. At the end of this article, you will understand what are JavaScript Object Methods and when, and how to use JavaScript Object Methods with examples.
JavaScript Object Methods with Examples
A function that is a property of an object is called an object method. JavaScript object method is also called Object function. As we know the function is nothing but the collection of statements that can be run anywhere at any time and it is used to avoid writing the same code again and again whenever it is needed. JavaScript function is a reusable piece of code.
- Designed to perform a particular task.
- Can be invoked(called) from another code.
- Usually has a name.
- Can take parameters and return a value.
Functions allow breaking a large program into smaller pieces.
Why uses Functions?
More manageable code
- Split large programs into smaller pieces.
- Better organization of the program
- Improve code readability and understandability.
Improves code maintainability.
- Promotes code reuse.
- Avoids repeating code.
To get deep knowledge of what the function is all about please refer JavaScript Function chapter. Meanwhile, we will summarize the function/method in short.
A function also known as a method is a self-contained piece of code that performs a particular “function”. You can identify a function by its format – it’s a piece of descriptive text, followed by open and closed brackets.
A function is nothing but an action to take to complete a goal, objective, or task. Functions allow you to split a complex goal into simpler tasks, which makes managing and maintaining scripts easier. A parameter or argument is data that is passed to a function to affect the action to be taken. Functions can be passed to zero or more arguments. A function executes when a call to that function is made anywhere within the script, the page, an external page, or by an event. Functions always return some value when executed. The data passed to a function when running is known as the function’s input and the value returned from an executed function is known as the function’s output.
A JavaScript function is a code block that can be reused wherever required. The function can be called via an event, by manual calling, or when the function is called.
To prevent the browser from executing a script when the page loads, we can put our script into a function. A function contains a piece of code that will be executed by an event or by a call to that function. You can call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document. However, to ensure that the function is read/loaded by the browser before it is called, it could be wise to put it in the <head> section.
How to Create a Function in JavaScript?
In JavaScript, functions can be created inside the JavaScript script tag only. A function is a reserved keyword of JavaScript. Use the keyword function with the name of the function. After the function name, open and close parentheses (). After parenthesis, open and close curly braces {} should be there. Within curly braces, write your lines of code from where the function starts and where ends are kept inside in curly braces.
Syntax:
function functionName(param1, param2, ...paramN) { //code to be executed return anyValue;//return is used if the function returns any value otherwise not. }
Here, param1, param2, etc. are variables or values passed into the function. The open {and the close} braces define the start and end of the function. A function with no parameters must include the parentheses () after the function name which is shown in the below syntax:
function functionName() { //code to be executed return anyValue;//return is used if the function returns any value otherwise not }
Note: Make sure we use capitals in JavaScript. ensure that the word function is written in lowercase letters, otherwise, a JavaScript error occurs! Also, note that we must call a function with the exact same capitals as in the function name.
JavaScript Function with Return Value
We can also create JavaScript functions that return values. Inside the function, we need to use the keyword return followed by the value to be returned. The return statement specifies the value that will be returned by the function. Therefore, functions that return values must use the return statement. Every JavaScript function returns undefined unless otherwise specified. Functions can be constructed in three main different ways.
- By Function Declaration
- By Function Expression
- Using the constructor of the Function object.
We begin with three print “Hello” examples. What we discussed above is given in the below example.
Example: JavaScript function 3 ways to define.
<html> <head> <title>JavaScript function 3 ways to define example</title> </head> <body> <script> //Way1-By function declaration function printHello1() { alert('Hello1') }; //Way2-By function Expression var printHello2 = function () { alert('Hello2') }; //Way3-Using the constructor of the Function object. var printHello3 = new Function( 'alert("Hello3")' ); printHello1(); printHello2(); printHello3(); </script> </body> </html>
Output:
In the above code. Each function:
- Can be called with printHello()
- Does not expect any arguments /parameters.
- Perform an action to show an alert message to the user.
- undefined is returned when execution is finished.
The printHello() function can be changed to allow us to say hello to someone specific through the passed argument by using an argument. What we discussed above is given in the below example.
Example: JavaScript function 3 ways to define with argument.
<html> <head> <title>JavaScript function 3 ways to define with argument example</title> </head> <body> <script> //Way1-By function declaration function printHello1(who) { alert('Hello1,' + who + '!') }; //Way2-By function Expression var printHello2 = function (who) { alert('Hello2,' + who + '!') }; //Way3-Using the constructor of the Function object. var printHello3 = new Function('who', 'alert("Hello3," + who + "!")' ); param = 'Shagufta' printHello1(param); printHello2(param); printHello3(param); </script> </body> </html>
Output:
In the above code. Each function:
- Can be called with printHello()
- Expects one argument to be passed.
- Perform an action to show an alert message to the user.
- undefined is returned when execution is finished.
Each function can be called in several ways, which is shown in the below code. What we discussed above is given in the below example.
Example: JavaScript function 3 ways to define and called in several ways
<html> <head> <title>JavaScript function 3 ways to define and called in several ways example</title> </head> <body> <script> //Way1-By function declaration function printHello1(who) { alert('Hello1,' + who + '!') }; //Way2-By function Expression var printHello2 = function (who) { alert('Hello2,' + who + '!') }; //Way3-Using the constructor of the Function object. var printHello3 = new Function('who', 'alert("Hello3," + who + "!")' ); param = 'Shagufta' //printHello2(param); //printHello3(param); printHello1(param); printHello1.call(window, param); printHello1.apply(window, [param]); </script> </body> </html>
Output:
We talked about function in short. We will see what the object method is all about. We have already seen what JavaScript Object is, what are its features, etc. in the JavaScript Objects Chapter.
An Object is an instance of a class that has the structure of its blueprint but also owns its unique state(property) and behavior(method). JavaScript objects are simple maps from names (or keys) to:
- values (properties)
- functions (methods)
Objects are containers with properties. properties can contain anything.
- Even functions
- Or other objects
An object property is an association between a name (or key) and a value. A value of a property can be either
- Property (variable/ field)
- Function (method)
We use methods to describe object behaviors. Hence, JavaScript methods are nothing but an action that can be performed on an object. JavaScript functions can be assigned to an Object function property, and in this case, they are called methods. JavaScript methods are the property containing a function definition. Methods are functions that are stored as object properties.
Use the following syntax to create an object method:
methodName : function () { //code here},
Access an object method using the following syntax:
objectName.methodName();
We can declare the properties and methods listed using cleaner Object Literal syntax as follows:
var myObject = { myProperty: value, secondProperty: value, myMethod: function () { //code here }, secondMethod: function () { //more code } } //Access an object method myObject.myMethod(); myObject.secondMethod();
An object can be created with curly brackets {…} with a list of properties. A property is a “key: value” pair, where the key is a string (also called a “property name”), and the value can be any data type, like strings, numbers, Booleans, or complex data types like arrays, functions, and other objects. with the names(keys) and the values separated by colons (:). As you already know, document.write() outputs data. The write() function is actually a method of the document object.
document.write(“This is some text”);
We have already seen how each function can be constructed in 3 ways i.e.
- By function Declaration
- By function Expression
- Using the Constructor of the Function Object.
Using function inside an object as a property. We will create a greet() method in a person object using the above 3 different ways along with object literals and this value
- Using Object Literal
- this value
By Function Declaration
Here as the name indicates we first declared the function named printMsg() as a regular function and secondly, we could use this pre-declare function as an object method, by assigning the function name printMsg to the greet property of the person object. Thirdly, call the greet() method.
Note: It is not necessary to write the function’s parentheses when assigning it to an object. Call the method by the Object property name you specified in the constructor function, rather than the function name.
Example: JavaScript defines a function to the person object using function declaration
<html> <head> <title>JavaScript defines function in person object using function declaration example</title> </head> <body> <script> //Way1-By function declaration const person = { name: 'John', age: 15, bloodgroup: 'A+', } //first, declare a regular function function printMsg(who) { alert('Hello,' + who + '!') }; //then add as a method to the property of the object person.greet = printMsg; //call the object method with argument person.greet(person.name); </script> </body> </html>
Output:
By Function Expression
Here we need to first use a function expression to define a function and assign it to the greet property of the person object. Later, call the greet() method.
Example: JavaScript defines a function to person object using the function expression
<html> <head> <title>JavaScript defines a function to person object using function expression example</title> </head> <body> <script> //Way2-By function expression const person = { name: 'John ', age: 15, bloodgroup: 'A+', } //function Expression to define a function person.greet = function (who) { alert('Hello,' + who + '!') }; //call the object method with the argument person.greet(person.name); </script> </body> </html>
Output:
In the next article, I am going to discuss Object Literal in JavaScript with Examples. Here, in this article, I try to explain JavaScript Object Methods with examples. I hope you enjoy this JavaScript Object Methods article. I would like to have your feedback. Please post your feedback, question, or comments about this article.