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

5
  • what are you trying to achieve? Commented Sep 17, 2015 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. Commented Sep 17, 2015 at 15:27
  • look at this and see if that give some hint stackoverflow.com/questions/4611190/passing-variables-in-jquery otherwise let me know Commented Sep 17, 2015 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? Commented Sep 17, 2015 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 Commented Sep 17, 2015 at 16:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! So variables declared without var have wider scope, correct?
yes @ruggerocastagnola. If you declare them with var , then you cant use them as window.variableName , you can only us as regular variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.