Why do I pass the window object in to the module pattern? - javascript

Here is a self executing anonymous method.
It seems to be good practice to pass in window as global. If window is available everywhere already why is this done?
(function (global) {
/* my code */
global["someName"] = someObject;
})(window);

It skips the code having to do a scope lookup since global is scoped inside the function.
Edit -- It's a performance optimization. Scoping in javascript is limited to function scope. global in this case is being defined within that scope, so when the code hits global[...] it looks at it's immediate scope (within the function) and finds global right away. Without that it would then have to move up to the closure scope, which in this case is the global javascript namespace, and search that entire scope for window.

The browser's JavaScript interpreter has to determine the scope of any variables it finds, starting at the most local scope and working its way outward. Using a function closure with window as the parameter global reduces the need to extend further up the scope chain to find window.
window is available everywhere, but using global the way it is in your example is more performant.

Related

How does the 'window' object become the global object of a front end JS script?

Hello Stackoverflow community!
I kind of know what the window and global object is, but I would like to know how this works under the hood / behind the scene.
How does the browser add this window object as the global object to our script and why?
Thanks
Creation phaase a.k.a Global Execution Context.
When running code at the base level, JS engine will automatically do the following:
Create a global object, which means all your code will sit inside of this global object. If you are using in browser environment, this global object is window. It all depends on where do you execute your JS code.
Create a special variable called "this". At the global level, "this" would equal the Global (window) Object.
A reference to the outer environment if there is one. This means where something sits physically in the code you write and what's around it, a.k.a Lexical Environment

V8 / JS runtime: how are JavaScript window functions available without prefix "window"

I don't know much about the JS console but I'm moving into command line programming and it would be good to know my native environment before I start using shell/node in a foreign one
My guess is that all command line statements are invoked with (window) eval(/* whatever user typed before hitting enter/*) but this seems like horrible practice. The context is definitely bound as "Window" if I console.log(this) but I'm not sure why / how
It's almost like the user cd'd into the window object to set it as the context
All JavaScript has a global scope. In the browser, the global scope is called "window" and it is a reference to the window object. In node, it is called "global" and refers to the global JS namespace in node.
The "window" global in a browser has a bunch of properties on it. Things like "console" or "location". When you want to talk to those pieces of code, you can optionally prefix the call with "window.". Example: to log something to the console you can type:
window.console.log("HELLO");
or you can leave the "window." off of the call, like such:
console.log("HELLO");
The global "window" object in the browser is the only optional object on the page. Any time you see a reference to a variable that wasn't declared using "var" (or "let" and "const" in ES6), that means that the variable is just a property on the global object.

let statement application consequences

I found such an explanation why cycles with variable declared with var in node is faster than in chrome:
Within a web browser such as Chrome, declaring the variable i outside
of any function’s scope makes it global and therefore binds it as a
property of the window object. As a result, running this code in a web
browser requires repeatedly resolving the property i within the
heavily populated window namespace in each iteration of the for loop.
In Node.js, however, declaring any variable outside of any function’s
scope binds it only to the module’s own scope (not the window object)
which therefore makes it much easier and faster to resolve.
Curious about a let statement in Ecmascript6: does it make calculations faster using more block scope declared variables in loops or it is just a safety measure against name collisions?
The goal with let was to have better scoping mechanism in JavaScript (no more wrapping things in anonymous functions just for the sake of scoping). Any performance gains are just cherry on the top.

If code is placed within an anonymous function, why can I access it from the console?

I've noticed that Meteor's production ready code is concatenated, minified, and then wrapped in an anonymous function.
In theory, this should make the Meteor object and its methods inaccessible through the DOM / window object / console.
Why can I still access objects placed within an anonymous function through the console?
Javascript is function scoped, which means the outer function variables are accessible (and editable!) by inner functions. This goes all the way up to global (window) variables. For example:
(function() {
window.t ='foo';
})();
If you run that code in the console, then see what t is, you'll see you created/changed it from within the function. Meteor globally scopes a few variables (Meteor, check, etc.) so you can access them, in addition to any variables you scope yourself when you create a package. This is because each .js file is also an anonymous function & if you didn't export some variables, you'd have to write everything in 1 big file. By only exporting the variables you need, your project stays modular. Hope this helps!

Is there EVER a reason to NOT use "var" when initially declaring a Javascript variable? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 9 years ago.
I already know the difference between using "var" and not using "var" to declare a Javascript variable. Using "var" ensures that the variable exists as a distinct entity strictly within the local scope of the code block, whereas not using "var" would effectively make the variable global. I also know that if you declare a variable at the global level, it doesn't matter whether you use "var" or not.
So my question is, is there ever a situation where it would be better to NOT declare a variable using "var"?
So far, I'm under the impression that it never hurts to always use "var" to declare a variable. Are there exceptions to this?
Not really. In fact, in strict mode you cannot declare a variable without a scope or a var. So, if you were trying to declare a global variable you must do something like window.foo = "bar";
Granted, window.foo is really "set a property on the window object".. so it's not even really initializing a variable.
Your question assumes that you do have control over whether your variable declaration is the "initial" declaration. If you do have that control, then there is never a reason not to use var except when you are working inside of a function and specifically want to access a global variable and not create a local variable. In that case you must not use var or else the variable will become a local variable and you can never access the global variable with the same name from within that function.
When you are using variables in the global scope, you are technically making an error if the same variable name is declared twice using var. There is no way to control this from happening sometimes, which is why you will run into situations where you "can't" use var.
Update: the type of error I am referring to is something like this: error: Identifier 'x' has already been declared
This doesn't happen anymore (thankfully). It happened way too often in the late 1990s when JavaScript was new. Perhaps it was an error of the browser implementations. At at rate, don't worry about redeclaring variables with var anymore. (Redeclaring variables with let is still not permitted. For the let keyword, Redeclaring the same variable within the same function or block scope raises a SyntaxError.)
Let me explain the history of the practice behind my word "can't":
Starting with the old-fashioned "Hit-o-Meter" scripts, JavaScript programmers started noticing that their scripts generated error messages (for anyone looking at the console) when used in the "wild" when many different script elements in the page might use the same global variables. The solution to avoid the errors from showing up was to simply not declare the variable. (A warning would show up when the variable was implicitly declared by the first assignment to it, but all the other errors that happened by multiple variable declarations in many places on the page would be gone. So it was a question of a lesser evil versus a greater evil.)
If you have full control over all the scripts in the page, then you will have full control as your phrase says, "initially declaring a JavaScript variable." For example, you can use var when declaring a global variable in the top script, but not use var when using the same variable in another script element later in your page.
If you have no way of controlling whether a variable with the same name might have been declared before, and if you don't want to commit the possible evil of using a global variable which has never been initialized even by a prior script element, then you have the option that I use of using properties of "self" or other convenient window or document properties. For instance, I will write self.variable = 1, which will be free of any problems associated with redefining a variable. There are no errors or warnings generated regardless of whether this variable is being used for the first time or being re-used by my script after already being used by another script on the page.
(Note: currently self and window are considered to be equivalent, but there was a time in the days of framesets where it was considered better style to use self to store any global variables/properties--and it also saved a tiny bit of code.)
If you're in the global scope then there's no difference.
If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).
If you're not doing an assignment then you need to use var:
var x; // Declare x
Sometimes you have to not use var, to access or change certain global (window.variable) variables.

Categories

Resources