DEV Community

Sudhakar V
Sudhakar V

Posted on

🔁 JavaScript Functions and Methods with return

🧠 1. Function – What is it?

A function is a reusable block of code that performs a task.

Syntax:

function functionName(parameters) {
  // code
  return result;
}
Enter fullscreen mode Exit fullscreen mode

📌 Example:

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

let result = add(5, 3);  // result = 8
console.log(result);
Enter fullscreen mode Exit fullscreen mode

🔁 2. Return Statement

  • return gives back a value from the function.
  • It exits the function immediately.
function greet(name) {
  return "Hello, " + name;
}

console.log(greet("Sudhakar"));  // Hello, Sudhakar
Enter fullscreen mode Exit fullscreen mode

🧰 3. Method – What is it?

A method is a function that belongs to an object.

Syntax:

let obj = {
  methodName: function() {
    return "I'm a method";
  }
};
Enter fullscreen mode Exit fullscreen mode

📌 Example:

let person = {
  firstName: "Sudhakar",
  greet: function() {
    return "Hello, " + this.firstName;
  }
};

console.log(person.greet());  // Hello, Sudhakar
Enter fullscreen mode Exit fullscreen mode

⚡ Quick Comparison

Concept Description Example
Function Reusable block of code function sum(a, b) { return a + b; }
Method Function inside an object person.greet = function() { ... }

💡 More Examples

➤ Arrow Function with Return:

const multiply = (x, y) => x * y;
console.log(multiply(4, 3)); // 12
Enter fullscreen mode Exit fullscreen mode

➤ Function Returning Another Function:

function outer() {
  return function inner() {
    return "I'm inner";
  };
}

let innerFunc = outer();
console.log(innerFunc());  // I'm inner
Enter fullscreen mode Exit fullscreen mode

Top comments (0)