why without var? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
seems stupid question but just curious.
num = "hello";
alert(num);
why is this possible I didnt initialize the num variable here.
num = "hello";
instead of
var num = "hello";

var means "Scope this variable to this function" not "Make it possible to use this variable".
If you leave var off then it will use the variable in the next scope up from the function. If that scope doesn't have the var yourVar then it will keep going up the scope chain until it becomes a global and dangles off the window object (assuming a browser or another JS environment in which the default object is window).
(This changes in strict mode, which you are presumably not using.)

Without the var keyword the variable is created at the global scope (in browsers under window).
If you add the var you just assign the variable to the current scope, which in most cases will be a function scope.
In general it will be better to use a function scope in order to not pollute the global scope and prevent conflicts between multiple variables of the same name!

Related

Terminology question about global variables and global scope [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Difference between variable declaration syntaxes in Javascript (including global variables)?
(5 answers)
Closed 2 years ago.
Is the following true:
For something to be in the global scope means it can be accessed anywhere in all files.
All global variables have global scope.
Therefore, the global object (and its properties) is a type of global variable.
P.s. This is a genuine question I find it useful getting terminology down and maybe it might help me be able to read the docs later.
A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.
To declare JavaScript global variables inside function, you need to use window object.
window.value=90;
Now it can be declared inside any function and can be accessed from any function. For example:
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
When you declare a variable outside the function, it is added in the window object internally. You can access it through window object also. For example:
var value=50;
function a(){
alert(window.value);//accessing global variable
}
You can read more here https://www.javatpoint.com/javascript-global-variable
All global variables can be used in all scripts. Just try it yourself. This is how jQuery or any library works.
Read more about global variables on Wikipedia.

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.

Javascript object creation practices [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
This is what I think is best for making an object in js
function obj(){
var x = "hi";
this.getX(){return x;}
}
var y = new obj()
console.log(y.x); //this returns undefined
But from what I have seen, using this.variable is used more often in object creation.
I am thinking in java where things should be "private" in a class (note I have read about closures), does that apply in js?
What is considered the best way of object creation?
It sounds like you're trying to apply Java concepts to JavaScript, but things works completely differently in JS. You should check out the MDN article on JavaScript closures.
var variables exist in the closure. They are accessible from any function declared in the same scope.
var me = 'hello';
function someFunction() {
console.log(me);
}
someFunction(); //prints 'hello' to console
this variables will be directly accessible, even outside the scope, in the resulting object.
function someFunction() {
this.me = 'hello';
}
var instance = new someFunction();
console.log(instance.me); //prints 'hello' to console

what the method this.method.bind(this) does? [duplicate]

This question already has answers here:
What is the use of the JavaScript 'bind' method?
(23 answers)
Closed 7 years ago.
Met the code first time:
var Controller = function($scope){
this._scope = $scope;
}
Controller.$inject = ['$scope'];
Controller.prototype.augmentScope = function() {
this._scope.a = {
methodA: this.methodA.bind(this)
}
}
I really don't understand what is the point. Any explanations?
It assumes that in the closure scope (If none it will be in the global scope such as window) there is a method called methodA. Then again, because the this is really the enclosing scope mentioned), it will remind it and assign it ti be used be through object a as well.
So you can execute it by:methodA() or a.methodA()
Edit to explain closure:
Although Javascript is very similar to Java/C++ in syntax it's quite different than both of them in the sense that when a function is instantiated as an object, it remembers the scope it was instantiated in. I would highly recommend anyone doing more than the casual JS(if there is such a thing), to look into this article.
The this in JS will deffer depends if it was created inside an instantiated function - AKA: new MyClass(). Referring to a literal object such as:
var myObj={a:this.b}
will not create a new this and will by default refer to enclosing scope. If none was created it will be the global object such as window in a browser

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

Categories