Previous posts on Perfection Kills JavaScript quiz: 1, 2.
3)
(function(x){
delete x;
return x;
})(1);
Correct answer: 1.
The line of code delete x;
does not actually delete x, so the immediately invoked function returns the value of x, i.e. 1. To check whether the line delete x;
deletes x, we can modify the code in the following way:
(function(x){
console.log(delete x);
return x;
})(1);
The logged value in this case is false, and delete
only returns false if the property cannot be deleted.
The best explanation of why x is not deleted can be found here: http://perfectionkills.com/understanding-delete/. When a function is executed, its arguments become properties of the function's activation object: activation_object.x = 1
. These properties have DontDelete attribute, hence they cannot be deleted.
All posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.