javascript toString and call

What are javascript toString and call methods?

JavaScript is a programming language that allows developers to manipulate data in various ways. It provides many built-in methods that help developers to perform different operations. Two of these methods are the toString() and call() methods.

The toString() Method

The toString() method is a built-in method in JavaScript that converts a value to a string. This method can be used on any type of data, such as numbers, strings, booleans, and objects. When called on a number, for example, the method will return the number as a string:


var num = 10;
console.log(num.toString()); // "10"
    

It is also possible to pass a radix parameter to the toString() method to specify the base of the number system to be used:


var num = 10;
console.log(num.toString(2)); // "1010"
    

This will convert the number to its binary representation.

The call() Method

The call() method is another built-in method in JavaScript that allows you to call a function with a specified this value and arguments provided individually. This method can be used to invoke a function with a different object as the this value:


var obj1 = {name: "John"};
var obj2 = {name: "Jane"};

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

sayHello.call(obj1); // "Hello, John!"
sayHello.call(obj2); // "Hello, Jane!"
    

In the example above, we define two objects, obj1 and obj2, and a function, sayHello(), that uses the this value to access the name property of the object. We then use the call() method to invoke the sayHello() function with the obj1 and obj2 objects as the this value, respectively.

The call() method can also be used to pass arguments to the function:


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

console.log(multiply.call(null, 2, 3)); // 6
    

In this example, we call the multiply() function with the null object as the this value and pass two arguments, 2 and 3. The result is 6.

Conclusion

The toString() and call() methods are important built-in methods in JavaScript that allow developers to manipulate data in different ways. By using these methods, developers can convert values to strings and invoke functions with a specified this value and arguments.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe