gw1500se Posted August 25, 2022 Share Posted August 25, 2022 (edited) 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 August 25, 2022 by gw1500se Quote Link to comment https://forums.phpfreaks.com/topic/315234-cannot-determine-is-variable-is-undefined/ Share on other sites More sharing options...
maxxd Posted August 25, 2022 Share Posted August 25, 2022 Have you tried swapping this: !(json_str in window) with this: typeof json_str == "undefined" Quote Link to comment https://forums.phpfreaks.com/topic/315234-cannot-determine-is-variable-is-undefined/#findComment-1599799 Share on other sites More sharing options...
gw1500se Posted August 25, 2022 Author Share Posted August 25, 2022 Yes. With or without the parens, I get the same result. Quote Link to comment https://forums.phpfreaks.com/topic/315234-cannot-determine-is-variable-is-undefined/#findComment-1599816 Share on other sites More sharing options...
gw1500se Posted August 25, 2022 Author Share Posted August 25, 2022 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. Quote Link to comment https://forums.phpfreaks.com/topic/315234-cannot-determine-is-variable-is-undefined/#findComment-1599817 Share on other sites More sharing options...
maxxd Posted August 25, 2022 Share Posted August 25, 2022 Your last post isn't the same code as your first. It's the code I told you to run - the parenthesis have nothing to do with it, it's using typeof result as a comparator, not in window. Quote Link to comment https://forums.phpfreaks.com/topic/315234-cannot-determine-is-variable-is-undefined/#findComment-1599840 Share on other sites More sharing options...
gw1500se Posted August 26, 2022 Author Share Posted August 26, 2022 Except that didn't work either originally. Quote Link to comment https://forums.phpfreaks.com/topic/315234-cannot-determine-is-variable-is-undefined/#findComment-1599852 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.