VândPupăză

Icon

Bine o zis cine o zis cand o zis ce o zis

JavaScript: Keep your sanity with JSON, use parseInt()

I had a recent problem when using some values passed on after a JSON eval(). The situation was simple: compare two numbers out of the JSON then take a course of action based on the result.

Always make sure you are using the correct data type!
If you think you are using numbers, make sure they’re not strings by passing them through either parseInt() or Number() .
You can check for the data type using the JavaScript typeof operator.

The JSON format implies that you send / receive a valid string. So any reference to numeric values might be changed to strings in the process, depending on your JSON’s structure.
Checking for the correct data type will save you a lot of time and it will keep your WTF count to a minimum.

Important note:
eval() is dangerous! It means converting string to script.
This means interpreting and running whatever you pass on to it
(no security checks whatsoever)!

Use eval() only when you are totally in control of what goes into it.
Even then, be cautious!

WTF count
When someone else looks over your script the WTF count can be a good code quality indicator :)

Category: English, JavaScript, Web, Work

Tagged:

2 Responses

  1. vladootz says:

    WTF count is indirect proportional with the quality indicator, right?

Leave a Reply