Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "pre set" a variable?

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?

like image 232
Norse Avatar asked May 17 '12 19:05

Norse


2 Answers

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);
like image 112
Kevin B Avatar answered Nov 15 '22 10:11

Kevin B


is this what are you going for?

var add = "1 + three";
var three = 3;
document.getElementById('thediv').innerHTML = eval(add);
like image 38
rezna Avatar answered Nov 15 '22 10:11

rezna