Which is the right way of declaring a global javascript variable? The way I'm trying it, doesn't work
$(document).ready(function() { var intro; if ($('.intro_check').is(':checked')) { intro = true; $('.intro').wrap('<div class="disabled"></div>'); }; $('.intro_check').change(function(){ if(this.checked) { intro = false; $('.enabled').removeClass('enabled').addClass('disabled'); } else { intro = true; if($('.intro').exists()) { $('.disabled').removeClass('disabled').addClass('enabled'); } else { $('.intro').wrap('<div class="disabled"></div>'); } } }); }); console.log(intro);
Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable.
So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.
Are global variables stored in specific object? The answer is yes; they are stored in something called, officially, the global object. This object is described in Section 15.1 of the official ECMAScript 5 Specification.
Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.
If you're declaring a global variable, you might want to use a namespace of some kind. Just declare the namespace outside, then you can throw whatever you want into it. Like this...
var MyProject = {}; $(document).ready(function() { MyProject.intro = ""; MyProject.intro = "something"; }); console.log(MyProject.intro); // "something"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With