define variable with/without var prefix in javascript [duplicate] - javascript

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 8 years ago.
Is there a difference define variable in global scope between
var my_var;
and
my_var;

In global scope, there is no difference, unless you using it again: var my_var; will redeclare it, while my_var; will be simply useless expression.

There is a difference only when not in global context.
Ex1 (with var):
var x = 0;
(function(){
var x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 0
Ex2 (without var):
x = 0;
(function(){
x = 1;
alert('fx: '+ x);
})();
alert('gx: '+ x);
//fx: 1
//gx: 1

var is actually (re)declaring the variable in any current scope while second form is declaring it (globally?) unless it's been declared in a containing scope before. The second form is implicitly declaring, while first form is doing so explicitly.
Thus there is no difference in global scope, for it isn't contained in any other scope.

Related

why let keyword does not work with eval() [duplicate]

This question already has answers here:
Define const variable using eval()
(2 answers)
Closed 4 years ago.
function foo(str, a) {
eval( str );
console.log( a, b );
}
foo( "var b = 3;", 1 );
This works just fine, but when we use let instead of var, it does not work. Why?
Because eval introduces a new block of code. The declaration using var will declare a variable outside of this block of code, since var declares a variable in the function scope.
let, on the other hand, declares a variable in a block scope. So, your b variable will only be visible in your eval block. It's not visible in your function's scope.
More on the differences between var and let
EDIT : To be more precise eval + let do, in fact, create a Lexical Environment. See #RobG response in Define const variable using eval()

how to check global variable is defined or not in javascript [duplicate]

This question already has answers here:
How can I check for "undefined" in JavaScript? [duplicate]
(16 answers)
Closed 5 years ago.
I have one global variable in one JavaScript file and I using it in another JavaScript file.
but sometime we not use that JavaScript file(where we define Global variable) so I am getting error like var_Name is not defined error. So any way in JavaScript to check variable is defined or not and if its not defined than how to defined that variable run time.
var_Global?var_Abc=var_Global:var_Global=somevalue
when if global variable is defined than I want to assign that variable to another variable and if not than I want to define that variable.
Thanks.
file1.js
var x = 'foo';
file2.js
if (typeof x !== 'undefined') {
console.log('x is defined')
} else {
console.log('x is undefined')
//define x
x = 'foo'
}
Try below ways :
1. check for undefined
if (window.var_Global === undefined) {
window.var_Global = 'hi';
}
2. check for property
if (!window.hasOwnProperty('var_Global')) {
window.var_Global = 'hi';
}
3. using logical OR (||) operator
window.var_Global = window.var_Global || 'hi';
4. To check all the Global variables.
Object.keys( window ); // return array of all the global variables.
Do it like this:
file1.js
var x = 30;
file2.js
var x = x || 10;
This is a common technique to check for a variable value in such contexts, specially for non-strict mode.
So x || 10 will first see if x has any value? In case x is undefined due to non-inclusion of the the file, then it would get a value 10. If x was defined, it would take value from file1.js. You can change this value 10 to any value you want.

Difference between local and global variables in javascript? [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 6 years ago.
I noticed that in JavaScript, Inside a function some times a variable created without mentioning var before it.
For example :
function myfunction() {
x = 10;
var y = 10;
}
what is the difference between these both?
function myact() {
x = 20;
var y = 10;
console.log(x);
console.log(y);
}
myact();
console.log(x);
//y not available here
var is used for declaration. So, assigning without declaration will simply give it global scope meaning: it will first search if it is available in any scope stack above, if not creates the variable implicitly in global scope and assigns.
JS Docs says:
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.
Assigning a value to an undeclared variable implicitly creates it as a
global variable (it becomes a property of the global object) when the
assignment is executed.

How this function: (function(){}()) works? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 7 years ago.
I am reading some question where i find this code, it seems to be easy but i can't understand how this function:(function() {} ()) works.
Please help me to understand that how the value of var foo=6 and bar=9 is only consider in bar=bar+foo
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var foo = 6;
bar = 10;
(function () {
var foo = 5;
bar = 9;
}())
bar = bar + foo;
document.getElementById("demo").innerHTML = "Final value is " + bar;
</script>
</body>
</html>
That's a mix of some pretty bad variable usage, particularly the use of "undeclared" bar.
Basically, your global scope has 2 variables, foo & bar. At first they're initialized to 6 & 10 respectively. Then, a function is called that declares it own foo variable and sets that to 5. It also sets the global bar to 9. So now the global values are 6 & 9. The sum of these is then 15.
Since
var foo = 5;
has the var declaration, it's a local variable. The assignment has no effect on the foo variable outside the function. The global variable continues to have the value 6.
bar = 9;
doesn't have a var declaration, so it's just an assignment. Since the variable isn't declared locally within the function, this assigns the global variable, so the global variable now has the value 9.
When you add the two global variables afterward, you get 9 + 6 = 15.

variables scope confusion in javascript [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 9 years ago.
I was studying the concept of variable scope in JS, found this example on it:
(function() {
var foo = 1;
function bar() {
var foo = 2;
}
bar();
console.log(foo) //outputs 1
if(true) {
var foo = 3;
}
console.log(foo) //outputs 3
})();
output of this function is
1
3
Now I am confused how come foo gets gets value 3 in second log. even when foo is declared by using var in if statement. shouldn't the foo declared in if will have a new instance as it gets in bar()??
if does not introduce a scope block (I understand it does in some langauges). In JavaScript, only function() {} creates a scope block.
There are only two kinds of scope in Javascript; function scope and global scope.
The code inside the if statement doesn't have a scope of its own, so the variable inside the if statement is the same one as the one outside it.
Declaring a variable more than once in a scope doesn't create more than one variable. The var keyword inside the if statement is ignored as the variable already is declared once in the scope, so it's just an assignment.
Note also that the declaration of variables is hoisted to the top of the scope, so even if a declaration is inside a code block that is not executed, the variable is still created:
var foo = 1; // a global variable
(function() {
console.log(foo) //outputs "undefined"
foo = 2; // sets the local variable
if(false) {
var foo = 3; // creates the local variable, but the assignment never happens
}
console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1

Categories