I'm trying to declare a variable whose value is another variable that isn't set at that time.
var add = 1 + three;
var three = 3;
document.getElementById('thediv').innerHTML = add;
//results in "NaN"
http://jsfiddle.net/seSMx/1/
Is there a way to do this using Jquery/Javascript?
You could turn add into a function,
http://jsfiddle.net/seSMx/3/
function add() {
return 1 + (three || 0);
}
var three = 3;
document.getElementById('thediv').innerHTML = add();
Although, this would be very hard to follow in my opinion. I would take it a step farther and make three
an argument to add
function add(three) {
return 1 + (three || 0);
}
document.getElementById('thediv').innerHTML = add(3);
is this what are you going for?
var add = "1 + three";
var three = 3;
document.getElementById('thediv').innerHTML = eval(add);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With