0

Can anyone help me what this small piece of code is doing in JavaScript? Actually, I am getting data from express server in Json form and when I render my page I want to access that data in my client JavaScript and this solution I got from another question in Stack Overflow (Accessing Express.js local variables in client side JavaScript), but I am not able to understand this syntax.

var local_data =!{JSON.stringify(data)};

I am trying to interpret this but cant understand. I am using handlebars as my template engine.

12
  • Hello, are you sure there are curly braces on the right hand side {JSON.stringify(data)} Commented Feb 17, 2019 at 19:41
  • Exclamation mark simply inverts the result of the right hand side. var local_data = !false; //local_data will be true var local_data = !true; //local_data will be false Commented Feb 17, 2019 at 19:43
  • The code you've should is IMHO not executable. I've tried it multiple times. Could you check this please? Commented Feb 17, 2019 at 19:43
  • 1
    Where did this line come from and are you sure you aren't getting an error from it? The statement doesn't make a lot of sense. If you wanted to create an object, you would use JSON.parse(), not JSON.stingify() and there wouldn't be a need for the {}. Also, the ! in front of the object would always return false as long as a valid object was created. Commented Feb 17, 2019 at 19:43
  • 1
    If you simply want to process the JSON data you are receiving, all you need to do is: let obj = JSON.parse(data);. After that, you will have a JavaScript object and can do whatever you want with it. The code you've shown is nonsensical. Commented Feb 17, 2019 at 20:07

1 Answer 1

3

The question where you took that from code indicates that the code is part of a Jade template. I searched around for this exact line of code and found it referenced here and here, both of which also reference Jade.

In other words, this isn't valid JavaScript, but it is valid Jade. In this case, !{...} are Jade's syntax for unescaped string interpolation.

The equivalent in Handlebars.js is {{{...}}}, so try this:

var local_data = {{{JSON.stringify(data)}}};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.