How to convert a string to a boolean value in JavaScript correctly?
Hello everyone! I'm just starting to learn JavaScript and ran into a problem. I have a string that comes from the server or from a form. It can be `"true"` or `"false"`. I need to convert it into an actual boolean value `true` or `false` to use in conditions.
I tried this code:
```javascript
let str = "false";
let bool = Boolean(str);
console.log(bool); // outputs true
```
But `Boolean("false")` returns `true`! This confuses me. I thought the string `"false"` should become `false`. I also tried double negation:
```javascript
let str = "false";
let bool = !!str;
console.log(bool); // also true
```
And that doesn't work either. I understand that an empty string `""` gives `false`, and any non-empty string gives `true`. But I need the string `"false"
No answers yet.
Log in to leave an answer
Blogs
Go for Machine Learning: Capabilities, Examples, and Limitations