Set global variable inside `$(document).ready(function()` - javascript

I try to set a global variable inside $(document).ready(function()
$(document).ready(function(){
$(".editCommentLink").on("click", function (e) {
e.preventDefault();
var window.comment_id = $(e.target).attr("id");
It throws error:
var window.comment_id = $(e.target).attr("id");
Uncaught SyntaxError: Unexpected token .
When try to place var comment_id elsewhere, it constantly report undefined

window.myVar or window["myVar"] is an explicit way to refer to a global variable.
A variable is a global variable if it's declared outside of a function (with or without "var"), or if it's declared inside a function without using "var", or if it's declared as window.myVar or window["myVar"].
A variable is declared by either assigning a value to it, or by using the keyword var.
One case where it's useful to refer to a global variable as window.myVar is if you're inside a function that has a local variable called myvar. In that case, myVar refers to the local variable, while window.myVar refers to the global variable.
window.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable.
Using window. is not necessary but is frequently used as a convention to denote that a variable is global.
Globals are generally to be avoided. You should define variables within the scope of functions.

Var is not required. Just use window.global_variable = “your_value”
For more information about variable scope in javascript please read following article of MDN lexical scope

You should omit the word var in var window.comment_id = ....

Comments of # CertainPerformance and #Li357 perfectly described:
You cannot declare a variable that's a property of another with var. Simply assign to the dot property instead
you can access directly or use window.Variableanme
JavaScript has two scopes – global and local. Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code. Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions. Because local scope in JavaScript is created by functions, it’s also called function scope. When we put a function inside another function, then we create nested scope.

Related

Not understanding the concept of local and global variables

Ok so just a quick one... I REAAAAAALLLLY am not understanding scope at all. Do some reason whenever I put a variable inside of a function it's undefined. It seems the only way it works it to declare it OUTSIDE of a function. So what gives? Am I simply misunderstanding the concept of local and global variables? Because it seems global variables are the only ones that work...
Edit:
Simple example...
let a = 'something';
function myFunction() {
// Code block
};
This works 👆
But the following gives me undefined variables:
function myFunction() {
let a = 'something';
// Code block
};
First lets take a look at the differences between local and global variables.
LOCAL VARIABLES - Any variable defined inside of a function or loop. If the variable is defined in a certain function/loop, it can only be accessed in that function/loop.
For example:
function number() {
let a = 0;
// Can access a here.
}
// Cannot access a here.
GLOBAL VARIABLES - Any variable that is not defined inside of any function or loop. These variables can be accessed anywhere.
For example:
let b = 0;
function number() {
// b can be accessed here.
}
// b can be accessed here.
The scope of a variable is where it can be accessed in. For ex, a scope of a local variable that is defined inside of function number() is the number() function since it can only be accessed there.
One more quick thing (Credit to Mikael Lennholm) var doesn't scope a variable to a loop (or any non-function statement block), it only scopes it to the current function. To scope a variable to any statement block you have to use let/const
Now let's look at your examples:
Here is the first example:
let a = 'something';
myFunction();
function myFunction() {
console.log(a);
};
That works fine, and that's what you said.
Here is the second example you said doesn't work:
function myFunction() {
let a = 'something';
console.log(a);
};
myFunction();
But, if you click the run button, you'll actually see it does work, it does get logged. If you after this go and check in the console what the variable a is of course it will be undefined, since a can be only accessed in the myFunction() function, and the console is not in that function.
You said that the script doesn't work, it's most probably because of something else (if it was because of this there would be an error in the console). You can try posting the website here and I can help you.
Hope this helped you :)
Global variables are variables that you have access to them anywhere in your codes.
Local variables are limited to their scopes like a function, module, class and etc.
if you define a local variable it can be accessible in the nested level like closures.
if you define a global variable and you define the same name as local variable , the local overwrite the global, then be careful.

Variable, defined insde for loop of window.onload function, gets global scope at window level

I have a function set to window.onload event. Inside that function I have a for loop, that defines variable unit on every iteration as a new object of type GAME.Unit. As a result of this, I have a variable unit in window scope, holding last created object! I always thought, variables inside loop are loop-oriented. I double-checked and there are no other declarations on unit variable anywhere in my code. What am I doing wrong?
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.
— MDN.
var scopes a variable to the function, not the loop.
To scope a variable to a block, use let.

why if statement isn't looking for a variable in global scope

I am trying to understand scoping in JS.Here i have an example which has a variable in global scope called check.It has a truthy value i mean 1.Then inside a function called main which doesn't have a variable called check but has an if statement which checks whether there is a check variable or not ,upon which it reassign another value to check variable.Then prints it out.if i use
if(check){}
it prints undefined.Here i have some questions:
1. check variable is declared in global scope.It means it has access everywhere.Then even if the IF statement fails it should print the globally assigned value which is 1 instead of undefined.Why it prints undefined instead of 1??
2. main function scope doesn't have a check variable.When if fails to find check inside main function's scope ,why it doesn't look for it in global scope??
(function(){
var check=1;
function main(){
if(check){
var check=10;
}
document.write(check);
}
main();
})();
JavaScript only has function scope and something called hoisting. Every variable declaration inside a function gets put at the beginning of the function. Thus, your code is equivalent to
var check=1;
function main(){
var check; // = undefined
if(check){ // block doesn't create scope
check=10;
}
document.write(check);
}
The local variable check shadows the outer variable check.
JavaScript will look up the chain for the most local variable it can find. Basically, local scope trumps global scope.
This is one of the potential pitfalls with global scope, and is why it should be avoided, since it creates clashes with local variables.

Declaring Empty Variables to make them global

In a JavaScript environment can I declare a variable before a function to make the variable reachable on a global level.
For instance:
var a;
function something(){
a = Math.random()
}
Will this make "a" a global variable?
or is using...
var a = function(){
var b = Math.random();
return b;
}
document.write(a())
Really the only way to do it?
Is there a way to make "b" global other than calling the function "a()"?
There are basically 3 ways to declare a global variable:
Declaring it in the global scope, outside of any function scope.
Explicitly assigning it as a property of the window object: window.a = 'foo'.
Not declaring it at all (not recommended). If you omit the var keyword when you first use the variable, it'll be declared globally no matter where in your code that happens.
Note #1: When in strict mode, you'll get an error if you don't declare your variable (as in #3 above).
Note #2: Using the window object to assign a global variable (as in #2 above) works fine in a browser environment, but might not work in other implementations (such as nodejs), since the global scope there is not a window object. If you're using a different environment and want to explicitly assign your global variables, you'll have to be aware of what the global object is called.
Will this make "a" a global variable?
A var declaration makes the variable local to the enclosing scope, which is usually a function one's. If you are executing your code in global scope, then a will be a global variable. You could as well just omit the var, then your variable would be implicitly global (though explicit declaration is better to show your intention).
Is there a way to make "b" global other than calling the function "a()"?
Your b variable is always local to the function a and will never leave it, unless you remove the var.
Before you think of making a variable global scope, you should consider JavaScript global namespace pollution. The more global variables you declare, the more it is likely that you application will get into conflict with another application's namespace and break. As such, it is highly important minimize the number of global variables.

window.variableName

I am going through some code and at the beginning of the script we have var emailID = email. Later on, the code refers to emailID by going window.emailID. I am wondering what are the rules that allow you to refer to a variable by going window.variableName?
I cannot post my script online as it is directly related to my work and would violate my contract.
window.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.
Globals are generally to be avoided. You should define variables within the scope of functions.
Global variables in JavaScript are attached to the "global object", which in a browser environment is aliased to window object - this is why you can refer to a global variable either as variableName or window.variableName.
It's also worth mentioning that using global variables in JavaScript is not considered good coding practice.
Here's a good and very detailed explanation.
window.myVar or window["myVar"] is an explicit way to refer to a global variable.
A variable is a global variable if it's declared outside of a function (with or without "var"), or if it's declared inside a function without using "var", or if it's declared as window.myVar or window["myVar"].
A variable is declared by either assigning a value to it, or by using the keyword var.
One case where it's useful to refer to a global variable as window.myVar is if you're inside a function that has a local variable called myvar. In that case, myVar refers to the local variable, while window.myVar refers to the global variable.
Global Variables in JavaScript
var no =10;
function getNo()
alert(no); // 10
}
getNo();
When a global variable is set, it's added to the window object!
var no =10;
function getNo()
alert(window.no); // 10
}
getNo();
We can direct set window variable.
function setNo(){
window.no=100;
}
function getNo()
alert(window.no); // 100
}
setNo();
getNo();
For pure theoretical explanations (as I encountered this "issue" myself) and easy to digest information you can look at the problem as this:
var myName = "Bob" equals to - globalObject(Window) = { myName: "Bob" }
so when you declare a variable, that variable name is passed to the window object as a property and it's value as a property value. That's why you can call the variable as an object method of the window object, basically.
It is used to define global variable in JavaScript.
globalVar = "Hello World";
function function1(){
alert(window.globalVar);
}
function1();
This will print "Hello World" in the popup.
function function1(){
globalVar = "Hello World";
alert(window.globalVar);
}function function2(){
alert(window.globalVar);
}
function1();
function2();
This will create two popups with value "Hello World", one from function1() and another from function2().
So, by using window we can call a variable from any scope in javascript.

Categories

Resources