JavaScript Methods and Functions


JavaScript Methods and Functions Interview with follow-up questions

1. What is the difference between a method and a function in JavaScript?

A method is just a function stored as a property of an object; a function is the standalone callable. The mechanics are identical — the real difference is how this binds when you call it.

const user = {
  name: "Ada",
  greet() {           // method — `this` is the calling object
    return `Hi, ${this.name}`;
  },
};

user.greet(); // "Hi, Ada"  → `this` is `user`

The follow-up interviewers are really after is this:

  • Called as obj.method(), this is obj. Called as a bare function, this is undefined in strict mode (or the global object in sloppy mode).
  • Detaching a method loses its receiver — const g = user.greet; g(); breaks because this is no longer user. Fix with user.greet.bind(user).
  • Don't define a method as an arrow function if it needs this — arrows take this lexically from the surrounding scope, not the calling object, so this.name would be undefined.

So "method vs function" is mostly terminology; the substance is this resolution.

↑ Back to top

Follow-up 1

Can methods be used without a specific object in JavaScript?

No, methods cannot be used without a specific object in JavaScript. Methods are defined as properties of objects and are meant to be called on those objects. If you try to call a method without an object, you will get an error.

Follow-up 2

Can you give an example of a method and a function?

Sure! Here's an example of a method in JavaScript:

const person = {
  name: 'John',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};

person.sayHello(); // Output: Hello, John

And here's an example of a function:

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

console.log(addNumbers(2, 3)); // Output: 5

Follow-up 3

How are methods and functions called in JavaScript?

Methods are called using the dot notation, where the method is invoked on a specific object. For example:

const person = {
  name: 'John',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};

person.sayHello(); // Output: Hello, John

Functions are called by simply using their name followed by parentheses and passing any required arguments. For example:

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

console.log(addNumbers(2, 3)); // Output: 5

Follow-up 4

What is the 'this' keyword in the context of a method?

In the context of a method, the 'this' keyword refers to the object that the method belongs to. It allows the method to access and manipulate the properties of the object. For example:

const person = {
  name: 'John',
  sayHello: function() {
    console.log('Hello, ' + this.name);
  }
};

person.sayHello(); // Output: Hello, John

In this example, 'this.name' refers to the 'name' property of the 'person' object.

Follow-up 5

Can functions be methods in JavaScript?

Yes, functions can be methods in JavaScript. When a function is assigned as a property of an object, it becomes a method of that object. The function can then be called using the dot notation on the object. Here's an example:

const calculator = {
  add: function(a, b) {
    return a + b;
  }
};

console.log(calculator.add(2, 3)); // Output: 5

In this example, the 'add' function is a method of the 'calculator' object.

2. How do you define a function in JavaScript?

There are three common ways to define a function, and interviewers expect you to contrast them:

// 1. Function declaration — hoisted
function add(a, b) {
  return a + b;
}

// 2. Function expression — assigned to a variable
const sub = function (a, b) {
  return a - b;
};

// 3. Arrow function — concise, lexical `this`
const mul = (a, b) => a * b;

Key points:

  • A declaration is fully hoisted, so it can be called before it appears. An expression or arrow is only available after its const/let binding runs (TDZ before that).
  • Arrow functions have no own this, arguments, or super, and can't be used with new — ideal for callbacks, wrong for object methods and constructors.
  • All forms support default (a = 0) and rest (...args) parameters.
  • Other forms exist for specific needs: class methods, async function, generators (function*), and the immediately-invoked (() => {})() pattern.
↑ Back to top

Follow-up 1

What is a function declaration?

A function declaration is a way to define a named function using the function keyword followed by the function name, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces. Here's an example:

function greet(name) {
    console.log('Hello, ' + name + '!');
}

Follow-up 2

What is a function expression?

A function expression is a way to define a function as a value assigned to a variable or a property of an object. It can be either anonymous or named. Here's an example of an anonymous function expression:

var greet = function(name) {
    console.log('Hello, ' + name + '!');
};

And here's an example of a named function expression:

var greet = function sayHello(name) {
    console.log('Hello, ' + name + '!');
};

Follow-up 3

Can you give an example of a function declaration and a function expression?

Sure! Here's an example of a function declaration:

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

And here's an example of a function expression:

var multiply = function(a, b) {
    return a * b;
};

Follow-up 4

What is the difference between a function declaration and a function expression?

The main difference between a function declaration and a function expression is that function declarations are hoisted, while function expressions are not. Hoisting is a JavaScript behavior where function declarations are moved to the top of their containing scope during the compilation phase, allowing them to be called before they are defined. Function expressions, on the other hand, are treated like any other variable assignment and are not hoisted.

Follow-up 5

What is hoisting in the context of function declarations?

Hoisting is a JavaScript behavior where function declarations are moved to the top of their containing scope during the compilation phase. This means that you can call a function before it is defined in the code. Here's an example:

