What is wrong whit this code? Can't get this to work


#1

function testeconta(){
var conta1 = x;
var conta2 = z;
x = 30;
z = 70;
var totalizar = conta1 * conta2;
return totalizar;
document.getElementById(“testemat2”).innerHTML = testeconta();
}


#2

you placed the function call (which executes the function) inside the function, why?


#4

Oh i saw that and already changed, but still not working. I’m trying to get it in a H1 inside html.


#5

can we see the code in action? Somewhere on jsbin for example? There might be other issues, difficult to say


#6

This is because you are trying to use a variable that hasn’t been defined declared yet. In Javascript this is not allowed. First define declared the variable and than you can use it.

Try flipping the varriables:

var x = 30;
var z = 70;
var conta1 = x;
var conta2 = z;

#7

Variables in JS only need to be declared, not necessarily defined.

var a, b;

console.log(a, b)    =>  undefined undefined

Notice we did not throw an Uncaught ReferenceError?

This is especially useful for when we will make multiple assignments in a loop. We should never use var in a loop, and JS will not allow us to use let in a loop, so declaring undefined variables is a viable option in this instance.


#8

So setting conta1 to x is ok if x is set after conta1 ?

This fixed OP’s problem of x is undefined.


#9

Tnx, it worked! But i thought that i could switch the variable value later, like assigning x to be 30 would change the value of the conta1 as well ( x would be 30).


#10

Tnx, Biirra already solved this. It’s seems to be a problem with variable value.


#11

In the case above, x not existing (reference error) is different from x being undefined. That what my only point.

var x, y;
do {
    x = Math.floor(Math.random * 11);
    y = y + x.toString();
} while (x < 10);
console.log(y)

conta1 would not be changed because x is changed. It would stay the same. Only x would point to a new value in memory.

In the case of arrays and objects, if two variables point to the same array, and the array is changed, both variables will still be pointing to the same object. We will see the change in both.


#12

understood,

editted the post.