Jump to content

Cannot Determine is Variable is "undefined"


gw1500se
 Share

Recommended Posts

I an trying to determine if a cookie exists using the following code:

const json_str=Cookies.get("Auto_Select_051969");
if (!(json_str in window)) {
    create_cookie();
    json_str=Cookies.get("Auto_Select_051969");
}
json=JSON.parse(json_str);

When it gets to the parse I get the error:

Uncaught SyntaxError: "undefined" is not valid JSON
    at JSON.parse (<anonymous>)
    at cookie_mgmt.js:16:11

'create_cookie()' is not executed. If 'json_str' is undefined, per the error, how can it fail the 'if' test?

I also tried:

if (typeof(json_str)=="undefined") {

Which also fails the 'if' test.

Edited by gw1500se
Link to comment
Share on other sites

I finally got it working but I can't explain how/why. I did:

console.log(typeof(json_str)=="undefined");

The output was "true" which I expected. I then edited the line by changing 'console.log' to 'if' and changed the ';' to '{' and the thing started to work. :confused:

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.