sayHello('John');

function sayHello(name) {
    console.log('Hello, ' + name + '!');
}

In this example, the sayHello function is called before it is defined, but it still works because of hoisting.

3. What are arrow functions in JavaScript?

Arrow functions (ES6) are a compact syntax for function expressions. They drop the function keyword and, with a single expression body, return implicitly:

const square = (x) => x * x;
const add = (a, b) => a + b;
const greet = () => "hi";
const makePoint = (x, y) => ({ x, y }); // wrap object literals in ()

But the syntax isn't the point interviewers care about — the semantic differences are:

  • No own this: an arrow captures this from the enclosing lexical scope. This makes them perfect for callbacks (arr.map(x => this.transform(x)) inside a class) but wrong as object methods or anything relying on a dynamic this.
  • No own arguments: use rest params ((...args) => …) instead.
  • Can't be a constructor: calling new on an arrow throws; they have no prototype.
  • They can't be generators and shouldn't be used where hoisting matters (they aren't hoisted like declarations).

So reach for arrows for short callbacks and lexical-this situations; use a regular function for methods, constructors, and dynamic this.

↑ Back to top

Follow-up 1

How does the syntax of an arrow function differ from a regular function?

The syntax of an arrow function differs from a regular function in a few ways:

  1. Arrow functions do not have their own 'this' value. They inherit the 'this' value from the enclosing lexical scope.
  2. Arrow functions do not have the 'arguments' object.
  3. Arrow functions do not have a 'prototype' property.
  4. Arrow functions cannot be used as constructors with the 'new' keyword.

Follow-up 2

Can you give an example of an arrow function?

Sure! Here's an example of an arrow function:

const add = (a, b) => a + b;

Follow-up 3

What is the difference in the 'this' keyword for arrow functions and regular functions?

In regular functions, the value of 'this' is determined by how the function is called. It can vary depending on the context in which the function is invoked.

In arrow functions, the value of 'this' is lexically scoped. It is determined by the surrounding scope where the arrow function is defined, and does not change with different function invocations.

Follow-up 4

Can arrow functions be used as methods?

Yes, arrow functions can be used as methods. However, it's important to note that arrow functions do not have their own 'this' value, so they are not suitable for methods that rely on the 'this' context. Arrow functions are best used for simple, self-contained functions.

Follow-up 5

What are the limitations of arrow functions?

Arrow functions have a few limitations:

  1. They cannot be used as constructors with the 'new' keyword.
  2. They do not have their own 'this' value, so they cannot be used for methods that rely on the 'this' context.
  3. They do not have the 'arguments' object.
  4. They do not have a 'prototype' property.

It's important to consider these limitations when deciding whether to use arrow functions in your code.

4. What are higher-order functions in JavaScript?

A higher-order function (HOF) is one that does either or both of: takes a function as an argument, or returns a function. This is possible because functions in JavaScript are first-class — they can be assigned to variables, passed around, and returned like any value.

// Takes a function
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2); // [2, 4, 6]

// Returns a function (a closure)
const multiplier = (factor) => (n) => n * factor;
const triple = multiplier(3);
triple(5); // 15

Follow-ups interviewers expect:

  • The built-in array methods map, filter, reduce, forEach, sort, and some/every are all HOFs — knowing them signals comfort with functional style.
  • HOFs enable closures, currying/partial application, and function composition, plus patterns like debounce/throttle, memoization, and decorators/middleware.
  • The function passed in is a callback; the one returned often captures variables via closure.

They make code more declarative and reusable by letting you parameterize behavior, not just values.

↑ Back to top

Follow-up 1

Can you give an example of a higher-order function?

Sure! Here's an example of a higher-order function in JavaScript:

function multiplyBy(factor) {
  return function(number) {
    return number * factor;
  };
}

const multiplyByTwo = multiplyBy(2);
console.log(multiplyByTwo(5)); // Output: 10

Follow-up 2

What is a callback function?

A callback function is a function that is passed as an argument to another function and is executed inside that function. Callback functions are commonly used with higher-order functions to perform asynchronous operations, handle events, or process data.

Follow-up 3

How are higher-order functions used in JavaScript?

Higher-order functions are used in JavaScript to enable functional programming paradigms, such as passing functions as arguments, returning functions from other functions, and creating function composition. They are also commonly used with array methods like map, filter, and reduce to process collections of data.

Follow-up 4

What are the benefits of using higher-order functions?

Using higher-order functions in JavaScript can lead to more modular and reusable code. They allow for the separation of concerns and enable the composition of smaller functions to create more complex behavior. Higher-order functions also promote code readability and can make asynchronous programming easier to manage.

Follow-up 5

Can you give an example of a built-in higher-order function in JavaScript?

