DEV Community

Cover image for Understanding methods and functions in JavaScript
Jibril Dauda Muhammad
Jibril Dauda Muhammad

Posted on

Understanding methods and functions in JavaScript

Chances are if you are learning JavaScript or using it for development you definitely have make use of the popular console.log() method, which is use to output message on the console. in this place console is the object, while log is a function inside the console object

Lets dive into the differences between functions and methods

What is a function:

A function is a set of instructions that you can use over and over again in JavaScript. It's like a recipe that tells your code how to do something. You can give the function a name, and then call it whenever you want to use those instructions.

function addValue(a, b) {
  return a + b;
}

console.log(addValue(3, 4)); // Output: 7

Enter fullscreen mode Exit fullscreen mode

the function addValue accepts two parameters a and b, and returns their sum.

What is a method:

A method is a special tool in JavaScript that can be used to make objects do something. It's like a button that you can press to make a toy do a specific action. Each object has its own set of methods that you can use to control it. In a lay mans term They are function inside object

const employee= {
  username: "mdjibril",
  developer: "fullstack developer",
  sayHello: function() {
    console.log("Hello, my username is " + this.username + " and I am a " + this.developer);
  }
};

employee.sayHello(); // Output: "Hello, my username is mdjibril and I am a fullstack developer."

Enter fullscreen mode Exit fullscreen mode

In this example, sayHello is a method attached to the employee object. It logs a message to the console that includes the object's username and developer properties.

In summary, functions are standalone blocks of code that can be called from anywhere in your code, while methods are functions attached to objects that can be called on those objects.

More Example

Function to check if a number is even

function isEven(number) {
  if (number % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

console.log(isEven(4)); // Output: true
console.log(isEven(5)); // Output: false

Enter fullscreen mode Exit fullscreen mode

method to convert a string to uppercase

const myString = "hello world";

const upperCaseString = myString.toUpperCase();

console.log(upperCaseString); // Output: "HELLO WORLD"

Enter fullscreen mode Exit fullscreen mode

that's a wrap, hope this clear the understanding between methods and function for you.

Top comments (0)