TypeError: JavaScript
If you're trying to learn to code in JavaScript, the vague TypeErrors can make you want to pull out your hair. But don't, we're here to help.
Join the DZone community and get the full member experience.
Join For FreeCan you add a number and a letter together?
If I ask you to give me the result of the addition of 1 plus H
will you be able to give me the answer?
The obvious answer is NO.
The same goes in JavaScript! If you add 1 and H in JavaScript or when you try to perform operations on two operands of unmatched types, JavaScript throws a TypeError
.
Per MDN: ‘A TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function.’
Therefore, it becomes necessary to make sure the variables must have the same data types before performing any operation. Type mismatch generates an error while executing the whole program.
Types of TypeErrors
For example, you will get Uncaught TypeError
if you are trying to convert a number to an uppercase character. As toUpperCase()
is a function to convert a string to uppercase characters, it will throw an error for following code structure.
Code structure
|
Error
How to Get Rid of This Uncaught Type Error: Cannot Set a Property
There are many methods possible to overcome this error.
1. Using the toString() Function
You can use the toString()
function to convert a number into a string first and then you can convert that string to upper case characters using the toUpperCase()
function.
|
Output
"1"
2. Using Constructor New String() of a Predefined Class
|
Output
|
Here are few more TypeErrors that can be thrown by JavaScript in different browsers.
TypeError Related to console.log()
|
TypeError Related to prompt()
|
TypeError Related to confirm()
|
Published at DZone with permission of Saif Sadiq, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments