Is it possible to overwrite the undefined in javascript? - javascript

like
function myFunction(){
var undefined = "abc";
}
If its possible then how to restrict not to allow that?

Is it possible to overwrite the undefined in javascript?
If by "the undefined" you mean the global undefined variable, then no. Since EcmaScript 5, it is specified as non-writable. However, older browsers don't adhere that spec, so it is overwritable in legacy engines. You cannot really prevent it in them, but always reset it by undefined = void 0;. If you still worry and want to know how to protect your own scripts, check the question How dangerous is it in JavaScript, really, to assume undefined is not overwritten?.
like function myFunction(){ var undefined = "abc"; }
That's a different thing. You can always declare a local variable with the name undefined (shadowing the global one) and assign arbitrary values to it.

Some browsers allow it, the best way to restrict it is avoiding it.
But... some are using this technique to preserve the undefined:
(function(undefined){
})()
They get a variable called undefined but don't pass a value which gives undefined the undefined value.
From jQuery's source code:
(function( window, undefined ) {
...
...
})(window);

Yes it is possible to overwrite undefined.
This question has good solutions for working around that problem - How to check for "undefined" in JavaScript?

Related

Why does declaring a variable named values as an object returns type of function in Firefox

I have used var values = {}; in a JavaScript file. However when I test my application on Firefox typeof(values) returns function instead of object. This can easily be tested within Firefox console window. As this variable has been used many times in my application; changing it's name may not be a feasible solution. My questions are:
Is there a way to force this variable name as an object?
What other variable names should i be concerned in order to avoid this problem?
The problem is your assignment tries to change the read-only property window.values which is a function, a console utility.
You don't have such problem if you do it in an inner scope:
(function(){ var values = {}; console.log(typeof values) })()
The difference between Chrome and Firefox is that Chrome doesn't define this property as read-only.
That's just an artifact of the Firefox console, it doesn't affect your real code. If you use typeof values in your actual script code, you'll see that it's undefined (or object if you create it as shown in your question).
Firefox's console provides values as a means of seeing the values of an object:
>> values({foo: "bar"})
-> Array [ "bar" ]
There are other functions available in the Firefox console; they're documented here.
Chrome / Chromium has a bunch of them as well (including values), documented here.
Is there a way to force this variable name as an object?
In real script code, not the console, there's no problem using values. However, I suggest avoiding creating globals, since the global namespace is very crowded.
What other variable names should i be concerned in order to avoid this problem?
name and title are common ones people trip over. This is another reason not to use global variables. Instead, put your code in a scoping function:
(function() {
// Your code here
})();
Because by doing so in firefox, you're trying to override/re-assign the global read-only window object values which type is function
window.values // its a function
Chrome however doesnt treat values as a read-only object
In order to make it works as you wish in Firefox, you need to place it inside a function
function test() {
var values = {};
console.log(typeof values); // typeof: object
}

Understanding “undefined” in Javascript: how it works, how to safely check against it and whether reassignment is possible

