TypeError: JavaScript

Saif Sadiq

Posted On: April 6, 2018

view count20945 Views

Read time2 Min Read

Can you add a number and an alphabet?

Say, if I ask you to give me the result of the addition of 1 and H will you be able to give me the answer?

The obvious answer is NO.

Same goes in JavaScript too!If you add 1 and H in JavaScript or when you try to perform operations on two operands of unmatched type, JavaScript throws a TypeError.

So, you can say in technical terms that ‘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 variables must have same data types before performing any operation.Type mismatch generates an error while executing the whole program.

Types of TypeError

For example, you will get Uncaught TypeError if you are trying to convert a number to uppercase character. As toUpperCase() is a function to convert a string to uppercase characters.It will give an error for following code structure.

Code structure

Error

How to get rid of this Uncaught type error: Cannot set property

There are many methods possible to overcome this error.

1.Using toString() function

You can use toString() function to convert number into string first and then you can convert that string to upper case characters using toUpperCase() function.

Output

2. Using constructor new String() of predefined class

Output

Here are few more TypeError that can be thrown by JavaScript in different browsers.

TypeError related to console.log()

TypeError related to prompt()

TypeError related to confirm()

Author Profile Author Profile Author Profile

Author’s Profile

Saif Sadiq

Saif Sadiq is a Product Growth specialist at LambdaTest and Growth Marketer.

Blogs: 12



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free