0

I want to check if a string is equal to another string and set a new string based on this condition.

 private myFunction( myString: string ) {

    if (myString != "someString") {
      let path:string = "/*/POST/A";
    }
    else{
      let path:string = "/*/POST/note/B";

    }
   (do something with path here)

Not sure the above is correct actually finding it pretty hard to find a decent example of this and completely new to typescript/ javascript.

3
  • let path = "/*/POST/note/B"; if (myString != "someString") { path = "/*/POST/A"; }? Commented Aug 14, 2020 at 14:32
  • yea that works comment as answer i will accept Commented Aug 14, 2020 at 14:33
  • You have to define your let variable before any condition if u want to do something with your path Commented Aug 14, 2020 at 14:37

2 Answers 2

2

let variables are block-scoped - they only exist within the block you declare them. So declaring let path inside of the if block or the else block won't allow you to use it later outside of the if/else.

All you need to do is declare it in the scope you want to use it and assign it in the if/else.

let path: string;
if (myString != "someString") {
  path = "/*/POST/A";
} else {
  path = "/*/POST/note/B";
}
//use path here

Sign up to request clarification or add additional context in comments.

Comments

1

Consider using a ternary expression so you’re not declaring the variable inside the conditional:

const path:string = myString === “someString” ? “option a” : “option b”

2 Comments

I like this, so the option a is if the string is equal to someString?
Yes. It takes this form: condition ? value if true : value if false

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.