JavaScript Objects, Functions, Methods and Properties: What They Are and How to Use Them

Photo by Irvan Smith on Unsplash

JavaScript Objects, Functions, Methods and Properties: What They Are and How to Use Them

different ways to create objects and more about objects and methods.

In programming, a function is a sequence of code that performs a specific task. JavaScript functions are special types of variables that can take values (called parameters) and return another value when the function has finished running. In this article, you will learn what functions and methods are, how to use them in your code, and some best practices for using functions effectively. Let’s get started!

What is a function?

Using functions, you can combine a number of statements to carry out a certain task. You can reuse a function in a script if various sections carry out the same action (rather than repeating the same set of statements).

In this example, the user is shown a message at the top of the page. The message is held in an HTML element whose id attribute has the value "message." The message is going to be changed using JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic function</title>
    <link rel="stylesheet" href="css/c03.css">
</head>
<body>
    <h1>starTravel</h1>
    <div id="message">Welcome to our site!</div>
    <script src="js/basic-function.js"></script>
</body>
</html>
var msg = 'Sign up to recieve our newsletter for 10% off!';

function updateMessage(){
    var el = document.getElementById('message');
    el.textContent = msg;
}

updateMessage();

starTravel.png

What are anonymous functions and function expressions?

An expression generates a value. Where values are expected, they can be used. A function is treated as an expression if it is used in a place where a browser would typically expect to see an expression (for example, as an argument to a function).

In order to call the function later in your code, you must give it a name, so these are known as named functions. Below, a function called area() is declared, which can then be called using its name.

function area (width, height) 
return width * height; 
}; 
var size= area (3, 4) ;

If you put a function where the interpreter would expect to see an expression, then it is treated as an expression, and it is known as a function expression. In function expressions, the name is usually omitted. A function with no name is called an anonymous function. Below, the function is stored in a variable called area. It can be called like any function created with a function declaration.

var area = function(width, height) { 
return width * height; 
} ; 
var size = area (3, 4) ;

The function is not processed in a function expression until the interpreter reaches that statement. Therefore, you are unable to call this function prior to the interpreter becoming aware of it. It also implies that every piece of code up until that point could possibly change what occurs within this function.

What is an immediately invoked function expression?

This method of function writing is applied in a variety of situations. Functions are frequently used to avoid name conflicts between variables (especially if the page uses more than one script).

These functions, which are pronounced "iffy," are not given names. As the interpreter comes across them, they are instead executed once.

Instead of storing the function itself so that it can be called later, the area variable will hold the value returned from the function in the code below.

var area = ( function() {
var wi dth = 3; 
var height = 2; 
return width * height; 
}());

The closing curly brace of the code block and the final pair of parentheses instruct the interpreter to call the function right away. The operators for grouping are in place to ensure that the interpreter treats this as an expression.

What is a variable scope?

The location where you declare a variable will affect where it can be used within your code. If you declare it within a function, it can only be used within that function. This is known as the variable's scope.

When a variable is created inside a function using the var keyword, it can only be used in that function. It is called a local variable or function-level variable. It cannot be accessed outside of the function in which it was declared. Below, area is a local variable.

If you create a variable outside of a function, then it can be used anywhere within the script. It is called a global variable and has global scope. In the example shown, wallSize is a global variable.

function getArea(width, height) 
var area = width * height; 
return area; 
var wallSize = getArea(3, 2); 
document. write(wallSize);

Functions used in an object

Objects group together a set of variables and functions to create a model of something you would recognize from the real world. In an object, variables and functions take on new names.

In an object, variables become known as properties. If a variable is part of an object, it is called a property. Properties tell us about the object, such as the name of a hotel or the number of rooms it has. Each individual hotel might have a different name and a different number of rooms.

In an object functions became known as methods. If a function is part of an object, it is called a method. Methods represent tasks that are associated with the object. For example, you can check how many rooms are available by subtracting the number of booked rooms from the total number of rooms.

var hotel = {
    name: "Quay",
    rooms: 40,
    booked: 25,
    checkAvailability: function(){
        return this.rooms - this.booked;
    }
};

Let's see some of the ways to create an object.

Creating objects using literal notation

Below, an object literal called hotel is created. Once it has been created, three properties and a method are then assigned to the object. To access a property of this object, you can use dot notation, just as you can with any object. For example, to get the hotel's name you could use: (hotel.name). Similarly, to use the method, you can use the object name followed by the method name: hotel.checkAvailability().

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>object literal</title>
    <link rel="stylesheet" href="css/c03.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit&display=swap" rel="stylesheet">
</head>
<body>
    <h1>Hotel Availability</h1>
    <div class="content">
        <hr>
        <div id="hotelName">Redrea</div>
        <hr>
        <div id="rooms">100</div>
        rooms left
    </div>
    <script src="js/object-literal.js"></script>
</body>
</html>
var hotel = {
    name: "Quay",
    rooms: 40,
    booked: 25,
    checkAvailability: function(){
        return this.rooms - this.booked;
    }
};

var elName = document.getElementById("hotelName");
elName.textContent = hotel.name;

var elRooms = document.getElementById('rooms');
elRooms.textContent = hotel.checkAvailability();

hotel.png

Create and access objects constructor notation

To get a better idea of why you might want to create multiple objects on the same page, here is an example that shows room availability in two hotels. First, a constructor function defines a template for the hotels. Next, two different instances of this type of hotel object are created. The first represents a hotel called Quay and the second a hotel called Park. Having created instances of these objects, you can then access their properties and methods using the same dot notation that you use with all other objects.

In this example, data from both objects is accessed and written into the page. (The HTML for this example changes to accommodate the extra hotel.) For each hotel, a variable is created to hold the hotel name, followed by space, and the word rooms.

The line after it adds to that variable with the number of available rooms in that hotel. (The+= operator is used to add content to an existing variable.)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>multiple objects</title>
    <link rel="stylesheet" href="css/c03.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit&display=swap" rel="stylesheet">

</head>
<body>
    <h1>Hotel Availability</h1>
    <div class="content">
        <div id="hotel1">hotel1 rooms: </div>
        <div id="hotel2">hotel2 rooms: </div>
    </div>
    <script src="js/multiple-objects.js"></script>
</body>
</html>
function Hotel(name, rooms, booked) {
    this.name = name;
    this.rooms = rooms;
    this.booked = booked;
    this.checkAvailability = function () {
        return this.rooms - this.booked;
    };
}

var quayHotel = new Hotel('Quay', 40, 25);
var parkHotel = new Hotel('Park', 120, 77);

var details1 = quayHotel.name + " rooms: ";
details1 += quayHotel.checkAvailability();
var elHotel1 = document.getElementById('hotel1');
elHotel1.textContent = details1;

var details2 = parkHotel.name + ' rooms: ';
details2 += parkHotel.checkAvailability();
var elHotel2 = document.getElementById('hotel2');
elHotel2.textContent = details2;

hotel.png