This question already has answers here:
Is using 'var' to declare variables optional? [duplicate]
(14 answers)
Closed 8 years ago.
Given the snippet code from Javascript the good parts (page 24):
var name;
for (name in another_stooge) {
if (typeof another_stooge[name] !== 'function') {
document.writeln(name + ": " + another_stooge[name]);
}
}
Why there is definition of variable name before use in for in loop, since it will work without it?
There are two different things to pay attention to here.
var
Without var, the variable would be a global unless it was already declared in a wider scope. (In strict mode, it would be an error rather than a global).
Before the loop
You could have for (var name… but that makes it harder to spot the var statement.
Douglas Crockford (the author of The Good Parts, so highly relevant here) advocates declaring all local variables at the top of the function so you have one place to look to find your scope.
var name = 1;
name = 1;
These two are different things. For the first line, name is a variable deaclared under the current function scope, while the second is equivalent to window.name = 1 (if name hasn't been decalred in current scope.) You should never declare temporary variables in the global scope unless you have a really good reason behind it.
It is recommended, that all variables of a function are defined in same place, so if you had multiple variables, that one in the loop would be defined among them:
var a, b, name; //etc
for (name in another_stooge) {
if (typeof another_stooge[name] !== 'function') {
document.writeln(name + ": " + another_stooge[name]);
}
}
This goes with the section of: "best practices".
Yes but in that case name will be a global variable and will behave differently. So if you are after the good parts use var for every variable you use (global variables are not good).
But you can shorten the code like this...
for (var name in another_stooge) {
That will make name a scope variable...
EDIT: Assuming you are asking why not
for (var name in another_stooge)
A matter of style.
Unlike many other languages, JavaScript is function scoped, not blocked scoped.
As a result, many programmers will manually "lift" their var declarations to the top of the function to make it readily apparent what is going on.
Or -- considering the use of document.write in that code, it could be that the original coder didn't realize there was another way.
Related
It may seem very trivial issue but very confusing and recurring for me. In some manuals for javascript or tutorials these terms are used alternately.
In others I found the explanation that we declare variables when we create them with var const let and we define variables, when we append some value/object to the declared variable as below:
var name; //declaring
name = 'Adam' //defining
var age = 'dead' //declaring + defining
Are there any approved and correct rules of using these two terms?
I'd say that "variable definition" is not a standard JavaScript term.
Functions (of all kinds) and object properties can get defined, but variables always get declared. This terminology might hint at the declarative nature of variables - a declaration always applies to the complete current scope, it's not an action that gets executed and does something.
var name is a declaration. var age = 'dead' is a declaration with an initialiser. name = 'Adam' is just an assignment. I'd guess that "defining" a variable refers to it no longer being undefined, so both an assignment statement or the initialiser of the declaration might do that. I'd rather speak of the initialisation of the variable, though.
var x is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation.
var x = 1 is both declaration and definition but are separated with x being declared in the beginning while its definition comes at the line specified (variable assignments happen inline).
I see that you already understand the concept of hoisting but for those that don't, Javascript takes every variable and function declaration and brings it to the top (of its corresponding scope) then trickles down assigning them in order.
You seem to know most of this already though. Here's a great resource if you want some advanced, in-depth exploration. Yet I have a feeling you've been there before.
Javascript Garden
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 7 years ago.
Is "var" optional?
myObj = 1;
same as ?
var myObj = 1;
I found they both work from my test, I assume var is optional. Is that right?
They mean different things.
If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete (most likely by someone else's code who also failed to use var). If you use var in the global scope, the variable is truly global and cannot be deleted.
This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.
This is one of the tricky parts of Javascript, but also one of its core features. A variable declared with var "begins its life" right where you declare it. If you leave out the var, it's like you're talking about a variable that you have used before.
var foo = 'first time use';
foo = 'second time use';
With regards to scope, it is not true that variables automatically become global. Rather, Javascript will traverse up the scope chain to see if you have used the variable before. If it finds an instance of a variable of the same name used before, it'll use that and whatever scope it was declared in. If it doesn't encounter the variable anywhere it'll eventually hit the global object (window in a browser) and will attach the variable to it.
var foo = "I'm global";
var bar = "So am I";
function () {
var foo = "I'm local, the previous 'foo' didn't notice a thing";
var baz = "I'm local, too";
function () {
var foo = "I'm even more local, all three 'foos' have different values";
baz = "I just changed 'baz' one scope higher, but it's still not global";
bar = "I just changed the global 'bar' variable";
xyz = "I just created a new global variable";
}
}
This behavior is really powerful when used with nested functions and callbacks. Learning about what functions are and how scope works is the most important thing in Javascript.
Nope, they are not equivalent.
With myObj = 1; you are using a global variable.
The latter declaration create a variable local to the scope you are using.
Try the following code to understand the differences:
external = 5;
function firsttry() {
var external = 6;
alert("first Try: " + external);
}
function secondtry() {
external = 7;
alert("second Try: " + external);
}
alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7
The second function alters the value of the global variable "external", but the first function doesn't.
There's a bit more to it than just local vs global. Global variables created with var are different than those created without. Consider this:
var foo = 1; // declared properly
bar = 2; // implied global
window.baz = 3; // global via window object
Based on the answers so far, these global variables, foo, bar, and baz are all equivalent. This is not the case. Global variables made with var are (correctly) assigned the internal [[DontDelete]] property, such that they cannot be deleted.
delete foo; // false
delete bar; // true
delete baz; // true
foo; // 1
bar; // ReferenceError
baz; // ReferenceError
This is why you should always use var, even for global variables.
There's so much confusion around this subject, and none of the existing answers cover everything clearly and directly. Here are some examples with comments inline.
//this is a declaration
var foo;
//this is an assignment
bar = 3;
//this is a declaration and an assignment
var dual = 5;
A declaration sets a DontDelete flag. An assignment does not.
A declaration ties that variable to the current scope.
A variable assigned but not declared will look for a scope to attach itself to. That means it will traverse up the food-chain of scope until a variable with the same name is found. If none is found, it will be attached to the top-level scope (which is commonly referred to as global).
function example(){
//is a member of the scope defined by the function example
var foo;
//this function is also part of the scope of the function example
var bar = function(){
foo = 12; // traverses scope and assigns example.foo to 12
}
}
function something_different(){
foo = 15; // traverses scope and assigns global.foo to 15
}
For a very clear description of what is happening, this analysis of the delete function covers variable instantiation and assignment extensively.
var is optional. var puts a variable in local scope. If a variable is defined without var, it is in global scope and not deletable.
edit
I thought that the non-deletable part was true at some point in time with a certain environment. I must have dreamed it.
Check out this Fiddle: http://jsfiddle.net/GWr6Z/2/
function doMe(){
a = "123"; // will be global
var b = "321"; // local to doMe
alert("a:"+a+" -- b:"+b);
b = "something else"; // still local (not global)
alert("a:"+a+" -- b:"+b);
};
doMe()
alert("a:"+a+" -- b:"+b); // `b` will not be defined, check console.log
They are not the same.
Undeclared variable (without var) are treated as properties of the global object. (Usually the window object, unless you're in a with block)
Variables declared with var are normal local variables, and are not visible outside the function they're declared in. (Note that Javascript does not have block scope)
Update: ECMAScript 2015
let was introduced in ECMAScript 2015 to have block scope.
The var keyword in Javascript is there for a purpose.
If you declare a variable without the var keyword, like this:
myVar = 100;
It becomes a global variable that can be accessed from any part of your script. If you did not do it intentionally or are not aware of it, it can cause you pain if you re-use the variable name at another place in your javascript.
If you declare the variable with the var keyword, like this:
var myVar = 100;
It is local to the scope ({] - braces, function, file, depending on where you placed it).
This a safer way to treat variables. So unless you are doing it on purpose try to declare variable with the var keyword and not without.
Consider this question asked at StackOverflow today:
Simple Javascript question
A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
What's the problem with the code?
The code only works the first time the user clicks the button.
What's the solution?
Add the var keyword before the variable name.
Var doesn't let you, the programmer, declare a variable because Javascript doesn't have variables. Javascript has objects. Var declares a name to an undefined object, explicitly. Assignment assigns a name as a handle to an object that has been given a value.
Using var tells the Javacript interpreter two things:
not to use delegation reverse traversal look up value for the name, instead use this one
not to delete the name
Omission of var tells the Javacript interpreter to use the first-found previous instance of an object with the same name.
Var as a keyword arose from a poor decision by the language designer much in the same way that Javascript as a name arose from a poor decision.
ps. Study the code examples above.
Everything about scope aside, they can be used differently.
console.out(var myObj=1);
//SyntaxError: Unexpected token var
console.out(myObj=1);
//1
Something something statement vs expression
No, it is not "required", but it might as well be as it can cause major issues down the line if you don't. Not defining a variable with var put that variable inside the scope of the part of the code it's in. If you don't then it isn't contained in that scope and can overwrite previously defined variables with the same name that are outside the scope of the function you are in.
I just found the answer from a forum referred by one of my colleague. If you declare a variable outside a function, it's always global. No matter if you use var keyword or not. But, if you declare the variable inside a function, it has a big difference. Inside a function, if you declare the variable using var keyword, it will be local, but if you declare the variable without var keyword, it will be global. It can overwrite your previously declared variables. - See more at: http://forum.webdeveloperszone.com/question/what-is-the-difference-between-using-var-keyword-or-not-using-var-during-variable-declaration/#sthash.xNnLrwc3.dpuf
Let me ask one question. It's about closures in JavaScript, but not about how they work.
David Flanagan in his "JavaScript The Definitive Guide 6th Edition" wrote:
...Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them....
Is this correct? Can I call every function (function object + it's scope) a "closure"?
And stacks' tag "closures" says:
A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.
In JavaScript every function refers to variables from the scope in which it was defined. So, It's still valid.
The question is: why do so many developers think otherwise? Is there something wrong with this theory? Can't it be used as general definition?
Technically, all functions are closures. But if the function doesn't reference any free variables, the environment of the closure is empty. The distinction between function and closure is only interesting if there are closed variables that need to be saved along with the function code. So it's common to refer to functions that don't access any free variables as functions, and those that do as closures, so that you know about this distinction.
It's a tricky term to pin down. A function that's simply declared is just a function. What makes a closure is calling the function. By calling a function, space is allocated for the parameters passed and for local variables declared.
If a function simply returns some value, and that value is just something simple (like, nothing at all, or just a number or a string), then the closure goes away and there's really nothing interesting about it. However, if some references to parameters or local variables (which, mostly, are the same) "escape" the function, then the closure — that space allocated for local variables, along with the chain of parent spaces — sticks around.
Here's a way that some references could "escape" from a function:
function escape(x, y) {
return {
x: x,
y: y,
sum: function() { return x + y; }
};
}
var foo = escape(10, 20);
alert(foo.sum()); // 30
That object returned from the function and saved in "foo" will maintain references to those two parameters. Here's a more interesting example:
function counter(start, increment) {
var current = start;
return function() {
var returnValue = current;
current += increment;
return returnValue;
};
}
var evenNumbers = counter(0, 2);
alert(evenNumbers()); // 0
alert(evenNumbers()); // 2
alert(evenNumbers()); // 4
In that one, the returned value is itself a function. That function involves code that makes reference to the parameter "increment" and a local variable, "current".
I would take some issue with conflating the concept of a closure and the concept of functions being first-class objects. Those two things really are separate, though they're synergistic.
As a caveat, I'm not a formalist by basic personality and I'm really awful with terminology so this should probably be showered with downvotes.
I would try to answer your question knowing you were asked about what closures are during the interview (read it from the comments above).
First, I think you should be more specific with "think otherwise". How exactly?
Probably we can say something about this noop function's closure:
function() {}
But it seems it has no sense since there are no variables would bound on it's scope.
I think even this example is also not very good to consider:
function closureDemo() {
var localVar = true;
}
closureDemo();
Since its variable would be freed as there is no possibility to access it after this function call, so there is no difference between JavaScript and let's say C language.
Once again, since you said you have asked about what closures are on the interview, I suppose it would be much better to show the example where you can access some local variables via an external function you get after closureDemo() call, first. Like
function closureDemo() {
var localVar = true;
window.externalFunc = function() {
localVar = !localVar; // this local variable is still alive
console.log(localVar); // despite function has been already run,
// that is it was closed over the scope
}
}
closureDemo();
externalFunc();
externalFunc();
Then to comment about other cases and then derive the most common definition as it more likely to get the interviewer to agree with you rather than to quote Flanagan and instantly try to find the page where you've read it as a better proof of your statement or something.
Probably your interviewer just thought you don't actually know about what closures are and just read the definition from the book. Anyhow I wish you good luck next time.
The definition is correct.
The closure keeps the scope where it was born
Consider this simple code:
getLabelPrinter = function( label) {
var labelPrinter = function( value) {
document.write(label+": "+value);
}
return labelPrinter; // this returns a function
}
priceLabelPrinter = getLabelPrinter('The price is');
quantityLabelPrinter = getLabelPrinter('The quantity is');
priceLabelPrinter(100);
quantityLabelPrinter(200);
//output:
//The price is: 100 The quantity is: 200
https://jsfiddle.net/twqgeyuq/
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 mean the browser does it very properly
I don't approve it, because putting var makes reading the code very easy.
if I do this will it work?
a=2;
console.log(a);
If you don't use the var keyword, then the variable will be global. If you are declaring the variable to be global, then it is not needed.
It is generally considered bad practice to declare variables to be global. When you do so, it is often referred to as "polluting the global namespace".
Yes, the drawback is that it becomes a "global" variable (a property of window), and if it's (unintentionally) used later, this may cause issues. If you have particularly large objects, then it may cause memory issues as well, unless you explicitly manage them.
As good code practice, it's typically best to constrain variables to the tightest scope possible for best readability.
They are different. If you do not use var, the variable always becomes global. Generally a bad idea.
when not using var, javascript will assume the variable is in the global namespace.
Thus:
a = 'abc';
function x() { a = 'def'; }
will overwrite "a", even though it is being run from inside a function. Sometimes that's what you want, but sometimes it isn't.
a = 'abc';
function x() { var a = 'def'; }
THAT will prevent "a" from being overwritten (the "a" inside of the function is a different variable).
In other words, always use var when declaring a new variable and you won't accidently overwrite existing variables.
This may be a silly question, but why are function arguments in JavaScript not preceded by the var keyword?
Why:
function fooAnything(anything) {
return 'foo' + anyThing;
}
And not:
function fooAnything(var anything) {
return 'foo' + anyThing;
}
I have a feeling the answer is because that's what the Spec says but still...
Most dynamicaly-typed programming languages don't have explicit vars in the argument list. The purpose of the var keyword is to differentiate between "I am setting an existing variable" and "I am creating a new variable" as in
var x = 17; //new variable
x = 18; //old variable
(Only few languages, like Python, go away with the var completely but there are some issues with, for example, closures and accidental typos so var is still widespread)
But in an argument list you cannot assign to existing variables so the previous ambiguity does not need to be resolved. Therefore, a var declaration in the arguments list would be nothing more then redundant boilerplate. (and redundant boilerplate is bad - see COBOL in exibit A)
You are probably getting your idea from C or Java but in their case type declarations double up as variable declarations and the cruft in the argument lists is for the types and not for the declarations.
We can even get away with a "typeless, varless" argument list in some typed languages too. In Haskell, for example, types can be inferred so you don't need to write them down on the argument list. Because of this the argument list consists of just the variable names and as in Javascript's case we don't need to put the extraneous "let" (Haskell's equivalent to "var") in there:
f a b = --arguments are still variables,
-- but we don't need "let" or type definitions
let n = a + b in --extra variables still need to be declared with "let"
n + 17
It would be a redundant use of the var keyword. Items that appear in the parentheses that follow a function name declaration are explicitly parameters for the function.
The var keyword declares the scope of the variable. A function argument also introduces the scope for that argument. Hence there's no need for it, since it serves the same function.
I think the question comes up because we're used to seeing function bla (int i) in many languages. The same, syntactically, as the int i; somewhere in the function body to declare a variable. The two ints are however not doing the same; the first defines the type, the second defines type and the scope. If you don't have to declare the type, the scope-declaration still needs to happen (which is why we have var in the second case) but there is no information needed in front of arguments.