In browser-based JavaScript, you can do something like this:
var foo = "foo";
(function() {
var foo = "bar";
console.log(foo);
// => "bar"
console.log(window["foo"]);
// => "foo"
})();
Is there any way to do something similar in Node, which lacks a window object?
If you want an environment agnostic approach, for example, when writing code to work on both the browser and Node.js, you can do something like this in global code at the top of your JavaScript file:
var globalObject = typeof global === "undefined" ? this : global;
and then use globalObject similar to how you would window in the browser context and as you would use global in the Node.js context.
Note that you must declare a variable without var for it to be part of the global object in Node.js.
You can access global variables using global keyword in nodejs.
Note:- There is one rule in nodejs only those variables willl be global variables which dose not have declared using var.
Like if you have declareation like bellow
foo = "sample"; //this you can access using global
But
var foo = "sample"; //this you cann't access using global.
The second one is not actually in global scope, it's local to that module.
From node global docs
In browsers, the top-level scope is the global scope. That means that
in browsers if you're in the global scope var something will define a
global variable. In Node this is different. The top-level scope is not
the global scope; var something inside a Node module will be local to
that module.
Related
var myVariable = 3;
console.log('global', globalThis.myVariable);
I tried running the code using node file.js, but keep getting the result:
global undefined
Can someone explain to me what exactly is going on here?
I find this from Node documentation:
In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.
and Global object:
In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.js this is not the case.)
It mean that when you declare var myVariable = 3; it doesn't go into the node global object, you can try to print global object out.
Try to assign value to globalThis variable
globalThis.myVariable = 3;
console.log('global', globalThis.myVariable);
In Node Js scoping, any variable declared in the root of a module (a particular JS file) is a module-level variable.
var test = 'This string is global to this module';
function foo() {
console.log(test);
}
Node Js also has the Global Namespace Object.
This object is accessible in any module.
global.test = 'This string iscan be accessed by any module via the gloabl namespace object';
function foo() {
console.log(global.test);
}
var global.myVariable = 3;
console.log('myVariable')
I did not check the code though
I am working on a javascript file with javascript functions that are not inside a closure. Obviously the function is callable by the console.
I know that adding a closure is best practice. But while tinkering i found that if I add in my file
window.myFunction = {}
the function becomes unavailable through the console.
Is this safe ?
All global variables/functions in Javascript (Browser) are a property of the window object:
var x = "foo";
console.log(window.x); //foo
It's not best practice to pollute the global scope, but it isn't "unsafe" if you control which scripts your page uses. (Although I don't recommend using global variables)
If you do need to have a global variable, consider using a name that you know other script won't use:
(function(window, undefined){
var privateVar = 5;
window.mySite = {
foo: "bar",
func: function(){
return "foo";
}
};
})(window);
console.log(window.mySite.func()); //"foo"
console.log(privateVar) //undefined
Now outside of the IIFE (Immediately-Invoked Function Expression) you can use window.mySite or just mySite, while privateVar won't be accessible.
More info on the window object here
What I mean is does node.js have object that are global function methods of. Like this in browser:
function myGlobalFunction() {
console.log(this === window);
}
myGlobalFunction();
=> true
The closest equivalent in node is global. I'm not sure if it translates in all of the same ways, but if you open a REPL and type in this === global, it will return true.
Here's a discussion on the global object, though some it the information may be deprecated as it's pretty old: 'Global' object in node.js
Yes, the global variable is the global object in Node.js
From the docs:
global# {Object} The global namespace object. In browsers, the
top-level scope is the global scope. That means that in browsers if
you're in the global scope var something will define a global
variable. In Node this is different. The top-level scope is not the
global scope; var something inside a Node module will be local to that
module.
I'm using some libraries (like for example Less.js & Dojo) which require global config variables. For example:
less = { ... };
dojoConfig = { ... };
This works ok, but I'm wondering, should I declare this variables explicitly on window?
window.less = { ... };
window.dojoConfig = { ... };
What are pros & cons of each approach? what are pros & cons of referencing this variable from the actual code like (not considering possible name conflicts with local variables):
var somethingNew = dojoConfig.something;
The only thing I can think of is that code without window is prettier :)
If you start running your code in strict mode, you'll find that it's illegal to create implicit globals by excluding var or window..
IMO, it's just always a better practice to make your declarations explicit. For globals, that's either window.foo or var foo if you're in the global variable scope.
As far as referencing the existing global, it's just like any other variable at that point, so you don't really need window. for that purpose, though you could use it if the variable is shadowed by a local variable with the same name.
Explicitly attaching properties to window is easier to maintain than implicit global variable declarations. If you need to be flexible about the environment, you can use the following syntax:
//Here, "this" refers to the window when executed inside the browser
(function() { this.prop = "value" })()
console.log(window.prop === "value") // true
Within that function, you can add your private logic and expose the needed variables as needed. Also, you can name that function and attach those properties to any object you bind it to via function.prototype.bind
By the way, implicit globals also won't work in strict mode.
JavaScript normally follows the function scope i.e. variables are accessible only within the function in which they are declared.
One of the ways to break this convention and make the variable accessible outside the function scope is to use the global window object
e.g.
window.myVar = 123;
My question is are there any other ways in JavaScript/jQuery to make the variable accessible outside the function scope?
Not with variable declarations, no. You can obviously declare a variable in an outer scope so that it's accessible to all descendant scopes:
var a; // Available globally
function example() {
a = "hello"; // References a in outer scope
}
If you're not in strict mode you can simply remove the var keyword. This is equivalent to your example:
// a has not been declared in an ancestor scope
function example() {
a = "hello"; // a is now a property of the global object
}
But this is very bad practice. It will throw a reference error if the function runs in strict mode:
function example() {
"use strict";
a = "hello"; // ReferenceError: a is not defined
}
As you wrote, variables are only visible inside the function in which they were defined (unless they are global).
What you can do is assign variables to the function object itself:
function foo() {
foo.myVar = 42;
}
console.log(foo.myVar); // outputs "undefined"
foo();
console.log(foo.myVar); // outputs "42"
But I would advise against it. You should really have a very good reason to do something like this.
You can define them as part of a global object, then add variables later
// Define your global object
var myObj = {};
// Add property (variable) to it
myObj.myVar = 'Hello world';
// Add method to it
myObj.myFunctions = function() {
// Do cool stuff
};
See the link below:
Variable declaration
Also, you can declare it without the var keyword. However, this may not be a good practice as it pollutes the global namespace. (Make sure strict mode is not on).
Edit:
I didn't see the other comments before posting. #JamesAllardice answer is also good.