1

Is it possible to convert a string into a variable name while in jQuery's document.ready?

If I try this in pure JS

var boh = "blahblah";
console.log(window["boh"]);

returns blahblah, while if I go with JQuery

$(document).ready( function() {
    var boh = "blahblah";
    console.log(window["boh"]);
});

returns undefined

  • what are you trying to achieve? – Maytham Fahmi Sep 17 '15 at 15:22
  • i'm getting values from a json and i want those values to become variables i can use within a script. i can do it outside `document.ready`, but i was curious whether it's possible to get them from inside. – ruggerocastagnola Sep 17 '15 at 15:27
  • look at this and see if that give some hint http://stackoverflow.com/questions/4611190/passing-variables-in-jquery otherwise let me know – Maytham Fahmi Sep 17 '15 at 15:35
  • 1
    In your first snippet `boh` is in the global scope, which you should avoid by all means while in the second `boh` is not in the global scope. Within DOM ready you may replace `var boh` with `window.boh` but I see no point in cluttering the global scope. Why do you want to use global variables? – PeterKA Sep 17 '15 at 15:36
  • Thanks a lot for the answers. I'm not sure I can fully understand your point @PeterKA. In my script, I'm using them from within a function inside jQuery, so I guess I'm using it locally – ruggerocastagnola Sep 17 '15 at 16:11

1 Answers1

1

try this without declaring the data type as var.

boh = "Pure JS";
console.log(window.boh);

$(document).ready(function() {
  boh1 = "jQuery";
  console.log(window.boh1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript variables are that defined and declared without varare under window scope.

J Santosh
  • 3,808
  • 2
  • 22
  • 43