I was looking at some of the AJAX calls that GMail does, and I noticed that sometimes the return value of the calls started with a number. Example: (note that there's is no semi-colon after the first line)
3
[1, 2];
If I were to enter this into a JavaScript console, I'd get undefined returned back. However, if the second parameter is a number or a string, I'd get the second parameter returned back. Example:
3
4
Returns 4.
My guess is that they're doing this to stop jsonp-type attacks, however, does anyone know what underlying evaluation is being done? In the 2nd case I believe that a semi-colon is "inserted" after the first line, which would make returning 4 make sense. However, I can't think of a reason why the first expression would return undefined.
The array the map() method returns consists of the values that are returned from the callback function. If you don't return a value from a function in JavaScript, you implicitly return undefined . Copied! This is the most common reason the map() method returns an array containing undefined values.
(Even when this is not the case, avoid overriding it.) A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
JavaScript assigns 'undefined' to any object that has been declared but not initialized or defined. In other words, in a case where no value has been explicitly assigned to the variable, JavaScript calls it 'undefined'.
This is because how ASI ( Automatic Semicolon Insertion ) works. The first statement is interpreted as
3[1,2];
so it is undefined
. The second one is interpreted by ASI as 3;4;
which is 4
.
ASI rules are counterintuitive in some cases, for example you might wonder why there is no semicolon between number and bracket? Well, there is a reason for that. Read these resources for more details:
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
http://bclary.com/2004/11/07/#a-7.9.1
Google will probably give you more results. :) That's why we have neverending semicolon-free JavaScript war.
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