The reason for this is because null caused by a variable that doesn't matter, so when converting to JSON it gives you JSON that doesn't matter, undefined means it doesn't exist at all, so you can't create a JSON object of what doesn't exist. Just check
if(typeof myvar === 'undefined')
before starting and handling the error in the code. As a rule, try to avoid undefined in your JS, they can create strange things everywhere and do NOT match null and are usually handled differently.
source share