4
var hello = 'null';

How do I remove the quotes so var hello will truly equal null (and not a string)? I'm curious on how to do this without using JSON.parse.

12
  • 1
    You don't. You test your value, and assign accordingly. A counter-question would be "what do you think you would concretely use this for?" because it's a good bet that what you're trying to do has a better way to do it. Commented Jun 30, 2018 at 1:28
  • Type in var hello = null;? Or do something like: var hello = 'null'; var bar = hello === 'null' ? null : hello;? Commented Jun 30, 2018 at 1:29
  • 1
    'null' is a string. It doesn't have any quotes, you can't remove them. How did you get this value? Further, what's wrong with JSON.parse? Commented Jun 30, 2018 at 1:29
  • The delete key? Commented Jun 30, 2018 at 1:30
  • 1
    There is something really wrong with your JSON. The stringify JSON should look something like this '{"someObj":null}' and not '{"someObj":"null"}' Commented Jun 30, 2018 at 1:40

3 Answers 3

3

Without JSON.parse, you cannot.

You can evaluate hello and alter its value later on in the code, which is much more real-world scenario.

hello = hello === 'null' ? null : hello
Sign up to request clarification or add additional context in comments.

Comments

0

Assign null, I've just done this:

var a=1;
console.log(a);
a=null;
console.log(a);
console.log(a===null);

Results:

1
null
true

Though, null in JS is also a value.

Comments

0

You could eval or parse it from JSON (but eval is a terrible approach, I only mention it for the sake of this specific example). Like,

var hello = JSON.parse('null');
console.log(hello === null);

1 Comment

eval for this is a sure-fire way to a disaster later on. Your answer should list the caveats of such an approach, if you're suggesting it.

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.