WebDevNote.io

WebDevNote.io

Defining JavaScript Methods

Defining JavaScript Methods

JavaScript Methods are simply functions used as properties within an Object.

Here's an example;

const calcObject = {
    add(num,num2){
        return num + num2
    },
    sub(num,num2){
        return num - num2
    },
    squ(num){
        return num * num
    },
    div(num, num2){
        return num / num2
    }
}
// OUTPUTS examples

calcObject.add(8,9)
17
calcObject.sub(18,9)
9
calcObject.squ(4)
16
calcObject.div(14,2)
7

We have written the functions using the shorthand style

We could also write it like this;

const calcObject = {
    add: function (num,num2){
        return num + num2
    },
    sub: function (num,num2){
        return num - num2
    },
    squ: function (num){
        return num * num
    },
    div: function (num, num2){
        return num / num2
    }
}

//OUTPUT will be the same as the previous code, if called with the same parameters in the example.
calcObject.add(8,9)
17
calcObject.sub(18,9)
9
calcObject.squ(4)
16
calcObject.div(14,2)
7

This is method in JavaScript.

It's very simple. You learn to swim by watching people swim and most importantly, trying it out yourself, you learn to code by practicing coding also. Goodluck.

#javascript#codenewbies#learn-coding#objects
 
Share this