I’ve been reading about undefined in JavaScript and now I am not sure if my understanding is correct. There is a lot of talk around how to check for undefined but somehow I couldn’t find any mentioning of something that to me seems fundamental to understanding of how undefined actually works (undefined being property on host object). This is the reason for this question, I need to confirm that what I understand is correct and if I’m wrong I would appreciate clarification.
Okay, first of all, undefined is property on host object (window in browsers) so it’s perfectly legal to use:
window.undefined
The value of this property is type "undefined". This is one of the JavaScript types along with Object, String, Number and Null. So if I do:
if(someVar===undefined) {}
I’m actually checking against window.undefined property, whatever it contains, is that right?
So this code below would be pretty dumb as this would check someVar only against the string "undefined", not the type nor the property of the window object, right?
if(someVar==='undefined') {}
This below would be also incorrect as this would check against the window.undefined property (whatever it contains):
if(typeof someVar===undefined) {}
So, to sum it up, the only proper and cross-browser way to check for undefined is to use typeof e.g.:
if(typeof someVar==='undefined')
Is that right?
Also in ES5 window.undefined cannot be reassigned but it’s perfectly legal in older browsers right?
This however can still be done and is evil if my understanding is right:
(function() {
var undefined=66;
alert(undefined);
})()
I would appreciate clarification if I misunderstood how undefined works in JavaScript.
You're almost correct. Except for this:
The value of [window.undefined] is type "undefined". This is one of Javascriupt types along with Object, String, Number, and Null
There are 3 undefined in javascript. The global variable undefined, the value undefined and the type undefined.
Even if the global variable undefined is overridden, the value undefined still exists. There are several ways to get it one of which is an empty argument to a function, another is a variable declaration without assigning anything:
// Note: Probably need older browsers to assign to undefined:
window.undefined = 1;
(function(foo){ // the value of foo is undefined;
var bar; // the value of bar is undefined;
return [foo === bar, foo === window.undefined]; // returns [true,false]
})();
Note carefully that in the example above we're checking the value, not the type. Yes === checks type and value but if you replace === with == the result would be the same.
The value undefined has type undefined ('Undefined' in the spec and documentation but typeof returns 'undefined') and type undefined is only valid for the value undefined.
That's all fine, plus:
you can use void 0 to reliably "generate" the real undefined value (or not-a-value; it's kind-of zen)
in a function, you can reference an argument that you know isn't supplied to get a reliable undefined
(function( undefined ) {
// ...
})();
This second example is not really the clearest code in the world, but you'll see it sometimes in common public codebases, tutorials, etc.
So if I do:
if(someVar===undefined) {}
I'm actually checking against window.undefined property whatever it
contains is that right?
Right.
So this code below would be pretty dumb as this would check someVar
only against the string undefined, not the type nor the property of
window object right?
if(someVar==='undefined') {}
Right.
This below would be also incorrect as this would check against the
window.undefined property (whatever it contains):
if(typeof someVar===undefined) {}
Right.
So to sum it up, the only proper and cross-browser way to check for
undefined is to use typeof e.g.:
if(typeof someVar==='undefined')
Is that right?
Yes, though it is error-prone because you may mis-type that string and get no error (even in strict mode) to indicate the mistake.
So it's better to call some method, especially if you're already using some framework e.g. in AngularJS - angular.isUndefined
Also in ES5 window.undefined cannot be reassigned but its perfectly legal in older browsers right?
Right.
This however can still be done and is evil if I my understanding is
right:
(function() {
var undefined=66;
alert(undefined);
})()
I believe so.
So to sum it up, the only proper and cross-browser way to check for undefined is to use typeof e.g.:
if(typeof someVar==='undefined')
No, the direct comparison somevar === undefined is fine.
There are any number of global variables that can be overwritten or shadowed that will break code. There's no way to protect against them all, except to simply not allow bad code.
What's nice about the direct comparison (aside from being shorter and cleaner) is that it's must more natural and intuitive, whereas people often get the other syntax wrong. They end up accidentally using the other examples you gave:
if (somevar === 'undefined')
if (typeof somevar === undefined)
These are very common errors, and are much more common than people redefining undefined.
Furthermore, you'll see things like this:
if (typeof somevar === 'undefiend')
This is much more subtle, and is hard to spot when surrounded by a bunch of other code. Again, it's a common mistake.
Probably the worst is when you see this:
if (typeof somevar === 'undefined')
somevar = "foobar";
What's wrong with that? Well, if somevar had not been declared, we've now created an implicit global variable. This can be really bad. If we had done a simple comparison, we would have been alerted to the problem with a ReferenceError.

Javascript testing whether or not a variable is set

Generally, I test whether or not a variable is set with something like this:
if (variable !== '') {
do something...
}
I know there are other methods for testing variables like typeof but I don't see any advantage - is this an appropriate way to test whether or not a variable is set? Are there problems with it that I should be aware of ?
Two reasons:
1) What if the variable is set by getting the contents of an empty input box?
if(someScenario){
var variable = $('empty-box').val(); }
Perhaps this is only done in certain cases, like when someScenario is true. Later on, you want to check if that variable was set. Your means returns false rather than true. Point is, you can come up with scenarios where you get wrong answers.
There's just no reason not to do it the accepted way.
if(typeof variable !== 'undefined')
It's no slower, has no real flaws, and is only a few characters more.
2) And most importantly, using typeof makes it totally clear what you're asking. Readability is crucial, and if another programmer read the first code, they would think you were checking that it wasn't an empty string. The method using typeof makes it perfectly clear what your conditional is looking for, and reduces the odds of mistakes later on.
If variable has been declared but might not have a value then your code:
if (variable !== '') {
tests if it is not the empty string. Is that what you want? An empty string might be a valid value. Better to test for undefined, or explicitly initialise it to a value that you can then treat as "invalid" (perhaps null, or whatever suits).
If variable has not been declared at all the above code would result in an error such that execution would stop at that point - you can't test the value of a variable that doesn't exist. So if, for example, you're trying to test a global variable that is created inside a function that may not have been called yet, or perhaps you're using several JS files and one needs to test a variable that may or may not have been created by one of the other files, then the only way to do it is with:
if (typeof variable != "undefined") {
Since you're using strict equality testing, the following will all return true:
false
undefined
null
0
The only time your check will return false is when you pass in an empty string.
Is that what you want?
Check out coffeescript's existential operator, by searching "The Existential Operator" on this page: http://coffeescript.org/
The functional problem with your approach is that is that you may inadvertently assign a blank string to variable at some point prior in your script and your logic block will now do the wrong thing.
From a stylistic standpoint your solution is less desirable because your intent to check the existence of the variable is not clear. Someone who was just reading through your code for this the first time might misunderstand what you wrote to mean "I'm expecting there to be a variable named variable set to the blank string" as opposed to "Do something if this variable does not exist."
This might be highly subjective, but my recommendation is to avoid code, that needs to check, whether a variable is set (a.o.t. has some value or type).
Consider this snipplet
var a=false;
if (some_condition) a="Blah";
if (typeof(a)=='string') ....
if (a===false) ...
this makes sure, a is always set, while keeping it easily differentiable from '', null or 0

What are unused variables set to?

Particularly for localStorage.foo
For Safari it is set to:
undefined
For Firefox it is set to:
null
Does anyone know the values for Chrome and IE?
Why is it different? Just random choices by browser programmers?
It's always undefined. Perhaps your observation method is what led you to believe the values are different in different browsers.
Oh, I'll qualify that statement for old versions of IE, which might do some other thing for all I know. I bet they use undefined also.
Ah - Mr. Protagonist has an interesting point. On any normal object, a non-existent property will be null. However, Firefox does indeed seem to report null as the value of a non-existent property specifically of localStorage. Hmm... My vote would be that that's a bug, but I'll check the w3c spec (or proto-spec or whatever it is).
The "value" undefined isn't really a value; it's more like the Buddhist mu — it's kinda like saying, "what you asked for doesn't make sense". The value null in JavaScript is treated differently than undefined. Thus:
var a = {};
var b = a.banana;
The variable "b" will be undefined. It's weird, but it lets you tell the difference between a property being present but null and a property being missing. (Of course, the in operator lets you figure that out too.)

How dangerous is it in JavaScript, really, to assume undefined is not overwritten?

Every time anyone mentions testing against undefined, it's pointed out that undefined is not a keyword so it could be set to "hello", so you should use typeof x == "undefined" instead. This seems ridiculous to me. Nobody would ever do that, and if they did it would be reason enough to never use any code they wrote... right?
I found one example of someone who accidentally set undefined to null, and this was given as a reason to avoid assuming that undefined isn't overwritten. But if they'd done that, the bug would have gone undetected, and I fail to see how that's better.
In C++ everyone is well aware that it's legal to say #define true false, but nobody ever advises you avoid true and use 0 == 0 instead. You just assume that nobody would ever be a big enough jerk to do that, and if they do, never trust their code again.
Has this ever actually bitten somebody where someone else assigned to undefined (on purpose) and it broke your code, or is this more of a hypothetical threat? I'm willing to take my chances to make my code marginally more readable. Is this a really bad idea?
To reiterate, I am not asking for how to protect against reassigned undefined. I've seen those tricks written 100 times already. I'm asking how dangerous it is to not use those tricks.
No, I never have. This is mostly because I develop on modern browsers, which are mostly ECMAScript 5 compliant. The ES5 standard dictates that undefined is now readonly. If you use strict mode (you should), an error will be thrown if you accidentally try to modify it.
undefined = 5;
alert(undefined); // still undefined
'use strict';
undefined = 5; // throws TypeError
What you should not do is create your own scoped, mutable undefined:
(function (undefined) {
// don't do this, because now `undefined` can be changed
undefined = 5;
})();
Constant is fine. Still unnecessary, but fine.
(function () {
const undefined = void 0;
})();
No proper code will do such a thing. But you can never know what some wannabe-smart developer or a plugin/library/script you are using did. On the other side, it's extremely unlikely and modern browsers will not allow overwriting undefined at all, so if you are using such a browser for development you'll quickly notice if any code tries to overwrite it.
And even though you did not ask for it - many people will probably find this question when looking for the more common "how to protect against redefined undefined" issue, so I'll answer that anyway:
There's a very good way to get a truly undefined undefined no matter how old the browser is:
(function(undefined) {
// your code where undefined is undefined
})();
This works because an argument that is not specified is always undefined. You can also do it with a function that accepts some real arguments, e.g. like this when you are using jQuery. It's usually a good idea to ensure a sane environment in this way:
(function($, window, undefined) {
// your code where undefined is undefined
})(jQuery, this);
Then you can be sure that inside that anonymous function the following things are true:
$ === jQuery
window === [the global object]
undefined === [undefined].
However, note that sometimes typeof x === 'undefined' is actually necessary: If the variable x has never been set to a value (contrary to being set to undefined), reading x in a different way such as if(x === undefined) will throw an error. This does not apply to object properties though, so if you know that y is always an object, if(y.x === undefined) is perfectly safe.
There's a simple solution to that: compare against void 0 which is always undefined.
Note that you should avoid == as it may coerce the values. Use === (and !==) instead.
That said, the undefined variable may be set by error if someone writes = instead of == when comparing something against undefined.
Only you know what code you use, and therefore how dangerous it is. This question can't be answered in the way you've clarified you want it answered.
1) Create a team policy, disallow redefining undefined, reserving it for its more popular usage. Scan your existing code for undefined left assignment.
2) If you don't control all the scenarios, if your code is used outside situations you or your policies control, then obviously your answer is different. Scan the code that does use your scripts. Heck, scan web for statistics of undefined left assignment if you wish, but I doubt that's been done for you, because it's easier to just pursue answer #1 or #3 here instead.
3) And if that answer isn't good enough, it's probably because, again, you require a different answer. Maybe you are writing a popular library that will be used inside corporate firewalls, and you don't have access to the calling code. Then use one of the other fine answers here. Note the popular jQuery library practices sound encapsulation, and begins:
(function( window, undefined ) {
Only you can answer your question in the specific way you seek. What more is there to say?
edit: p.s. if you really want my opinion, I'll tell you it's not dangerous at all. Anything that would be so likely to cause defects (such as assigning to undefined, which is obviously a well-documented risky behaviour) is itself a defect. It's the defect that is the risk. But that's just in my scenarios, where I can afford to hold that perspective. As I'd recommend you do, I answered the question for my use-cases.
It's safe to test against undefined. As you already mention. If you get to some code that overrides it (which is highly improvable), just don't use it anymore.
Maybe if you are creating a library for public use, you can use some of the techniques to avoid the user change it. But even in this case, it's their problem, not your library.
You can use undefined in your code when coding for browsers supporting ECMAScript 5.1 as it is immutable according to the language specification.
Also see this compatibility table or this caniuse ECMAScript 5 to see that all modern browsers (IE 9+) have implemented immutable undefined.
It's not dangerous at all. It can only be overwritten when running on an ES3 engine and that's not likely to be used any more.
First of all, if your code breaks it's probably not because some other developer out there "is trying to be a jerk" as you put it.
It's true that undefined is not a keyword. But it is a global level primitive. It was intended to be used like this (see "undefined" at developer.mozilla.org):
var x;
if (x === undefined) {
// these statements execute
}
else {
// these statements do not execute
}
The common alternative to that (also from MDN) and in my opinion the better way is:
// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
// these statements execute
}
if(x === undefined){ // throws a ReferenceError
}
Which has a couple of advantages, the obvious one (from the comments) is that it does not trigger an exception when x is not declared. It's also worth noting that MDN also points out that it is important to use === over == in the first case because:
var x=null;
if (x === undefined) {
// this is probably what you meant to do
// these lines will not execute in this case
}
else if (x == undefined) {
// these statements will execute even though x *is* defined (as null)
}
else {
// these statements do not execute
}
This is another often overlooked reason why it is probably better to just use the second alternative in all cases.
Conclusion: It's not wrong to code it the first way, and certainly not dangerous. The argument you've seen that you use as an example against it (that it can be overwritten) is not the strongest argument for coding the alternative with typeof. But using typeof is stronger for one reason specifically: it doesn't throw an exception when your var is not declared. It could also be argued that using == instead of === is a common mistake in which case it's not doing what you expected it to. So why not use typeof?

Categories