1

i have this issue in react i have this function but its not right format of react

check(img) {
        console.log(img,typeof img)
        const url="";
        const arrN = ["15","16","35","36","37","38","39","40","n15","n16","n35","n36","n37","n38","n39","n40"];
        for (var i = 0; i < arrN.length; i++) {
            if (img === arrN[i]) {
                 url = "/blah/allIcons/blah"+img+"_en.png";
            }else{
                 url = "/blah/allIcons/blah"+img+".png";
            }
        }
        return url;
    }

it give me this errror

Module build failed: SyntaxError: "url" is read-only

how i can do it ?

3
  • 1
    Maybe use have defined url above. just use url = "" instead of const url = ""; Commented Feb 9, 2017 at 12:32
  • @AdnanUmer Very bad advice. I guess you don't know why declaring variable is important. Commented Feb 9, 2017 at 12:37
  • const is something that u can't change, use var or let, read the diff between const, var, let. stackoverflow.com/questions/762011/… Commented Feb 9, 2017 at 12:52

2 Answers 2

5

If you change url variable then it's should not be declared as a constant. Use let:

check(img) {
  const arrN = ["15", "16", "35", "36", "37", "38", "39", "40", "n15", "n16", "n35", "n36", "n37", "n38", "n39", "n40"];
  let url = "";

  for (var i = 0; i < arrN.length; i++) {
    if (img === arrN[i]) {
      url = "/blah/allIcons/blah" + img + "_en.png";
    } else {
      url = "/blah/allIcons/blah" + img + ".png";
    }
  }
  return url;
}

But you don't seem to need it anyway, as entire for-loop check seems inefficient. Can be optimized like this:

check(img) {
  const arrN = ["15", "16", "35", "36", "37", "38", "39", "40", "n15", "n16", "n35", "n36", "n37", "n38", "n39", "n40"];

  if (arrN.indexOf(img) > -1) { // or if (arrN.includes(img)) {...}
    return "/blah/allIcons/blah" + img + "_en.png";
  }

  return "/blah/allIcons/blah" + img + ".png";
}
Sign up to request clarification or add additional context in comments.

1 Comment

it should not be declared as a constant :)
0

Use let url="" instead of const url="".

The value of a constant cannot change through re-assignment, and it can't be redeclared.

So if you declare variable const url="", you can't later say url="/blah/allIcons/blah" + img + "_en.png"

2 Comments

Could you provide more info and details with your answer? Thank you
@Robert, I updated my answer with some more info and references, however I will not go into details explaining let and const here, because question is not about it.

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.