Jason Chu
Jason Chu

Reputation: 385

What's wrong with my try/catch code?

var tryThis = false
try {
  if (tryThis = true) {
    console.log("Why does this get printed?")
  }
} catch(e) {
  console.log("The error is", e)
}

There's something definitely wrong with my understanding of Javascript's try/catch statements. I'm new to this so any help would be appreciated!

Upvotes: 0

Views: 63

Answers (2)

Ele
Ele

Reputation: 33726

// this is actually assigning `true` to `tryThis`
if (tryThis = true) 

This is just to help you understand how to compare boolean values

When you need to make a comparison between boolean values, you don't need to do this: tryThis === true because it's unnecessary.

var tryThis = false
try {
  if (tryThis === true) {
              ^

Just use the boolean value as follow:

var tryThis = false
try {
  if (tryThis) { // this is the same as tryThis === true or tryThis !== false
      ^

If you want to compare a boolean value to false, don't do this:

 tryThis === false
         ^

Rather, use the negation operator, so, do the following:

 !tryThis
 ^

Upvotes: 0

Matt Morgan
Matt Morgan

Reputation: 5303

This line:

 if (tryThis = true) {

assigns true to tryThis, which evaluates to (as @Tibrogargan commented above) to true. Instead:

 if (tryThis === true) {

You want to compare the values. Use ===.

Upvotes: 3

Related Questions