Javascript delete operator - javascript

I read a book about javascript that said:
var o = {x:1 , y:2 };
delete o ; // Can't delete a declared variable so returns false;
However, the book also states that the variables declared outside any function scope are properties of the global object.
Why aren't we allowed to delete it then if it is a property of the global object?

By saying:
var o = {x:1 , y:2 };
in the top level scope, you are declaring a global variable, which can not be deleted. It does create a property on the global object (which is aliased to the window object in browsers), but it is a special property indeed. However, if you make the declaration like:
o = {x:1 , y:2 };
then you are setting a property on the global scope (remember, the window object) implicitly. The two are similar, but different enough. The delete operator removes an implicit property from an object, but will not delete a variable created on the global object.
Edit, found a more thorough answer
https://stackoverflow.com/a/4862268/1443478

Since O is already declared and have properties you cannot use delete on the object. You can use
var o = {x:1 , y:2 };
delete o.x ;
and delete properties here is a DEMO for the same.

first you have to know what is the work of delete operator.let me explain---
"The delete operator removes a property from an object".here i say it removes an object property not a variable.
in your code you declare a variable.not an object so delete does not work.i think you understand.
o = {x:1 , y:2 };
delete o ;
but the code above is right i think. why?
because here o is a property of the global object which is also an object so it work properly.the link which can help you is delete operator
it is my first answer.be happy with coding.

Related

Why I can not delete global varaible in JS?

Using Chrome I passed in console this name of global variable:
multiConfig
And get result:
multi: {type: "1", containerId: "mp", go: {…}}
__proto__: Object
I try to delete this variable by click:
if (window['multiConfig']) {
delete window['multiConfig'];
}
And I get this error:
ERROR TypeError: Cannot delete property 'multiConfig' of [object Window]
Why?
You cannot delete a window variable, but you can unset it:
window['multiConfig'] = undefined;
Reason:
The window object is not configurable.
You can refer to this - How to unset a JavaScript variable?
Variables declared with var are added as properties on the global window object and cannot be deleted with the delete operator.
From MDN - var:
In the global context, a variable declared using var is added as a
non-configurable property of the global object. This means its
property descriptor cannot be changed and it cannot be deleted using
delete.
Reason for this is also explained:
The property created on the global object for global variables, is set
to be non-configurable because the identifier is to be treated as a
variable, rather than a straightforward property of the global object.
JavaScript has automatic memory management, and it would make no sense
to be able to use the delete operator on a global variable.
Also note that trying to delete a property set on of global window object for variables declared with var fails silently in non-strict mode and throws a TypeError in strict-mode.
Also note that you can delete a property from the window object if is set explicitly.
var a = 1; // can't be deleted
window.b = 2; // can be deleted
delete window.a;
delete window.b;
console.log(window.a);
console.log(window.b);

How does IIFE works when I assign an IIFE to a variable?

I was confused with this following code in javascript.
var x=(function(){
var customObject = function(){};
customObject.prototype.sayHello=function(){
alert("hello");
};
return customObject;
})();
//var y=new x();// If I uncomment this line and comment the next line "var
//y=x;" the code works
var y=x;
y.sayHello();
This code doesn't say hello but it does when I remove the comment. I read that IIFE executed immediately after it is defined. So, it should assign the customObject to x directly.
My question is that why I need to create a new instance of x to say hello. It is not clear to me how IIFE is working here.
Please help me to understand this concept. Thank you in advance :-) .
You're correct that the customObject is assigned to x. But customObject (and therefore x) does not have a sayHello property. It has a prototype property, and that has a sayHello property.
When you do y=x and then y.sayHello(), you're trying to call customObject.sayHello, which doesn't exist.
When you do y=new x(), you create an object whose prototype is the customObject.prototype object. Then, when you call y.sayHello(), the sayHello function is found via the prototype chain.
This isn't really related to your use of an IIFE. You'd get the same result if you just wrote:
var x = function() {}
x.prototype.sayHello = function() {
alert("hello");
}
instead of the IIFE.
Ok, I got your confusion here.
First, IIFE is doing its job correctly here. It executes and returns customObject to variable x
This is what it is supposed to do.
Now coming to your actual question, why I need to create a new instance of x to say hello?
You may have read, all classes(functions) have a prototype and all variables have __proto__ property.
Anything set on a prototype is accessible to instances of that constructor.
For ex:
var myName = "apl"; // a simple string
console.log(myName.toUpperCase()) // outputs: APL
How do you think we were able to call toUpperCase() on our variable name?
We could, since typeof(myName ) turns out to be string. So myName would be able to call any properties/methods which are set on String.prototype.
In short, __proto__ property on myName should be set to String's prototype
i.e myName.__proto__ === String.prototype // true since myName is an instance of String
Hence, in your case, you need y to be an instance of x. Only then you would be able to access methods set on x prototype which in turn is customObject.prototype

Javascript: On Deletion Behavior

