0

For something like the following:

"use strict";
let a = 1;
console.log(eval(`
    a++; 
    let b=4;
`));
console.log(`a=${a}, b=${b}`);
// ReferenceError: b is not defined

Is it possible to do something where it prints undefined or something if the variable is not there instead of throwing an error? Something conceptually like:

console.log(`a=${a}, b=$?.{b}`)
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

0

The placeholder has to contain an expression and there doesn't seem to bean idiomatic way of using an undefined variable (likely due to parsing error) so I would go with a getter instead of using a raw variable.

For example before accessing b you can write

let getB = function () {
    return (typeof b !== "undefined")? b :undefined;
}

Then in the template literal you can write ${getB}.

CollinD
  • 7,304
  • 2
  • 22
  • 45
uberhaxed
  • 225
  • 1
  • 9
  • could you show how that would work or what you mean? If it's a getter, wouldn't you have to pass the variable itself to it which would produce a referenceerror ? – David542 Mar 07 '22 at 20:32
  • @David542 Getters don't take arguments. In the getter function you can do any type of type checking logic and are able to return a string or a value like null. – uberhaxed Mar 07 '22 at 20:41
  • ok, do you want to show that in your answer with some code instead of just your single sentence and I can go ahead and accept your answer? – David542 Mar 07 '22 at 20:42