0
function makeCar() {
    var car = {
        color: "red",
        convertible: true
    };

    return car;
}

I know that local variable car holds a reference to the object, but when the function finish, will the object be released resulting in memory leak?

5
  • 2
    The object will only be released if there are no references to it. What would you expect var x = makeCar() to do? Commented Mar 2, 2018 at 15:19
  • 2
    JS is a garbage-collected language. Memory does not get allocated by assignment/initialisation, and is not released just because something goes out of scope. Commented Mar 2, 2018 at 15:20
  • memory is released by the garbage-collector only when there are no references to the object, yet there are some exceptions like WeakMap and WeakSet Commented Mar 2, 2018 at 15:24
  • Of course you can use this. The caller receives a "copy" of car. Commented Mar 2, 2018 at 15:28
  • 2
    Possible duplicate of Life of JavaScript objects & Memory Leaks Commented Mar 2, 2018 at 15:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.