I am reading an interesting article on understanding delete in JS.
I understand that properties created via variable declaration cannot be deleted, or more precisely, has the DontDelete attribute, while properties created via property assignment can be deleted.
But I'm confused with how property overloading works with this idea:
> var GLOBAL_OBJECT = this;
undefined
> var declared = "I cannot be deleted";
undefined
> delete declared;
false
> assigned = "I can be deleted";
'I can be deleted'
> delete assigned;
true
> // Now, I will override `declared` ...
> declared = "I am overrided - now deletable?";
'I am overrided - now deletable?'
> declared;
'I am overrided - now deletable?'
> delete declared;
false
This seems to me is that property attributes are predetermined when properties are created within the Variable Object. So, when you attempt to override a property, you can expect that it will be overridden but that the property attributes will not.
Is this correct?
What you call "override" a property is actually a regular assignment. You simply change the value of the variable. All the attributes of the variable remain the same, including the DontDelete you mentioned.
In the case of the assigned variable in your example, the variable was defined implicitly, not declared with the var keyword and that is what makes it able to be deleted.
I have read the article too hastily.
Here is a quote from the article that addresses this topic,
Note that it is during property creation that attributes are determined (i.e. none are set). Later assignments don't modify attributes of existing property. It's important to understand this distinction.

why can't global variables be deleted?

How come a properly declared global variable can't be deleted?
I don't know if this is across all program languages, but I know that in JavaScript it can't be deleted.
Source: Javascript the Definitive Guide O'Reilly.
When you use global variables and you want to be able to delete them, you should easily define them in a global object, without using var in your statement, like:
let's say you want to define a global varible in your code, and you need to be able to delete them whenever you want, so if you do:
function myfunc(){
var name = "Robert";
console.log(delete name);
}
and call it in your console you would have, false as the result of delete statement, which means it has not got deleted, but if you do it like:
function myfunc(){
var obj = {};
obj.name = "Robert";
console.log(delete obj.name);
}
then your result would be true, which means it gets deleted now.
now for global object if you create it like:
window.myobj = {};
then you can delete it and it actually get deleted:
delete window.myobj;
or
delete window["myobj"];
The thing is when you create your variable using var, in the window context, although it is on object in the window, but it doesn't get deleted, for instance if you do:
var myobj = {};
in the browser dev console, it gets defined in the window, and you can have it like:
window.myobj
but you can not delete it, because you have defined it in a var statement.
But do not forget to set it to null, if you really want it to get deleted from memory:
window["myobj"] = null;
delete window["myobj"];
As was stated in this answer by user Eric Leschinski
Delete a variable in JavaScript:
Summary:
The reason you are having trouble deleting your variable in JavaScript
is because JavaScript won't let you. You can't delete anything created
by the var command unless we pull a rabbit out our bag of tricks.
The delete command is only for object's properties which were not
created with var.
JavaScript will let you delete a variable created with var under the
following conditions:
You are using a javascript interpreter or commandline.
You are using eval and you create and delete your var inside there.
or you can set null to an variable which will behave like a deleted object
When variable is created in global scope then automatically DontDelete property is added to the variable and set to the true. That is the reason global variables (or functions too) can not be deleted.
For other variables that property is false so those can be deleted.
For more clarity you can refer the article : understanding delete
With ECMAscript 5, the properties added to an object now have attributes which allow you more control over the object. These attributes are:
value - The actual value of the property
writable - If the property can/cannot be changed.
configurable - If set to false,any attempts to change its attributes will fail in strict mode (and will return false in non-strict mode)
enumerable - if the property can be iterated over when the user does for (var prop in obj) {}
These attributes can be checked with another API exposed by Ecmascript 5 called:
Object.getOwnPropertyDescriptor(obj, prop)
Now, when you create a global variable WITHOUT the 'var' keyword, like so:
sum = function (a, b) { return a + b; }
then this property 'sum' get created on the window object with configurable attribute set to true.
console.log(Object.getOwnPropertyDescriptor(window, "sum"))
... and therefore this property CAN be deleted from the window object.
delete window.sum //returns true
But when you create a property with the var keyword, then configurable property is set to false like so:
var multiply = function (a, b) { return a * b; }
console.log(Object.getOwnPropertyDescriptor(window, "multiply"))
... and now, this property CANNOT be deleted.
delete window.multiply //returns false in non-strict mode
Courtesy: John Resig

How to delete object from window javascript

I need to delete one object in my case. so i am using "delete" keyword but after using it, I am able get the value again
var test= {};
test[0]="111";
test[1]="555";
delete test;
alert(test[0])
You can't delete a local variable that has been declared with var.
You can only delete properties of objects - this happens to also include global variables which are implicit properties of the window object.
You can delete properties on objects, you can't delete variables.
Either assign undefined or let the variable fall out of scope.
As has been mentioned, you can't delete a variable that has been declared with var.
For example, if you were to change your code to the following - so that test is an explicit property of window - the delete will work.
window.test = [];
window.test[0]="111";
window.test[1]="555";
delete window.test;
alert(window.test[0]);
Whenever delete, it returns a boolean that tells wether it could delete the var or not. In this case, it returns false:
delete test; // false
You can just set test to undefined:
test = undefined;
you can use test = undefined to make remove object value

Categories