DEV Community

Cover image for Avoid toString() Fatal Error [String Casting in JavaScript]

Posted on

Avoid toString() Fatal Error [String Casting in JavaScript]

Hey welcome! I made this YouTube video on how you can convert any value to a string in JavaScript and thought of posting it here. We are going to understand the nature of JavaScript strings along with the toString method of converting different value types to strings. Later at the end of the video, we will have an in-depth look at string casting in JavaScript and how you can avoid fatal errors that might occur using the toString function. So let's get started!

If you want access to the source code to this video or need to follow along, you can easily do so by using the link to CodeSandbox given in the description below. If you are watching this on Instagram you can access the description by double-tapping on the title of the video. I also have a link to my Discord server and you can post your questions there and I would certainly answer them for you.

Alright, let's get started! Now strings in JavaScript are primitive types and are immutable. By being immutable what I mean is that once a string is created its value cannot be changed. Let's try to understand this with an example. Let me start by declaring a variable over here.

let language = 'Java';
Enter fullscreen mode Exit fullscreen mode

Now I am going to assign another string value to this variable.

language = language + 'Script';
Enter fullscreen mode Exit fullscreen mode

Here I am just concatenating the previous value of the language variable which is Java with another string Script so that the variable value now reads as JavaScript. Let's print the value of the language variable to the console and see what we get. So as expected this is printing the complete word JavaScript to the console. But, even though you used concentration to append the string Script to the initial value Java, JavaScript in the background created a new string JavaScript first and then deleted the previous string Java. The deletion of the string is the last process that is performed by JavaScript. This is because the strings in JavaScript are immutable. Looking at this example it might look like a simple process of just adding a new piece to the previous value, but that is not the case. It's really important to understand this concept because whether a value type is mutable or not holds a lot of importance when you are working with complex applications, especially in React.

Let's look at another tricky part related to strings. This happens when you are trying to

convert another value to a string. Let me declare a variable over here and call it a number and set the value of the variable to 15.

let number = 15;
Enter fullscreen mode Exit fullscreen mode

I will convert this number to a string and log the number to the console. I will also log the typeof number to console to ensure that it has been converted to a string.

number = number.toString();
console.log(typeof number);
Enter fullscreen mode Exit fullscreen mode

Now, this is a normal practice in JavaScript and you will use toSting method quite often to convert values to strings. But, there is a problem here. Let us suppose that the value of the variable is of the type null or undefined. This might happen in case of a function not returning a value or a null value in an object property being returned by the API, or any other reason. Let's see what happens when the variable is undefined. I will declare a new variable and will now assign it any value. Now let's log the value to the console and see what we get.

let variable;
Enter fullscreen mode Exit fullscreen mode

Our variable returns undefined and that's what we expected. Now let's try to call the toString method on this variable and see what happens.

Enter fullscreen mode Exit fullscreen mode

See we get an error. You see toString will always throw an error if the value you are trying to convert to string is either null or undefined. Now, this might throw an error in production especially if you have not tested your code for all edge cases. Not there would be a lot of solutions while you are writing production-ready code which would involve including this in a conditional statement or using strict type checking using TypeScript. Since we are talking about string let's look at a simple solution which if implemented will at least not throw an error in production.

The solution here is to use the String() casting function rather than using the most commonly used toString() function. Let's see how it works. I will declare a few more variables of different value types.

let boolean = true;
let nullType = null;
let num = 25;
Enter fullscreen mode Exit fullscreen mode

You can use String casting with the String method with a capital S like so.

Enter fullscreen mode Exit fullscreen mode

I will go ahead and convert the rest of the variables to strings as well to see what value is returned by each one of them:

Enter fullscreen mode Exit fullscreen mode

Let's see our console to check what we have got. Now you will notice the String function does not throw an error if the value is undefined or null. Instead, it converts them into the literal text of each of those values. This as I said is not the ideal solution but at least would avoid fatal errors in production if any of the values that you are trying to convert turns out to be null or undefined.

That's it from this tutorial. If you liked this please consider following me on Instagram as I keep posting tutorials like these on my page. Please consider giving a like to the video as well as it helps a lot with the Instagram algorithm. I will see you again in the next one, till then cheers!

Discussion (0)