DEV Community

loading...

bind(), apply() and call() me maybe: Pt. 2

arynnboniface profile image Ronnie ・1 min read

Last week, I covered bind() and this week I'll be going over apply().

First thing, this is how JavaScript's MDN describes apply():

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
Enter fullscreen mode Exit fullscreen mode

Let's say you just got a new job. There are a lot of new people to meet, so let's write some code that will make introducing yourself to everyone a little bit easier:

let aboutMe = {
  firstName: "Joe",
  lastName: "Coder",
  job: "web developer"
}

function sayHello(greeting, message) {
  return `${greeting}. I'm ${this.firstName} and I'm a 
  ${this.job}. ${message}`
}

let introduction = sayHello.apply(aboutMe, ["Hello!", "It's nice to meet you!"])

console.log(introduction)
// returns "Hello! I'm Joe and I'm a web developer. It's nice to meet you!"
Enter fullscreen mode Exit fullscreen mode

Can you guess what happens without apply?

let introduction = sayHello(aboutMe, ["Hello!", "It's nice to meet you!"])

console.log(introduction)

// returns [object Object]. I'm undefined and I'm a undefined. Hello!,It's nice to meet you!

Enter fullscreen mode Exit fullscreen mode

It's a good thing we remembered to use apply() or that would have been embarrassing.

That sounds pretty similar to bind(), but remember: bind() creates a new function and apply() does not. If we were to try: console.log(introduction()) we would get an error that looks something like this: TypeError: introduction is not a function

apply() is similar to call(), which we'll be covering next week!

Discussion (0)

pic
Editor guide