Skip to content
Advertisement

javascript eval works one way but not the other, why?

I am trying to use eval function for dynamic assignment. I know it is bad practice and have modified the code to not use eval. Still though, I don’t understand why it worked one way but not the other.


Here is what worked:
onFilterChosen(filterEmited: string, kind: string) {
    eval("this.dbParams." + kind + " = filterEmited");
} 

What didn’t work:
onFilterChosen(filterEmited: string, kind: string) {
    eval("this.dbParams." + kind + " = " + filterEmited);
} 

Can someone tell me what’s wrong with the second approach?

Advertisement

Answer

In the second example, there must be a variable which has the name of the value of filterEmited. Let’s make an example, we call the function:

onFilterChosen('filter', 'abc');

will result in this JS to be executed in the first example:

this.dbParams.abc = filterEmited

which works, because the parameter is called filterEmited. whereas in the second example this will be executed:

this.dbParams.abc = filter;

and since there is no variable “filter” it might crash.

btw. emitted is spelled with two t’s!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement