Your code is working fine and does not result in an error in the console. Instead, it alerts a function definition:
function error(code) {
var errors = {
1000: function() {
return `Troubles with ${product}`
},
1001: function() {
return 'error'
}
//And many errors with different variable names...
}
alert(errors[code]);
//it returns error in console :(
}
function check() {
var product = 'car';
error(1000)
}
check();
However, if you call the function error(1000)
, it may cause an error because product
is not within scope. You should pass it as a parameter to the function. One way to do this is by passing an object with named properties that the template literal can utilize:
function error(code, params) {
var errors = {
1000: function(params) {
return `Troubles with ${params.product}`;
},
1001: function() {
return 'error';
}
//And many errors with different variable names...
}
alert(errors[code](params));
}
function check() {
var product = 'car';
error(1000, {product});
}
check();
I would suggest defining error
differently, as there is no need to recreate your errors
object and its properties each time you call error
. Here's a more efficient implementation:
const error = (() => {
const errors = {
1000(params) {
return `Troubles with ${params.product}`;
},
1001() {
return 'error';
}
//And many errors with different variable names...
};
return function error(code, params) {
alert(errors[code](params));
};
})();
function check() {
var product = 'car';
error(1000, {product});
}
check();