DEV Community

Cover image for TypeError: JavaScript
Saif Sadiq for LambdaTest

Posted on • Edited on • Originally published at lambdatest.com

TypeError: JavaScript

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.

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

var num=1;
i.toUpperCase();

Error

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.

var num = 1;
try {

    num.toString().toUpperCase();   // Convert number into string first 
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
}

Output: 1

2. Using constructor new String() of predefined class

var num = 1;
num=new String(num);
try {

    num.toUpperCase();   // You cannot convert a number to upper case
}
catch(err) {
    console.log(err.name);
}

Output: 1

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

TypeError related to console.log()

TypeError: Property 'log' of object # is not a function (Chrome) 
TypeError: console.log is not a function (Firefox)
TypeError: 'your string' is not a function (evaluating 'console.log("your string")') (Safari)
TypeError: Function expected (IE)

TypeError related to prompt()

TypeError: Property 'prompt' of object [object Object] is not a function (Chrome)
TypeError: prompt is not a function (Firefox)
TypeError: 'a string, this could vary' is not a function (evaluating 'prompt("your question")') (Safari)
TypeError: Function expected (IE)

TypeError related to confirm()

TypeError: Property 'confirm' of object [object Object] is not a function (Chrome)
TypeError: confirm is not a function (Firefox)
TypeError: 'a string, this could vary' is not a function (evaluating 'confirm("your question")') (Safari)
TypeError: Function expected (IE)

Original Source: lambdatest.com

Top comments (7)

Collapse
 
jreina profile image
Johnny Reina

You can add 1 and 'H' in JS. The 1 gets coerced to a string and the result is '1H'.

Also, the Cannot set property 'innerHTML' of null error has nothing to do with the type of the num variable. document.getElementById("demo") is returning null in this case and setting properties on null throws a TypeError.

Collapse
 
vyzaldysanchez profile image
Vyzaldy Andrés Sanchez

Yes, you're right.adding a number with an integer will result in JS triggering implicit coercion which will convert the number into string and it will perform concatenation instead. No errors thrown.

Collapse
 
saifsadiq1995 profile image
Saif Sadiq

Thanks Vyzaldy for bringing this to me. I'll look into it.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

What he said 👆

Collapse
 
saifsadiq1995 profile image
Saif Sadiq

Hi Johnny, I got your point. It was my bad.

Collapse
 
ernestasdob profile image
Ernestas

Suggesting that javascript works on the "obvious answer" principle is quite dangerous.

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Please note that new String() is a wrong and dangerous answer as it returns a String object and not a string. Much better is the String() static method, that just calls .toString() on the argument.

{
const obj = {toString:()=>"YOWZA", valueOf: Math.random}
let a
const examples = `String(0)
new String(0)
typeof String(0)
typeof new String(0)
!!String("")
!!new String("")
String(0)==="0"
new String(0)==="0"
String(obj)
new String(obj)
Number("0")
new Number("0")
typeof Number("0")
typeof new Number("0")
!!Number("0")
!!new Number("0")
Number("0") === 0
new Number("0") === 0
Number(obj)
new Number(obj)
Boolean(false)
new Boolean(false)
typeof Boolean(false)
typeof new Boolean(false)
!!Boolean(false)
!!new Boolean(false)
(a = Number(), a.b=a, a.b)
(a = new Number(), a.b=a, a.b)`
.split('\n')
const maxLen = Math.max(...examples.map(x => x.length))
examples.forEach(line => console.log(line.padEnd(maxLen)," => ",eval(line)))
}

Above are just a few examples of how this will get you.

Or, non-executably:

const obj = {toString:()=>"YOWZA", valueOf: Math.random}

String(0)                 // "0"
new String(0)             // String{"0"}

typeof String(0)          // string
typeof new String(0)      // object

!!String("")              // false
!!new String("")          // true

String(0)==="0"           // true
new String(0)==="0"       // false

String(obj)               // "YOWZA"
new String(obj)           // String{"YOWZA"}

Number("0")               // 0
new Number("0")           // Number{0}

typeof Number("0")        // number
typeof new Number("0")    // object

!!Number("0")             // false
!!new Number("0")         // true

Number("0") === 0         // true
new Number("0") === 0     // false

Number(obj)               // 0.42685934002722714
new Number(obj)           // Number{0.644528120927234}

Boolean(false)            // false
new Boolean(false)        // Boolean{false}

typeof Boolean(false)     // boolean
typeof new Boolean(false) // object

!!Boolean(false)          // false
!!new Boolean(false)      // true

const a1 = Number()
a1.b = a1
a1.b                      // undefined
const a2 = Number()
a2.b = a2
a2.b                      // Number {0, b: Number {0, b: Number{...}}}