Certainly! One example of a built-in higher-order function in JavaScript is the map method. It is used to create a new array by applying a function to each element of an existing array. Here's an example:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
  return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

5. What is a closure in JavaScript?

A closure is a function bundled together with the variables from the scope where it was defined. It lets an inner function keep accessing its outer function's variables even after that outer function has returned.

function counter() {
  let count = 0;            // private to the closure
  return () => ++count;     // remembers `count`
}

const next = counter();
next(); // 1
next(); // 2

What interviewers probe:

  • Private state / encapsulationcount above can't be touched from outside; this is the module pattern and the basis of data privacy before class #fields.
  • Practical uses: factory functions, memoization, currying, and event/async callbacks that "remember" setup values (debounce, throttle).
  • The classic gotcha: var in a loop shares one binding, so all callbacks see the final value:
  for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
  for (let i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 0 1 2

let creates a fresh binding per iteration — a common "fix the bug" question.

  • Mention memory: closures hold their captured variables alive, so careless long-lived closures can retain more than intended.
↑ Back to top

Follow-up 1

Can you give an example of a closure?

Sure! Here's an example of a closure in JavaScript:

function outerFunction() {
  var outerVariable = 'Hello';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

var closure = outerFunction();
closure(); // Output: Hello

In this example, the inner function innerFunction has access to the outerVariable from its outer function outerFunction, even after outerFunction has finished executing.

Follow-up 2

How are closures used in JavaScript?

Closures are commonly used in JavaScript for various purposes, such as:

  1. Implementing data privacy and encapsulation by creating private variables and functions.
  2. Creating function factories or currying functions.
  3. Implementing asynchronous operations with callbacks.
  4. Managing state in functional programming.

Closures provide a way to maintain access to variables and functions that are no longer in scope, allowing for more flexible and powerful programming patterns.

Follow-up 3

What are the benefits of using closures?

The benefits of using closures in JavaScript include:

  1. Encapsulation and data privacy: Closures allow you to create private variables and functions that are inaccessible from outside the closure, providing a way to encapsulate and hide implementation details.
  2. Persistent state: Closures can retain the values of variables even after the outer function has finished executing, allowing for persistent state across multiple function calls.
  3. Function factories: Closures can be used to create functions with pre-configured settings or parameters, making it easy to create reusable function factories.
  4. Asynchronous operations: Closures are commonly used with callbacks to handle asynchronous operations, allowing for more readable and maintainable code.

Overall, closures provide a powerful tool for creating modular and flexible code in JavaScript.

Follow-up 4

What is the scope chain in the context of closures?

The scope chain in the context of closures refers to the hierarchy of scopes that a closure has access to. When a function is defined, it has access to its own scope, the scope of the outer function, and the global scope. This forms a chain of scopes, where each scope has access to its parent scope.

When a closure is created, it retains a reference to its outer function's scope, allowing it to access variables and functions from that scope even after the outer function has finished executing. If a variable is not found in the immediate scope, the closure will look up the scope chain until it finds the variable or reaches the global scope.

Understanding the scope chain is important when working with closures, as it determines which variables and functions are accessible within a closure.

Follow-up 5

Can closures be used to create private variables in JavaScript?

Yes, closures can be used to create private variables in JavaScript. By defining variables within the scope of an outer function, those variables are not accessible from outside the function. However, any inner functions defined within the outer function have access to these variables, creating a closure.

Here's an example:

function createCounter() {
  var count = 0;

  return {
    increment: function() {
      count++;
    },
    decrement: function() {
      count--;
    },
    getCount: function() {
      return count;
    }
  };
}

var counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getCount()); // Output: 2

In this example, the count variable is encapsulated within the createCounter function, and the inner functions increment, decrement, and getCount have access to this private variable through the closure.

6. How is the value of `this` determined in JavaScript?

A core gotcha question. For a regular function, this is decided by how the function is called (the call-site), not where it's defined. The rules, in priority order:

  1. new bindingnew Foo() sets this to the freshly created object.
  2. Explicit bindingcall/apply/bind set this to the object you pass.
  3. Implicit bindingobj.method() sets this to obj (the thing left of the dot).
  4. Default — a plain fn() call gives undefined in strict mode (or the global object in sloppy mode).
const obj = {
  name: 'A',
  greet() { return this.name; },
};
const g = obj.greet;
obj.greet(); // 'A'  — implicit
g();         // undefined — lost `this` (classic bug)
g.call(obj); // 'A'  — explicit

Key contrast: arrow functions ignore all of this — they capture this lexically from the enclosing scope and can't be rebound. That's why arrows are great for callbacks (they keep the outer this) but wrong for object methods that need dynamic this. call vs apply differ only in how args are passed (list vs array); bind returns a new permanently-bound function.

↑ Back to top

Live mock interview

Mock interview: JavaScript Methods and Functions

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.