Creating a dynamic variable name in JS

var $geometryPointFields = $('[class*="Point"]', $panel),
    $geometryLineFields = $('[class*="Line"]', $panel),
    $geometryPolygonFields = $('[class*="Polygon"]', $panel);

function(geometry) {
    // geomtery is either Point, Line or Polygon
    ${'geometry'+geometry+'Fields'}.show() // ?

How do I do this? I can't or rather don't want to use window[] or scope[].

2 answers

  • answered 2018-07-11 04:02 CertainPerformance

    Because the three variables are all geometry fields, it would probably make the most sense to use an object rather than three standalone variables:

    const geometryFields = {
      Point: $('[class*="Point"]', $panel),
      Line: $('[class*="Line"]', $panel),
      Polygon: $('[class*="Polygon"]', $panel)

    Then you can access the property of the object with the geometry string:

    function showGeom(classStr) {

    If you have to use standalone variables, you could eval, but you really shouldn't eval:

    $geometryPointFields = $('.point');
    function showGeom(classStr) {
      eval('$geometry' + classStr + 'Fields').show();
    setTimeout(() => showGeom('Point'), 1500);
    .point { display: none }
    <script src=""></script>
    <div class="point">point</div>

  • answered 2018-07-11 04:18 31piy

    Your variables are formed using jQuery selectors' response. Why don't you select and show the elements directly in the function?

    function showElements(geometry) {
      $('[class*="' + geometry + '"]', $panel).show();

    You just need to ensure that $panel is accessible in this function, and it should work fine.