Is declaring a function variable required (in Javascript)? - javascript

The teachers at my school are teaching us we have to specifically declare function variables like so:
function something(var1, var2)
{
var var1, var2;
console.log(var1);
console.log(var2);
}
something("Totally", "Cool");
However I can't seem to find any topics about this, so my question is, is this even required? Isn't it perfectly normal and OK to just leave the var var1, var2; out?
If so, is this stated somewhere in the W3C JavaScript documentation?
I mean it works either way, but if it works without... Cleaner code I'd say :P
Code I'm talking about: http://pastebin.com/y5B2aznc
Thanks!

in javascript, the scope of variables depends on how they are declared:
if you declare the variable when you define it, the scope of the variable is global
if you declare it using the var keyword, the scope of the variable is within the function
if you use the newer ES6 let keyword, the scope of the variable is within current block
so it is better to not use global variables and always limit the scope of your variables.
Here are a few references explaining the variable scopes in javascript:
What is the scope of variables in JavaScript?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
you should also definitely read Douglas Crockford's Javascript, the good parts:
http://shop.oreilly.com/product/9780596517748.do
http://javascript.crockford.com/‎
edit:
in your particular case, it is not useful:
function something(var1, var2)
{
var var1, var2;
console.log(var1);
console.log(var2);
}
as you give those variables as parameters of the function, they are already declared within the function scope, so declaring them again as var is redundant, and you can safely remove that line.
function something(var1, var2)
{
console.log(var1);
console.log(var2);
}

In your particular case, all the variables passed as arguments are local variables just like the variables you declare with var. So re-declaring them with var is redundant.
But a better practice is to leave the arguments with their original values, and do stuff with them storing the results in other local variables. E.g.:
function something(var1, var2)
{
var varAlt1 = var1.toUpperCase(), varAlt2 = var2.toLowerCase();
console.log(varAlt1);
console.log(varAlt2);
}

Omitting the keyword var in the declaration will result in the variables being global and not having their scope limited to the function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

If you don't use the var statement then the variables will be created in the global scope which is the window object. This is a bad practice since you're polluting the global scope and can affect other scripts/functions.
I suggest you read on the var statement on MDN. Also, here's a nice article on Javascript scope.
Edit: I didn't notice that the variables you're declaring are also the function parameters. In this case, the var statement will have no effect since re-declaring an already declared variable is a no-op (does nothing).
If you want to know more about the var statement and how scope is handled in Javascript, may I suggest reading this article?

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.

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.

When do I use var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Variable Scope
My understanding it that with in a function if I use var then I have a local variable. If I do not delcare var I now have a global variable.
But what about oustide of functions, what effect does var have?
First of all, it's generally bad practice to use code outside of functions. If nothing else, wrap your code in anonymous functions:
(function(){
// code
})();
As for what effect var has, it "declares" a variable:
var foo;
alert(foo); // undefined;
vs:
alert(foo); // error: foo is not defined
The reason for this is that the above code is functionally identical to:
alert(window.foo);
without declaring the variable with var, you get a lookup error, the same as trying to access the property of any object that doesn't exist.
Note that one of the oddities of var is that all declarations are pulled to the top of the script, so this will work as well:
alert(foo); // undefined
var foo;
You will also have access to your variable in the window object (though you will also have this by setting the variable without var, e.g. just foo=42):
var foo;
for(var key in window){
// one of these keys will be 'foo'
}
It is good practice to always use var. Strictly speaking when you are already in the global scope you don't need to but for the sake of code maintainability you should.
Say you have:
foo = 'bar';
But later you decide you want to move this code into a function:
function doSomething() {
foo = 'bar'; // oops forgot to add var
}
If you forget to add a var statement you've just created an implicit global. Now if you create a new object in the global scope that is named foo they will cause conflicts with one another.
function doSomething() {
foo = 'bar'; // Implicit global
}
foo = 'baz';
doSomething();
console.log(foo); // Returns 'bar', not 'baz'
This kind of error is particularly insidious when you forget to use var on something like i in a for loop. Learning to use JSLint can help to avoid these and other problematic logic or syntax errors.
Your question is answered in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
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.
I believe using var outside of a function works the same as not using var: you get a global. The exception to this would be if you are in a class or some other namespace structure, in which it will still define a variable in that locale
i believe you want to create a var whenever you are initializing a variable. As i've coded, when ever i need to initialize a variable, i start it with var. If you declare a variable without the word var, it's always global. If you declare a variable with var, inside a function, it's local to that function. If you create a variable with var outside functions, it will be a global variable.
If you are declaring a global variable and set a value it won't have any practical value, but as mentioned, it's best practice. If however you want to declare a variable without a value, you will need "var".

Distinguishing closure and local variables

A local function in the closure declares a variable with the same name which exists in the closure. So, how could we access closure's variable from the local function?
function closure()
{
var xVar;
function func1()
{
var xVar;
// how to distinguish local and closure scopes.
return xVar;
}
return function () { return func1(); };
}
Creating a private object and making private variables as properties of this object could help. But I am wondering if there is a better and neat solution. Can a scope chain help?
I have edited to make it a complete closure. Anyway, closures are not much concern here, it could be considered for inner functions however, there may be a solution with closures somehow.
Thanks
You can't access the scope chain explicitly in JS. Your problem is the age-old one of variable shadowing, but it's that much more maddening because in JS, the scope chain is actually there at runtime, it's just not available for you to access.
You can play some tricks with rejiggering current scope if you use the hated with operator, but that (as well as arguments's caller/callee stuff) really just give you access to objects and functions with their properties. There's no way to say "give me what xVar means in the n-1 runtime scope from right here".
Variables defined in an inner scope hide variable declarations in an outer scope. The "better and neat solution" is not to reuse variable names that way.
In your example the xVar variable is not a closure, because you redefined its scope to each function. To use that variable as a closure continue to declare it with the var command in the closure() function and then do not declare it with the var function in the func1() function. Instead just use the variable immediately in func1().
There is not an easy way to test if a function is a closure or a local variable. You would have to perform some sort of flow control test and then analyze assignments, where assignments occur, and where assignments do not occur. Then you must compare those results. You could write a tool, in JavaScript, to perform that analysis upon a given input and write you a report as output.

Categories

Resources