0

I have a problem that I create a variable with value that not exist yet (other variable)

example:

var a=b;
var b=5;
console.log(a)
//I want result to be 5

I need it to be without wrapping with function or object (unless I can still call "a" as is and not "a()" )

if 'a' can point to 'b' by ref I will do:

var b="temp"
var a=b
b=5

so, is there any way that 'b' will point on same location as 'a' ?

larry ckey
  • 141
  • 2
  • 14
  • 2
    Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Kukic Vladimir Jul 06 '17 at 08:45
  • do you mean that there is no way of doing this? – larry ckey Jul 06 '17 at 08:51
  • All primitives values like, booleans, strings, numbers, when attributed to another variable, is created a new value by copy. Objects like, arrays, functions and any other type of object are passed by reference. – Rubens Pinheiro Jul 06 '17 at 08:54
  • correct, this is why I have a problem :) I thought maybe someone have an "out of box" idea – larry ckey Jul 06 '17 at 09:05
  • No, there's no (generic) solution. What is your [actual problem](https://meta.stackexchange.com/q/66377)? – Bergi Jul 06 '17 at 09:18
  • I think in every language, even the functional ones, that have lazy evaluation, you can't simply do that because you're attributing a variable that was even defined yet to "a". And JS will just assume that, "a" will receive undefined. Even if you use a object for "b", you're declaring it after, so before it, it simply doesn't exist in memory. As Ferdia said, you can deal with **future** values using Promises or Observables, but **first** you need declare the variable you're trying to associate to another :) – Rubens Pinheiro Jul 06 '17 at 09:26

2 Answers2

0

Maybe the Promises API could work for you? Docs here

A trivial example;

var bPromise = new Promise(function(resolve, reject) {
   resolve(5);
});

bPromise.then(function(result) {
   var a = result;
   console.log('a = ' + a);
});
Ferdia
  • 26
  • 3
0

Well, you can do using a JS feature:
As function declarations are hoisted up by the JS interpreter, we can play around creating a "producer" for a "lazy evaluation" (very common in functional languages, but not included natively in JS).

const a = b;
b(5);
console.log(a());

//We just take advantage of the function hoisting and context to do this
function b(val) {
 return val? this.val = val : this.val;
}
Rubens Pinheiro
  • 490
  • 5
  • 11