Bogdan
Bogdan

Reputation: 692

Does a string variable declared in a function get recreated each time the function is called?

If you have a function like:

function test() {
  var hello = "hello world"
}

test();
test();
test();

Will hello variable be recreated three times? Or will the value 'hello world' be stored and the variable will be created but set to point to the same location in memory every time? I'm also asking in the context of modern browsers/JS engines.

Upvotes: 0

Views: 67

Answers (2)

Bergi
Bergi

Reputation: 665455

Will hello variable be recreated three times?

Yes, definitely. (Unless it's completely optimised away by DCE)

Or will the value 'hello world' be stored in the same location in memory every time?

Now that's a different thing - the string value. Since strings are immutable, and the difference between the same value in different memory locations is not observable, we cannot know without looking at the implementation. For that question, see Do common JavaScript implementations use string interning? (hint: yes, they are memory-efficient).

Upvotes: 2

Sebastien Daniel
Sebastien Daniel

Reputation: 4778

yes.

However you could create a IIFE (immediately invoked function expression), that returns a function. That way it wouldn't be re-instantiated every time you call the returned function.

var hi = (function() {
  var hello = "Hello world";

  return function() {
    return hello;
  }
}());

hi(); // "Hello world";

However this could vary depending on which interpreters/JIT compilers you're running on. Some of their optimizations could optimize your code to not re-instantiate every time...

Upvotes: 3

Related Questions