Krystian Krystian - 1 year ago 84
Javascript Question

Why do we make "window.x = x = ..." in javascript functions?

In WebRTC official sample I have found in few places the following code:

var pc1;
...//some code
function call() {
//...some code
// Add pc1 to global scope so it's accessible from the browser console
window.pc1 = pc1 = new RTCPeerConnection(servers);

On W3C Tutorials ( I've found, that:

var carName = "Volvo";

// code here can use window.carName

Because in HTML, window object is a global scope.

So there is my question- is there any logic, that they used

window.pc1 = pc1 = new RTCPeerConnection(servers);

instead of simple

pc1 = new RTCPeerConnection(servers);

I'm not a javascript developer, so that's a little bit confusing to find such statement in official WebRTC tutorial when yesterday I've just read that such statement is illogical.

Answer Source

In the code snippet as you post it no there is no reason this is done as pc1 will be accessible in the global scope anyway.

It is however, due to the exact same scoping nature of javascript for developers to wrap code in iffe's to avoid polluting the global scope with all these variables.

If the code snippet was wrapped in an iffe then it would make a difference to declare as in that statement because otherwise (and as the comment above suggests) the variable would not be accessible on the browser console.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download