What is the difference between call and apply in JavaScript? When to use which?
Hello everyone! I started learning JavaScript and came across the call and apply methods. I understand that both allow calling a function with a specified context (the value of this), but I can't grasp the fundamental difference between them.
Let's say I have a simple object and a function:
```javascript
const person = {
firstName: 'Ivan',
lastName: 'Petrov'
};
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.firstName} ${this.lastName}${punctuation}`);
}
```
I can call this function using call:
```javascript
greet.call(person, 'Hello', '!'); // Hello, Ivan Petrov!
```
And using apply:
```javascript
greet.apply(person, ['Hello', '!']); // Hello, Ivan Petrov!
```
The result is the same. I read that the difference is in how arguments are passed: