Is there any way to detect/prevent auto casting in JavaScript(native or library)? For example, DOM output as [object Object].
Asked
Active
Viewed 226 times
0
-
Possible duplicate of [Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?](https://stackoverflow.com/questions/6307514/is-it-possible-to-override-javascripts-tostring-function-to-provide-meaningfu) – Dat Pham May 07 '19 at 01:38
-
Please include some code to demonstrate the behavior you're alluding to. I'm not entirely clear how `[object Object]` represents "auto casting", so an example would certainly help. :) – Tyler Roper May 07 '19 at 01:56
-
@TylerRoper I'll try to find out. I actually don't know myself because I am working with some old code that needs fixing up. [object Object] being outputted as a string is something I have come across from time to time and generally, I would rather that this is always thrown as an error. – Damien Golding May 07 '19 at 02:05
-
@DatPham Seems like that could be the way to go. Is there a way to know if the casting was done automatically(Not done by user)? – Damien Golding May 07 '19 at 02:13
-
@DamienGolding Depend on what do you mean by "not done by user". If it means native or built in of javascript then maybe use a function that detects if `toString` function of an object is native (not done by user) or not. https://davidwalsh.name/detect-native-function and use it like this: `isNative([your object].toString)` – Dat Pham May 07 '19 at 03:38
1 Answers
0
When comparing variables, use the triple equals (===
) operator which will check both variable type and value.
let foo = '604';
let bar = 604;
// Compare value
console.log(foo == bar);
// Compare type and value
console.log(foo === bar);

Miroslav Glamuzina
- 4,472
- 2
- 19
- 33