This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
I am trying to add a value to a variable using the += function. This is the code I am using:
function getAnswer() {
var num1 = Number(document.getElementById('numone').value);
var num2 = Number(document.getElementById('numtwo').value);
var oper = document.getElementById('oper').value;
var numberOfEquation = 0;
numberOfEquation += 1;
if (oper == '+') {
var p = document.createElement('p');
var txt = document.createTextNode(num1+num2 + ' - Equation ' + numberOfEquation);
p.appendChild(txt);
document.body.appendChild(p);
} else if (oper == '-') {
var p2 = document.createElement('p');
var txt2 = document.createTextNode(num1-num2 + ' - Equation ' + numberOfEquation);
p2.appendChild(txt2);
document.body.appendChild(p2);
}
console.log('You did an equation!');
}
I don't know what went wrong.
It appears to be a misunderstanding of how local variables work.
Local variable:
function x() {
var y = 0;
++y;
return y;
}
x(); // => 1
x(); // => 1
x(); // => 1
This returns 1 each time since var y explicitly declares a local variable. It will only exist during the execution of that function. As soon as the function terminates that variable ceases to exist. When the function starts up again it makes a brand new one.
Here's a different approach with a persistent variable:
var y = 0;
function x() {
++y;
return y;
}
x(); // => 1
x(); // => 2
x(); // => 3
This is because y exists outside the scope of the function. It lives as long as your program does.
I'm new to javascript and I'm not sure if there is anything called re-initialization in javascript, so please excuse if there is no such concept.
What happens if a javascript variable is re-initialized?
Ex:
function foo()
{
var x = 10;
.... //do something
.... //do something
.... //do something
var x = 20;
console.log("x: " + x);
}
What would be the value of x here?
x will be 20. var is "hoisted" (more below), which means that the variable gets declared as of the beginning of the function, before any step-by-step code is run. Any initializer on a var statement is actually just an assignment statement.
So your code:
function foo() {
var x = 10;
//do something
var x = 20;
console.log("x: " + x);
}
is treated as though it were like this:
function foo() {
var x;
x = 10;
//do something
x = 20;
console.log("x: " + x);
}
When you call a function, the JavaScript engine does several things before it starts executing the step-by-step code in the question. one of the things it does is look through the code and process any var statements. (Although it's called the var statement, var is more of a declaration.)
It's quite fun, your code could also be written this way:
function foo() {
x = 10;
//do something
x = 20;
console.log("x: " + x);
return;
var x;
}
It would still be valid, and it would do exactly the same thing.
More (on my blog): Poor, misunderstood var
ES6 will introduce let, which behaves differently (amongst other things, it is scoped to the block it's in, whereas var is scoped to the function as a whole even if declared within a block); details on MDN.
The var keyword essentially just determines the scope of the variable and is handled before any of the code is actually executed (look up "hoisting"). Using var twice for the variable is redundant, but doesn't really do anything in particular. In the end you're just assigning 10 to x and later you assign 20 to x; nothing more, nothing less.
You can always run simple test to check that. var means it's this variable is in current scope. So in your example x will be equal to 20
var x = 10;
var x = 20;
var y = 10;
function Test() {
var x = 30;
y = 20;
alert('X in function: ' + x);
alert('Y is global, so it\'s ' + y);
}
Test();
alert('X outside of function: ' + x + ', also Y = ' + y);
I am trying to call this function in Javascript but it wont work.
eval("function f() { return x + 1;}")
I called it by typing function f(12);
If you MUST you eval.. you should give x to the function as a parameter. So it should be :
eval("function f(x) { return x + 1;}")
But you could just write it as:
function f(x) {
return x + 1;
}
eval() in javascript
The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
var x = 10;
var y = 20;
var a = eval("x*y") ;
var b = eval("2+2") ;
var c = eval("x+17")";
var res = a + b + c;
Output:
200
4
27
Create your function like this:
function f(x) {
return x + 1;
}
When the 'hypotenuse' function is called the value of 'x' changes from 1. Fix it so that 'x' is still 1 in the gobal scope.
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
All you need to do to make this happen is redeclare the x variable using var within the function. This is will declare the x variable within the scope of the function, leaving the original, globally scoped x variable untouched:
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b,
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
Or, using the code style which you originally adopted (splitting out var declarations):
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
For more detailed info on what is happening here, read up on javascript scope
Try this:
var x = 1;
var y = 1;
function hypotenuse(a, b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
//console.log(hypotenuse(x, y));
//console.log('x = ' + x);
Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;