Get global variable dynamically by name string in JavaScript?



Display in alert by using alert(window()). Following is the syntax −

alert(window['yourVariableName' + 'yourVariableName' + otherVariableName]);

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<script>
   var globalVariablelocal_print100=100;
   print100=1;
   alert(window['globalVariable' + 'local_' + print100]);
</script>
</body>
</html>

To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.

Output


Advertisements