Declare variables with Javascript objects - javascript

I'm just wondering if it's fine to declare variables with JSON format?
For example, do this:
$(function(){
var global = {
varA : 'This is a global variable from global.varA ~!',
varB : 'This is a global variable from global.varB ~!'
};
alert(global.varA);
alert(global.varB);
});
Instead of this:
$(function(){
var globalVarA = 'This is a global variable from globalVarA ~!',
globalVarB = 'This is a global variable from globalVarA ~!';
alert(globalVarA);
});
The reason why I want to do this is that, It would be easier to look for when I work on a really long JS file. And anything starts with global. I know it is a global variable.
Is it a good practice?
Is there anything I need to put into considerations?

First, this is not JSON format, it's just normal javascript object literal.
Second, since it's valid syntax, you could do this, and this is normal practice to put the variables in a namespace (through there's no namespace concept in javascript).
If you want to make global be global, then you could set it to be a property of the global object window:
$(function(){
var global = {
varA : 'This is a global variable from global.varA ~!',
varB : 'This is a global variable from global.varB ~!'
};
window['global'] = global;
});

Your "new variables" are actually properties of an object literal. They are not variables, nor do they have global scope. However, I don't think it's the worst way to define "references to values". You're using an object as an associative array, which is A-OK.

Related

Is it ok to assign all variables to an object for a way to avoid creating global variables?

1.For example if i had defined an object before declaring the variables, then called the them as part of the object as below...
//Global object
var Global = [];
//Every var thereafter ...
Global.variable1 = some value;
Global.variable2 = some value;
Global.variable3 = some value;**
Yes, this is called namespacing. It creates a single global (which should probably have a more unique name than you are using) and then puts all your global state as a property on that single global.
This is a well used and recommended practice, used by libraries such as jQuery that are designed to be compatible with lots of other code (that may have its own globals). This practice limits the use of your own globals which lessens the chance of conflict with other code.
You would generally make the single global be an Object, not an array like this:
var myGlobal = {};
myGlobal.prop1 = "whatever";
There are other ways to limit how many variables must truly be global by using a closure to enclose both your code and your state. This is an alternate technique to the namespacing that you proposed.
It works like this:
(function() {
var variable1 = some value;
var variable2 = some value;
var variable3 = some value;
// all your code here that uses variable1, variable2 and variable3
})();
These variables are actually local variables to the immediately invoked function expression (abbreviated IIFE which is essentially just an anonymous function that is immediately executed for the purpose of creating a function scope that has private variables).
Because all your code is in the same function scope, they work like globals for your code without actually being globals. Other code cannot conflict with these variables or access these variables so it also achieves privacy.
This is one of the reason's people use an Immediately Invoked Function Expression (IIFE). By putting your code in an anonymous function that calls itself, you don't have to worry about variables polluting the global namespace.
It looks something like this:
(function() {
var variable1 = 'some value'; // This variable is not global
var variable2 = 'some value'; // This variable is not global
var variable3 = 'some value'; // This variable is not global
})();

how to call global variable inside another scope Javascript

How do i get the value of the global variable inside a scope .
If i have the same name variable present in same scope .
<script>
var number =2;
var fun= function(numbs){
console.log(number);
//here it displays 2
var number =numbs;
console.log(number);
//here it displays 3
console.log(number);
//how do i get value of global variable here
}
fun(3);
</script>
you should be able to call
window.number
A global variable is really just a property of the window object.
Simply :
console.log(window.number);
From the MDN :
Global variables
Global variables are in fact properties of the global object. In web
pages the global object is window, so you can set and access global
variables using the window.variable syntax.
But you shouldn't have to do this. If you need to go around shadowing, you have a design problem and you should probably fix it.

Javascript context confusion

I have this object:
var test = {
setup: function() { property = 'hello!'; console.log(this); }
};
When I run test.setup(); and print out test.property(); it gives me undefined. I understand it's because I need to do this.property but my question is: why?
I can clearly see that the context is the test object via console.log(this), but for some reason it doesn't work.
Thanks
When JavaScript finds a loose assignment like property = 'hello!', it will create a global variable (or raise an error, if in strict mode). So if you want it to be a property, you have to be explicit.
Because in this situation, property = 'hello!' is the same as window.property = 'hello!', not this.property = 'hello!'.
If you assign to an undeclared variable, it will create a global variable.
When you declare variable with "no var" you will "accidentally" create global variable (attached to window object) so rule of thumb: Always use "var" with variable declaration.
With "var" here, you will create local variable to setup function.

variable-variables inside function scope

Before you ask... I don't plan to actually do this. It's bad practice for obvious reasons. I'm just curious if it is possible.
In javascript, you can use bracket syntax to make variable-variables in global scope:
var var_name = 'my_var',
var_value = 'my_value';
window[var_name] = var_value;
alert( my_var ); // Works! alerts user: 'my_value'
However, when you're inside of a function and you use the 'var' keyword, the variables you create are locally scoped to the function they are declared in. Is there some object that can be used with the bracket syntax (like window) to get access to the locally scoped variables? Something like this:
this_function[var_name] = var_value;
I doubt it's possible, but thought I'd ask just for kicks.
No, there's no object you can use to access var variables within function contexts (even though they are properties of an object called the "variable object" of that execution context; the object has no exposed name and so cannot be accessed directly). The var thing in the global context is a bit of a special case, and you shouldn't rely on it (although the spec does define it). If you want to access those variables as properties of the global object (window, in the case of web browsers), explicitly assign them to window properties rather than using var, for clarity:
window.x = 'my value';
or if you prefer:
window["x"] = 'my value';
(Those two statements have identical results, both create/set a property called "x" on the window object.)

scope in javascript

i have encountered the following curious piece of code:
function foo(){
works = {hello:"world"};
function bar(){
alert('does not work');
}
var notwork = {hello:"world"};
}
foo();
alert(works.hello);
alert(notwork.hello);
Can someone please explain to me why works work, and notwork doesn't work? Or point me out to a good resource that explains this in detail.
Thank you very much!
var notwork creates a local variable valid only for the runtime of the function.
works creates a global variable that is valid throughout the javascript runtime.
var declares a variable as "local" to the function it's defined in.
Without var, you works variable is global : it can be seen/accessed/used from anywhere.
With var, your notwork variable is local to the foo function : it cannot be seen/used from outside of that function.
For more informations, you can take a look at the documentation of the var statement on MDC, which states (quoting) :
The scope of a variable is the current
function or, for variables declared
outside a function, the current
application.
Using var outside a function is
optional; assigning a value to an
undeclared variable implicitly
declares it as a global variable.
However, it is recommended to always
use var, and it is necessary within
functions in the following situations:
If a variable in a scope containing the function (including the global
scope) has the same name.
If recursive or multiple functions use variables with the same name and
intend those variables to be local.
Failure to declare the variable in
these cases will very likely lead to
unexpected results.
You've missed out the var keyword so works is being defined on the global object.
You want
var works = ...

Categories