Program Like A Pro: Better Ways of Using the Call and Apply Function in JavaScript

John Ali
2 min readMay 5, 2023

--

The `call` and `apply` functions are powerful tools in JavaScript that allow you to change the context of the `this` keyword and pass arguments to a function. Here are some tips on how to use them like a pro:

Using call()

The `call()` method invokes a function with a specified `this` value and arguments provided individually. Here’s an example:

function greet(name) {
console.log(`Hello, ${name}! My name is ${this.name}.`);
}

const person = { name: 'John' };
greet.call(person, 'Jane');

In this example, the `call()` method is used to invoke the `greet()` function with the `person` object as the `this` value and `’Jane’` as the argument.

Tips for using call()

- The first argument passed to `call()` is the value of `this` inside the function.
- The remaining arguments are the arguments to be passed to the function.
- You can use `null` or `undefined` as the `this` value if you don’t need to set it.
- You can use `call()` to invoke functions with a specific `this` value, even if they don’t belong to that object.

Using apply()

The `apply()` method is similar to `call()`, but the arguments are passed as an array. Here’s an example:

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

const numbers = [2, 3];
const result = sum.apply(null, numbers);
console.log(result);

In this example, the `apply()` method is used to invoke the `sum()` function with `null` as the `this` value and `[2, 3]` as the arguments.

Tips for using apply()

- The first argument passed to `apply()` is the value of `this` inside the function.
- The second argument is an array of arguments to be passed to the function.
- You can use `apply()` to invoke functions with a specific `this` value, even if they don’t belong to that object.
- If the function doesn’t take any arguments, you can pass an empty array as the second argument.

Conclusion

The `call()` and `apply()` methods are powerful tools in JavaScript that allow you to change the context of `this` and pass arguments to a function. By using them correctly, you can write more flexible and efficient code.

--

--

John Ali
John Ali

Written by John Ali

Versatile Content Creator & Tech Enthusiast: DevSecOps, Machine Learning, Software Engineering, Backend & Frontend Development, Data Engineering

No responses yet