I get a strange behavior when declaring an object with the logical OR.
my_var = my_var || {}; // throws TypeError
If I add the var keyword
var my_var = my_var || {}; // returns empty object
Why is this? I can't seem to find an explanation. my_var is global scope, so why is var changing the behavior?
The first example tries to assign to a property on the global object named my_var by reading the value from an identifier called my_var (OR an empty object). However, the identifier my_var is not defined at that point, so it fails.
In the second example, due to how javascript variable hoisting works, the my_var variable is already declared, when you read from it by assign to it.
Also have a look at this example:
a = a; // fails, undeclared identifier
a = 0;
With var keyword it will work!
b = b; // succeeds allthough identifier undeclared?!
var b = 0;
This is because variable hoisting will turn it into this:
var b; // declaration of b hoisted to the top of scope
b = b;
b = 0;
when defining a variable without var, you're directly accessing the global object. That means, your Javascript engine trys to lookup my_var on the global object (window if you're in a browser). Since that property does not exist yet, your JS engine will throw.
That happens on the right side of your statement, when your engine trys to read a variable with the name my_var. assigning like
my_var = {};
would work tho. But accessing an identifier without var will cause the browser to lookup the scopechain. Since the variable object for the global object is the global object itself, the lookup procedure will end up nowhere ( = exception ).
By putting the var keyword infront, your js engine knows at parsetime that it has to declare a new variable with that identifier name. It actually does declare that variable with an undefined value (that is called "hoisting"). That means, using var will prematurely create a property in the current context with that name. So if that code is not located in any function or eval context, it'll create the property my_var on the window object.
In your second example, the var defines the scope of my_var. This allows the value to be set properly. Here's a quick and dirty look at what's happening in both examples:
With example 1, the JS engine has to do the following:
Check the current scope to see if my_var exists.
Check the scope above (and the scope above that) until it finds my_var.
Create my_var in the global scope when it's not found.*
*Step 3 has not yet happened when you try to assign a value to my_var.
Example 2:
Is there a variable named my_var in the current scope? Yes, you just created it using the var keyword.
Assign its value.
In the 2nd situation, my var is undefined so the variable is assigned an empty object which is {}
Although I cannot quote the specs, I assume that the initialization in a var statement is just syntactic sugar:
var my_var = my_var || {};
is equivalent to:
var my_var;
my_var = my_var || {};
In the first line, my_var is declared and implicitely set to the special value undefined. Then, in the second line, my_var exists, undefined evaluates to false and no error is raised.
In your first example, however, my_var is unknown when the right hand side is evaluated, hence the error.
In the first case you try to assign a variable that was not defined. Its the same as you would write :
my_var = a || {};
in the second case my_var is only undefined as you use the var keyword an create my_var in the actual scope. Undefined is converted to false and it will return the empty object.
Interestingly, this will work:
a = my_var || {}; // 'a' is now an empty object
When you use the 'var' keyword you're literally giving the command "create a new variable and assign to it this value." If you don't use 'var' then you're implying that the variable already exists within the global scope somewhere.
In your example the JavaScript engine attempts to look up the current value of 'my_var', finds that it doesn't exist, cannot create it because you're currently attempting to assign a value to it, and fails.
Related
This is a serious question, It has been nagging me for a while. In JavaScript you can declare a variable which has no type. It's type is often dynamic, depends on further value assigned to it.
e.g
var text;
typeof(text); //undefined
text = 'someText';
typeof(text); //string
So as we know that Javascript can dynamically change variable's type why these assignments are invalid then?
e.g
var someObj;
someObj.a = 'hello world';
console.log(someObj) //TypeError
var someTable;
someTable[0] = 'hello world';
console.log(someTable[0]) //TypeError
where this problem can be fixed just by adding definition to variable declaration:
var someObj = {};
var someTable = [];
I'd expect a good explanation of this problem. Thanks for answers.
There's a big difference between declaration and initialisation of variables.
When you declare a variable without initializing it with a value, its type will be undefined, so when you will try to call it or access it, it will give undefined, because simply there were no value defined for the variable.
That's why it should be initialized:
var someObj = {};
var someTable = [];
So you can treat it as a string, an object or an array according its initialized value.
Documentation:
Please take a look at variables MDN Reference for further reading, where it says:
A var statement declares variables that are scoped to the running execution context’s VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. [...] A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer’s AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
You're getting confused about where the error is thrown. In your first example:
var someObj;
someObj.a = 'hello world'; // the error is thrown here
That error is thrown because someObj is undefined (not undeclared). So, you can't access the property a on undefined.
The same explanation applies for your second example:
var someTable;
someTable[0] = 'hello world'; // the error is thrown here
You're trying to access index 0 of undefined.
The reason that defining them as {} and [], respectively, fixes your issue, is that you are then accessing property a of {} and index 0 of [].
1) Data types in Javascript are not dynamic, they are mutable. This means that depending on kind of operation you are applying to them they can change from being something into another thing (e.g. a number can become a string doing something like this: 4 + 'a').
2) The "error" is a consequence of having a variable not initialized. In Javascript when you are doing this:var something = 'a'
you are doing two operations, a declaration, and an assignment. If you don't do the assignment and you try to access to a property of the object you have declared it will throw an error. In your case, you are declaring a variable but not initializing it to the "compiler" can't access the "a" property or the position 1 because it is of type undefined.
The function below will return b is not defined because the compiler will look in the function and then into the global scope in search for a variable b.
However, I assumed that defining b without the word var would automatically create a global variable?
Can anyone explain the rules when omitting the word var?
function foo(a) {
console.log( a + b );
b = a;
}
foo( 2 );
Not using var in a function for a variable declaration does make it global, but in your case, the JavaScript engine is hitting this line:
console.log( a + b );
before it hits this line:
b = a;
And, that's the line that declares it (globally).
And, because you didn't use var, the declaration is not hoisted to the top of the code base (which it would have been with var - you would still not have gotten a value for b because only the declaration would be hoisted, not the initialization, but it would not have thrown an error), so you get your error.
See more about var and hoisting here.
In strict mode:
Using an undeclared variable will throw an exception
In non-strict mode:
Assigning to an undeclared variable will create a global, but this is not hoisted
Declaring a variable with var creates a local variable and is hoisted to the top of the function
Reading an undeclared variable will throw an exception
Since you are not in strict mode and you try to read b before you assign a value to it, you get an exception.
Guidelines to follow:
Always "use strict"
Always declare your variables
Declare them in the global scope if you want them there
… but try to avoid global scope. Consider using a closure instead if you think a global would be useful.
Variables declared this way b = a are not hoisted, like variables declared with the var keyword. That means that, at runtime, the compiler reads b, not as undefined (as would happen with var b = a), but as something that doesn´t exist at all, thus throwing a ReferenceError.
Info on Hoisting: https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
Is this a variable definition or declaration? And why?
var x;
..and is the memory reserved for x after this statement?
EDIT:
In C extern int x; is a declaration, int x = 5; is a definition. What's the analog in JS? Wikipedia says a declaration allocates memory and the definition assigns a value to this allocated memory.
SECOND EDIT:
I think the explanation of #Deryck sounds great, but there's some output that disagrees with his explanation:
> var x;
undefined
> x
undefined // now it looks like x is defined to the value undefined
> y
ReferenceError: y is not defined
If the ReferenceError output would say y is not declared it would make sense. But often I read that JS has two non-values: null and undefined. So var x would be a definition with the value undefined.
var x is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation.
var x = 1 is both declaration and definition but are separated with x being declared in the beginning while its definition comes at the line specified (variable assignments happen inline).
I see that you already understand the concept of hoisting but for those that don't, Javascript takes every variable and function declaration and brings it to the top (of its corresponding scope) then trickles down assigning them in order.
You seem to know most of this already though. Here's a great resource if you want some advanced, in-depth exploration. Yet I have a feeling you've been there before.
Javascript Garden
PS - your analogy between C variable dec/def and JS was spot on. What you read on Wikipedia was correct.
Declaring a variable is like telling the (javascript) compiler that this token x is something I want to use later. It does point to a location in memory, but it does not yet contain a value. ie. it is undefined
var x;
defining it means to give it a value which you can either do it like:
x = 10; // defining a variable that was declared previously
or like this:
var y = 20; // declaring and defining a variable altogether.
http://msdn.microsoft.com/en-us/library/67defydd(v=vs.94).aspx
http://www.w3schools.com/js/js_variables.asp
I will give you a long answer for better explanation.
When the javascript engine is not able to find a particular variable in memory, it will throw an error. To be more specific, when the javascript engine (Execution Context) is not able to "reference" a variable in memory, it will throw a ReferenceError. This is not exactly the same as a Declaration Error, at least in javascript.
There is a deference between a not defined error and the value undefined.
So doing
var a = undefined;
and
var a;
will both log the same result i.e. undefined. This is because, when you simply do a var a; the javascript engine allocates memory for the variable and automatically sets it's value to undefined, which is different from saying that a doesn't exist at all - in which case it will throw a ReferenceError.
Hoisting
console.log(a); // undefined
var a = 'something';
will log undefined because, the javascript engine knows there's a variable declared somewhere in the code - which means to say that the javascript engine actually does something before it executes the code - one of the thing it does is hoists variables. To put it simply, the above code is the same as
var a; // hoisted (declared and defined the value `undefined`)
console.log(a); // undefined
a = 'something' // update the defined value to `something`
So, yes, declaration and definition happen together in javascript (automatically - if you don't do it yourself) and the default defined value is undefined.
ES6
Just an additional note
const a;
will throw a SyntaxError where a initializer (definition) is necessary. const is the only time when you need to declare and define manually.
> var x;
undefined
> x
undefined // now it looks like x is defined to the value undefined
> y
ReferenceError: y is not defined
Although it is usually said that Javascript is an interpreted language, but there is also a compilation step that happens very fast just before the interpreter runs. The job of this compilation step is to create scope chains, where variables are declared(no read/write operation here, just simple name-keeping) in their respective scopes. These variables will point to some memory location but value in it will be undefined until some execution is carried out by the interpreter.
> Compiler run:
When compiler sees var x;, it will simply book-keep this variable in its respective scope.
The next x; and y; are simply ignored in the compilation step as they are execution statements.
> Interpreter run:
When interpreter sees var x;, it will skip this as there is no read/write operation here.
Now when interpreter sees x;(execution statement), "x" will already be declared in the scope, and it will hold value "undefined", which is what you get on the console.
But when interpreter sees y; similarly, there has been no previous declaration or name-keeping for it in the compilation step, and thus we get the ReferenceError as expected.
Hope someone finds this comment useful.
var x, y, z;
var x;
var h = 4;
i = 4;
all the above are global variables if placed at the top, (outside any functions)
Lets say that the javascript has a function start
function start() {
x = 5*5;
}
the global variable x is now equal to 25
Where as if the var x; was not placed outside of any functions, that variable x would just be local to that function.
You declare JavaScript variables with the var keyword:
var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign
var carname="Volvo";
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following statement:
var carname;
var hoisting
In JavaScript, a variable can be declared after being used.
bla = 2
var bla;
// ...
// is implicitly understood as:
var bla;
bla = 2;
For that reason, it is recommended to always declare variable at the top of functions. Otherwise, it may lead to confusing cases
When declaring a variable without assigning a value to it, there still needs to be some memory available for it, otherwise you cannot make a reference to the variable later in the program. I don't think it's a noticeable amount of memory being used and won't make a difference.
var x;
This is a variable declaration. In Js if you don't assign any value to variable in declaration. It will get undefined by default.
var x; // declaring x
console.log(x); // output: undefined
But if you have not even declared the variable in you try to access it. It says that the variable is not defined.
console.log(y); // Output: ReferenceError: y is not defined
If you need access to objects between JS files, it's good practice to expose one object to the global namespace and declare fields and methods on that object.
File 1:
var myObject;
myObject.myField = "Field!";
File 2:
myObject.prototype.myFunction = function () {
return this.myField;
};
I have taken from a really good discussion on : Equivalent of C extern declaration in JavaScript
https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions
Various trivia regarding the difference between undefined and null completely aside, the short answer is: there is no equivalence in Javascript. There are no bare "forward declarations". Javascript variable declarations are definitions. Variables that have been defined but not explicitly initialized will contain the value 'undefined'. There is no "external linkage".
If you refer to an identifier that is not in any accessible scope (perhaps because it doesn't exist the first place), you will get your "ReferenceError: y is not defined". This has nothing to do with variable value or storage.
In simple terms,
undefined means value to the variable is not defined.
not defined means the variable itself is not defined.
var x; //value is not defined. So,
x //undefined
//y variable is not declared or defined. So,
y // y is not defined
Here i am just creating a global namespace for my application and everything works as expected
var MYAPP = MYAPP || {} ;
but if I omit var keyword ( i know it's not the right way), javascript throw an error "ReferenceError: MYAPP2 is not defined" .
MYAPP2 = MYAPP2 || {};
just out of curiosity can some one explain me in second case why javascript is not able to resolve the reference.
The first version doesn't produce an error because Javascript's variable hoisting makes it equivalent to this:
var MYAPP; // declares, but leaves the value undefined / unchanged
MYAPP = MYAPP || {}; // creates, if the value was previously undefined
Importantly, the declaration part of this does not overwrite any existing declaration or assignment that was already made to the variable.
This is what allows this pattern to be used repeatedly within a single scope. MYAPP either retains the value it already had, or is initialised to an empty object.
in the second case, that declaration step is effectively omitted. If the variable has not already been declared (or otherwise exists in scope, i.e. as a property of the global object) then the error you see is generated.
var MYAPP = MYAPP || {} declares variable MYAPP in current scope (aka execution context). If declaration appears in a function - local variable is declared; if it's in global scope - global variable is declared.
MYAPP2 = MYAPP2 || {}, on the other hand, is merely a property assignment. It first tries to resolve MYAPP2 against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find MYAPP2, only then it creates x property on a global object (which is a top level object in a scope chain).
var keyword declare immediately variable you are referencing to
var a = a || {};
is like as
var a; a = a || {};
In second case you are refencing to variable isn't declared yet.
I had to use json2.js in my project as browser(IE8) JSON object was not available for parsing strings to JSON.
I ran through json2.js and am having a doubt with the variable declaration.
A JSON global variable is declared in json2.js like
var JSON;
if(!JSON){
JSON={};
}
What is the effect of declaration var JSON; on the global JSON object.
I hope the declaration should override the global JSON object in any browser (IE8/IE7).
But for my surprise it is not overriding when a global object is available.
Only a variable definition / initiation overrides a global variable?
Kindly clarify.
For each variable declaration (not initialization!). The following happens (section #10.5):
8. For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do
Let dn be the Identifier in d.
Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.
If varAlreadyDeclared is false, then
Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.
So you see, whenever var x is encountered, it is tested whether a variable with name x already exists in the environment. If yes, it is just ignored, but if not, then the variable is declared and initialized with undefined.
Since the code is run in global scope it tests whether JSON exists in global scope. So if JSON already exists, var JSON; is just ignored.
Just some thoughts regarding testing/explaining this behaviour:
I don't know at which point in the JavaScript execution the global object is created, but I assume before all other scripts are evaluated. That means, JSON exists and has a value before any variable declaration, something you can only simulate if you include two scripts (can also be inline I guess, they are evaluated after another).
Try:
// script1.js
var foo = 'bar';
// script2.js
var foo;
if(!foo) {
foo = 'baz';
}
alert(foo);
// include script2.js after script1.js
What's the result? (cheaters look here).
Whenever you are in a single script file, all variable declarations are hoisted to the top anyways. So if you have
var foo = 'bar';
var foo;
if(!foo) {
foo = 'baz';
}
the script is actually executed as:
var foo;
var foo;
foo = 'bar';
if(!foo) {
foo = 'baz';
}
You could not actually test whether the second var foo; overwrites the first one, since at this point it has no value yet. So this is not a good example to demonstrate the behaviour quoted above.
The var keyword ensures there is a variable in the enclosing function or (like here) in window but it doesn't initialize one.
In fact, the order doesn't really impact.
Look at this code as an example :
a = 3;
var a;
alert(a);
It alerts "3".
So the var declaration in the code you show simply ensures there won't be errors in the test, and doesn't remove the existing value.
It's good to keep this in mind because a common error in javascript is to have more than one var declaration in a function and being surprised by the value set before even the var declaration. Run this for example :
if (true) {
a = 3;
}
// lot of code, at a different level
if (true) {
var a;
if (433/43==3) a=true;
if (a) alert('should not happen');
};
Yes, the var is attached to the function, not the block...
It may not be an option for you, but it is also possible to set IE8 to compatibility mode to get the native JSON object back:
// in your preinit page event
Response.AddHeader("X-UA-Compatible", "IE=8");
The other option would be to create the JSON variable only if it does not exist:
var JSON = JSON || {};
If you are in the global scope when executing that block of code, then var JSON will overwrite the global JSON object to undefined.
If you are in any other scope (like inside a function), then there will be no effect.