0

How to check (eval?) if a given string/variable is valid

If I try

getData('/img/webshop/'+product.images[551].slug+'/'+product.images[1].src')

I get 'Cannot read property slug of undefined' if array item [551] does not exist

My getData function contains a Try catch function to check if [551] exists but the error is allready generated when the getData function is called

I could solve this by adding back-ticks

getData(`'/img/webshop/'+product.images[551].slug+'/'+product.images[1].src'`)

and sending this like a string but then I need to convert this string in getData, (eval?) but this doesn't work. ( remains string)

Cid
  • 14,968
  • 4
  • 30
  • 45
  • Does this answer your question? [How to check if array element exists or not in javascript?](https://stackoverflow.com/questions/13107855/how-to-check-if-array-element-exists-or-not-in-javascript) – Cid Feb 14 '20 at 10:44
  • Short answer, check it **before** calling the method – Cid Feb 14 '20 at 10:45
  • Why would changing it to backticks solve the issue? – evolutionxbox Feb 14 '20 at 10:45
  • 1
    Sending a variable name as parameter won't send its content. – Cid Feb 14 '20 at 10:46
  • @evolutionxbox I want to try catch in a seperate function, after calling the function. back-ticks make sending without error. I was a try.. –  Feb 14 '20 at 10:55
  • @Cid I know how to check, I want it checked inside the function, calling the function gives an error. (thanks for editing my question :-) ) –  Feb 14 '20 at 10:57
  • Well, then do it. – Cid Feb 14 '20 at 10:59
  • @Cid want to use the parameter to get the content –  Feb 14 '20 at 11:07

0 Answers0