JS var : help me to understand this [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
I understand that I should always use 'var' to define a local variable in a function.
When I define a global function, what's the difference between using 'var' ?
Some of code examples I see over the internet use
var globalVar = something;
globalVar = something;
What's the difference?

Well, the difference is that technically, a simple assignment as globalVar = 'something'; doesn't declare a variable, that assignment will just create a property on the global object, and the fact that the global object is the last object in the scope chain, makes it resolvable.
Another difference is the way the binding is made, the variables are bound as "non-deletable" properties of its environment record, for example:
var global1 = 'foo';
delete this.global1; // false
global2 = 'bar';
delete this.global2; // true
I would strongly encourage you to always use the var statement, your code for example will break under ECMAScript 5 Strict Mode, assignments to undeclared identifiers are disallowed to avoid implicit globals.

Short: There is no difference in the global context**.
Long: The Variable object for the global context is the global context itself. That is why we can just access global variables and methods within a function-, or eval context. However, the var statement just makes sure you're defining a variable in the current context, so it makes no difference by omitting that in the global context. Exception: ES5 strict mode will probably throw an error when it sees a declaration without var.
**
the only difference is, that var will declare a variable without definition in the current (execution) context. This happens at js parse time, so the engine knows that there is a variable with that name available in the context. Omitting var will end up in a direct property access from the global object.

Related

Initialization vs assignment

The terms "initialization" and "assignment" seem to be used interchangeably. I did some searching and it seems that there might technically be a difference. My understanding is that, in the context of variables, a variable is initialized when the JavaScript engine makes it available for use, and assignment (whether done explicitly [as in let foo = 1;] or by the JavaScript engine, as in the following example) is one way to achieve this.
let foo;
console.log(foo); // undefined (initialization and assignment?)
Is my understanding correct? Also (if so), what actually occurs during initialization to make the variable available?
TLDR:
{ // declaration (hoisted)
// Temporal deadzone
let foo; // declaration and initialization to undefined
foo = 1; // assignment
}
A bit longer:
Declaration
Declaring a variable means that we reserve the identifier at the current scope. In javascript declarations are hoisted, that means that it gets declared when the scope the variable is in gets visible (the block it is in gets executed). However you cannot access that variable now as it is in
The temporal deadzone
This is a specific part of the code that is between the beginning of the scope and the initialization. Trying to access the variable here results in an error.
Initialization
The initialization takes place in the line were you declared the variable. It will assign a value to the variable and will make it available for access. This for example:
let foo;
will initialize foo to undefined,
let foo = 2;
will initialize foo to 2.
Assignment
...just means that you change the value of a variable. All assignments in javascript use =. The initialization is basically just the first assinment.
The explanation above does not apply to variables declared with var, so just don't use var to avoid confusion :)

Javascript hoisting and variable assignment (with no declaration)

Looking at MDN's introduction to JavaScript, Grammar and Types section - one reads:
Declaring variables
You can declare a variable in three ways:
With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables.
By simply assigning it a value. For example, x = 42. This always declares a global variable. It generates a strict JavaScript
warning. You shouldn't use this variant.
With the keyword let. For example, let y = 13. This syntax can be used to declare a block scope local variable. See Variable scope
below.
The following code snippet would seem to fit the "by simply assigning it a value" scenario, meaning the variable should be treated as global.
(function(){
console.log(myVar);
//the following will throw a ReferenceException error
//myVar = 10;
//the following will not, and I can understand it following the defintion of the behavior of using `var` keyword
//var myVar = 10;
})();
But running the code will generate a ReferenceException when myVar is commented, and undefined when not. I would expect it to generate undefined in both cases, since if myVar is a global variable (per definition), than javascript's variable hoisting would make it known before reaching console.log(myVar);
What is the explanation behind such behavior ? (the behavior I described is what I get when trying it in my firefox's console, but running it in jsfiddle will not throw an error).
Are self-executing functions an exception to hoisting ?
the "by simply assigning it a value" scenario
You are reading the value, not assigning it
if myVar is a global variable (per definition),
It isn't.
myVar is:
a variable scoped to the function if the function contains var myVar (or function myVar () { ... }, or it is listed as a parameter in the function definition).
a variable scoped to the block if the block contains let myVar
a global variable if a value has been assigned to it previously and neither of the above conditions are true.
Since you haven't assigned a value, it isn't a global. Since none of the above conditions are true, it isn't any kind of variable, so you get a reference error.
Regarding your comment:
I left my var when I meant var in the scenario I am trying to depict. Updated question.
… and the edit to which you refer:
Commented out code is not evaluated. Having a comment that uses the keyword var doesn't do anything.
Regarding your further edits.
You get a reference error if you try to read a variable before it has been declared.
var statements (and function declarations) are hoisted so a variable declared with those methods can be read anywhere in the function.
Assignments are not hoisted. A global variable created implicitly by assignment (which is generally not considered to be best practise and is banned in strict mode) can't be read before the value is assigned.
Since my comment seemed to help explain it to you, I will turn it into an answer:
Implicit global variable creation (when you don't actually declare it, but just assign to it) is NOT hoisted. The variable creation happens inline at the moment the assignment occurs.
Thus, when you try to read the variable, it does not exist yet and that is an error.
var or let declarations are hoisted to the top of their appropriate scope.
All of this should hopefully help explain why you should just run in strict mode where implicit global creation is illegal and not allowed and triggers an immediate error. It's basically evil. A simple typo misspelling a variable may not trigger an error when you really want it to.

Is it necessary to use the keyword 'var' to declare a variable 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 9 years ago.
I have found that it does not seem necessary to use the keyword 'var' when declaring a variable in Javascript. In fact, I have found no bad side effects from omitting it altogether.
Perhaps this is bad form, but can someone explain why it would be necessary?
Using the keyword var ensures that your variable is properly scoped. If you do not use the keyword, then JavaScript will automatically create the variable as a global scope, which can cause issues later in the execution of your page.
name = 'Bic'; // implicitly global
function myFunc() {
var name = 'John'; // this variable is scoped here
console.log(name); // John
getName(); // Bic
}
function getName() {
console.log(name); //Bic
}
myFunc();
getName();
In the code above, I declared a global name, and a scoped name. Note, the global name lingers on after myFunc() has finished executing. name is a property of most HTML elements. In this particular answer, my declaration of name without the var keyword can have detrimental affects to a page's execution. The value of name gets thrown out of scope, and this can affect targeting elements, and other things. If you take a look at this Fiddle, and click Run again after it loads, you will notice it automatically opens a new tab. This is because the original value of name has been clobbered, and the page does not know where to truly open.
As a general rule, it is good to always declare variables with the var keyword, as this makes it easier to follow the scope of that variable, as avoids unforeseen issues they can cause.
As was noted by Pointy, the 'use strict' pragma (introduced in ECMAScript 5) actually prohibits the declaration of variables without the var keyword.
if you don't declare it, perhaps you are accessing a global var. be careful with that because you can get undesired side effects.
By definition, declaring a variable requires the var keyword. There are other ways of creating variables though, such as including them in a formal parameter list:
function foo(a, b, c) {...}
here a, b, and c are created more or less as if they were declared with var. The ill effects of creating variables without var are noted in other answers.

What does "var" do in JavaScript? Why is it sometimes part of an assignment? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
var foo = 1;
foo = 1;
What is the difference between above two lines ?
Basically, var declares a variable and you can also assign to it at the same time.
Without var, it's assigning to the variable. Assigning will either assign to an existing variable or create a global variable of that name then assign to it.
Outside of functions, that means there's no real difference (in principal) if the variable does not already exist. Both create the global variable foo in that case.
Within a function, there's a huge difference. The first creates a variable local to the function regardless of whether or not it exists elsewhere.
The second will create a global variable if it doesn't exist, or simply change the value if it does exist.
In order to keep code as modular as possible, you should always use var unless you are specifically wanting to change existing global variables. That means declaring all globals outside of functions with var and declaring all locals with var.
foo = 1 will put foo in the last scope where foo was defined, or the global scope. var foo = 1 will put the variable in the current scope (i.e. the current function).
In first case foo will be available in the same scope where it is defined, i.e. it will be local variable.
In second case foo is a global variable, located in global scope.

scope in javascript

i have encountered the following curious piece of code:
function foo(){
works = {hello:"world"};
function bar(){
alert('does not work');
}
var notwork = {hello:"world"};
}
foo();
alert(works.hello);
alert(notwork.hello);
Can someone please explain to me why works work, and notwork doesn't work? Or point me out to a good resource that explains this in detail.
Thank you very much!
var notwork creates a local variable valid only for the runtime of the function.
works creates a global variable that is valid throughout the javascript runtime.
var declares a variable as "local" to the function it's defined in.
Without var, you works variable is global : it can be seen/accessed/used from anywhere.
With var, your notwork variable is local to the foo function : it cannot be seen/used from outside of that function.
For more informations, you can take a look at the documentation of the var statement on MDC, which states (quoting) :
The scope of a variable is the current
function or, for variables declared
outside a function, the current
application.
Using var outside a function is
optional; assigning a value to an
undeclared variable implicitly
declares it as a global variable.
However, it is recommended to always
use var, and it is necessary within
functions in the following situations:
If a variable in a scope containing the function (including the global
scope) has the same name.
If recursive or multiple functions use variables with the same name and
intend those variables to be local.
Failure to declare the variable in
these cases will very likely lead to
unexpected results.
You've missed out the var keyword so works is being defined on the global object.
You want
var works = ...

Categories