Lifetime of local variables in Javascript

Although I am adept in C and C++, Javascript is a new realm for me. Currently, I am delving into three.js but finding it challenging to grasp this particular concept:

var camera, scene, renderer, control;

init();

function init() {
    scene = new THREE.Scene();

    var light = new THREE.DirectionalLight( 0xffffff, 2 );
    light.position.set( 1, 1, 1 );
    scene.add( light );
}

This excerpt represents the core of my inquiry. Despite extensive reading across various sources, I have not encountered an explanation that clarifies my doubts.

My query pertains to the local variable "light" created within the function using the "new" keyword to instantiate an object. As per my understanding, objects in JavaScript are passed by reference. Therefore, when added to the scene with "scene.add(light);", why does it continue to function? Shouldn't the object get destroyed once the reference is passed, causing issues when invoking the render function outside of "init"?

Hence, my question revolves around whether the "new" keyword somehow enables the local variable to persist beyond the function's scope, ensuring the object remains active as long as there exist references pointing to it?

Could you confirm if my interpretation aligns with the actual behavior?

Answer №1

After declaring the variable light within a function, it ceases to exist once the function exits. However, when the object that the variable points to is "added to the scene" using scene.add(light), a second reference to the object is likely created. As a result, after the function exits, the initial reference light becomes out of scope and is removed, leaving only the reference from scene.add(light).

In JavaScript, garbage collection will only clean up an object when there are no references left pointing to it.

It is worth noting that using new does not have any special functionality other than creating a new instance of an object.

Answer №2

If I define a variable "light" inside a function and initialize it with the "new" keyword, will it create an object?

Absolutely.

Since I declared it within the function "init", it is a local variable. Objects in JavaScript are passed by reference, as I've come to understand.

If by "passing by reference" you mean like in C and C++, then no. But if you mean like in Java, then yes. Some refer to it as passing by "copy-of-reference", similar to passing a pointer to the object.

So when I add it to the scene using "scene.add(light);", why does it still work? If I passed the reference, shouldn't the object be destroyed and cause issues when calling the render function outside of "init"?

The object isn't created on the stack, only the value pointing to it resides there. The object itself is created on the heap. By passing the object to another method and assuming that method stores the reference somewhere, the object will persist even after exiting this function. Only the variable (holding the "pointer") will go out of scope.

I'm curious, does the "new" keyword somehow make the local variable persist beyond the function's body, keeping the object alive as long as something holds a reference to it?

The object will be automatically garbage-collected (similar to 'free' in C) once there are no more references to it (as in Java).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problems with the functionality of Javascript and ajax

I've created this JavaScript/AJAX code, but unfortunately, it's not functioning as expected and I am unable to determine the reason behind it. $(document).ready( function(){ $('#btn4').click( function(){ var plano = $(&a ...

Error: Attempting to access property 'navigate' of an undefined variable is not allowed

Hey there, evening everyone! I'm facing a bit of an issue when trying to click on the "login or register button" as I'm getting this error message: "TypeError: Cannot read property 'navigate' of undefined" I've made some small ad ...

Verify if a value is present in an array or falls within specified range of values

My goal is to input a value and determine if it exists in an array or falls within a specified range of values within the array. I then want to retrieve the index of the lower range value. For instance, consider the following array: dataArr = [10, 20, 30 ...

Setting up a personalized configuration entry in environment.js

I am currently working with EmberJS version 2.4.2 and I have a specific requirement to handle custom configuration entries using an environment.js file. var ENV = { APP: { myKey: "defaultValue" } }; While everything works perfectly in development ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...

I am looking for a way to hide email addresses using Regex in JavaScript

I'm looking for a way to hide an email address [email protected]=> [email protected] using JavaScript I attempted to use the /(?<=.{2}).(?=[^@]*?@)/ regex, but it is not functioning properly in Internet Explorer and Mozilla. I need a ...

The presence of "label.error" appears to persist across all bootstrap tabs

I am facing an issue where the $('label.error') element appears on every bootstrap tab, even though it should only display on one specific tab. The problem arises when a field fails validation on a bootstrap tab and as a result, a label with clas ...

Barba.js (Pjax.js) and the power of replacing the <head> tag

I have been using barba.js to smoothly transition between pages without having to reload the entire site. If you want to see an example, take a look here. Here is a snippet of code from the example: document.addEventListener("DOMContentLoaded", func ...

The functionality of Nuxt's asyncData is restricted when attempting to access data from authorized express routes

Setting up an online store. I began with the products, which can be pulled without authorization but require it for editing. The process is smooth so far, probably because it's happening on the client side where authentication information is included ...

Implement scroll bar functionality on canvas following the initial loading phase

I am currently working with canvas and I need to implement a scroll bar only when it is necessary. Initially, when the page loads, there isn't enough content to require a scroll bar. My project involves creating a binary search tree visualizer where u ...

Error: Express.js failing to send the correct file in response

For some reason, express.js seems to be acting strangely when I try to send an HTML file in a GET request. const express = require("express"); require('dotenv').config() const app = express(); const PORT = process.env.PORT || 5000; ap ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

What are the benefits of storing dist in both a GitHub repository and on npm?

I'm curious about why some repositories include a dist folder. Shouldn't repositories just store source code and not any builds or compiled files? Let's take a look at an example with ES6 code. package.json { "files": [ "dist", ...

jQuery Date-Based Price Countdown Feature

Unfortunately, I am not well-versed in jQuery/JavaScript and I am facing a challenging issue. In essence, there is an upcoming event where the prices of certain fixed items will decrease every minute between two specified dates. For example: 2012 07 25 ...

Tips for incorporating tabs using jQuery

Check out this code snippet: <script> $(function() { $("#tabs").tabs({ event: "mouseover" }); $("#tabs").tabs("add","#tab-4","Friends Discussions"); $("#tabs").tabs("add","#tab-5","Announcements"); $("#tab ...

Tips for sending event and additional arguments to a click handler

Hi there, I recently created a canvas using easelJS. Within my canvas, I have points that have a click handler defined for them with this syntax: p.on("click", handleMouseClickEvent); However, I am facing an issue when trying to pass arguments to the han ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

Enhance your website visuals with jQuery Sparklines and CSS Transforms

I've incorporated jQuery Sparklines into an html page that I've resized using the transform: scale property. However, this adjustment has caused the jQuery Sparklines tooltip to appear in the incorrect location. For instance, consider the code sn ...

Exploring JSON Data with NativeScript

As a newcomer to NativeScript and JSON, I am currently facing challenges in accessing data from my JSON file. My main goal right now is to simply log some of the data for debugging purposes. Below is the code snippet from my view-model: var config = requ ...

SQL query encountering issue after introducing apostrophe symbol ''`

SELECT CONCAT ( schoolname ,CASE WHEN schoolcity IS NULL OR schoolcity = '' THEN '' ELSE (', ' + REPLACE(schoolcity, 'ã', 'a')) ...