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
.
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
.
- 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. – Mike 'Pomax' Kamermans 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;
? – user2864740 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 withJSON.parse
? – Adam Jenkins Commented Jun 30, 2018 at 1:29 - The delete key? – Sean F 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"}' – Aman Chhabra Commented Jun 30, 2018 at 1:40
3 Answers
Reset to default 3Without 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
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.
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);