Bruno Bruno - 28 days ago 10
Javascript Question

JavaScript function default parameter - Strange behaviour

That's one of the strangest things I've seen in a while...

I was playing with JavaScript default parameters, and was curious to know if they are resolved taking into account the context of execution of the function.

I prepared this simple test:



var o = {
a: 42,
fn(b = this.a) {
console.log(b);
}
};

o.fn();





As you can see, the answer to my initial question is YES.

And if you copy and paste the snippet into dev tools you'll get the same result... unless you've open dev tools while visiting twitter.com; in that case the result is
undefined
.

I experienced the same behaviour also if the host object is an array



var arr = [
42,
function fn(b = this[0]) {
console.log(b);
}
];

arr[1]()





Do you have any idea why this could possibly happen?

Answer

Twitter overwrites the console.log function.

Comments