Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript functions where the variable being tested is a string

I’m working on a function that is supposed to check if a variable is equal to "this is a string" when run and logs true or false. This is what I tried:

let e = "this is string"
function stringCheck(){
  if(e = "this is a string"){
    console.log(true)
  } else{
    console.log(false)
  }
}

It didn’t work. It logs ‘true’ even when I make it so e equals something completely different. I tried switching ‘true’ and ‘false’ and that made it so it only logged as ‘false’ no matter what e equaled. I can’t figure out what’s wrong with the code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are making an assignment instead of a comparison in your function. You must use the correct operator. In this case I replaced the single = with a ===:

function stringCheck(){
  if(e === "this is a string"){
    console.log(true)
  } else{
    console.log(false)
  }
}

In JavaScript you have two different equality operators:

== compares values and makes automatic castings if necessary

2 == '2' // true. The string gets converted to number.

=== compares value AND type:

2 === '2' // false. String and number aren't equal.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading