JavaScript deals with booleans by returning them as values, instead of references

I've been working on converting one of my mid-sized JavaScript APIs from using a lot of global variables and functions to a more organized structure similar to the namespace encapsulation seen in libraries like jQuery. I've decided to implement this using anonymous functions.

Here is a snippet of the code:

(function(window, undefined) {
    var MyLib = (function() {
        var AbortProgram = true;
        function DisplayAbortProgram() { alert('AbortProgram inside=' + AbortProgram); }
        return { AbortProgram: AbortProgram, DisplayAbortProgram: DisplayAbortProgram }
    } ())
    window.MyLib = MyLib;
})(window);

MyLib.AbortProgram = false;
alert('AbortProgram outside=' + MyLib.AbortProgram);
MyLib.DisplayAbortProgram();

Upon running the code, the value of AbortProgram outside the function is false while inside it remains true. This has led me to question why this behavior is occurring. It seems likely that the issue lies in the return statement, which may be returning the value of DisplayAbortProgram rather than a reference to it. As JavaScript returns values for primitive types and not references, objects are passed by reference instead.

After research, it appears that there might not be a way to return a reference to the boolean variable directly. Therefore, I will need to implement a function called SetAbortProgram(value) to handle this situation.

Answer №1

AbortProgram is concealed by the closure, preventing it from being altered. This is typically the intended outcome of the pattern being utilized.

When you execute MyLib.AbortProgram = false;, you are not modifying the existing hidden variable but rather introducing a new AbortProgram variable.

If your goal is to allow modification of AbortProgram, consider simplifying your code as shown below:

var MyLib = {
        AbortProgram: true,
        DisplayAbortProgram: function DisplayAbortProgram() { alert('AbortProgram inside=' + this.AbortProgram); }
};

MyLib.AbortProgram = false;
MyLib.DisplayAbortProgram();

Alternatively, you can enhance your current code by adding a setter like so:

(function(window, undefined) {
    var MyLib = (function() {
        var AbortProgram = true;
        function DisplayAbortProgram() { alert('AbortProgram inside=' + AbortProgram); }
        function setAbortProgram(v) {AbortProgram=v}
        return { AbortProgram: AbortProgram, DisplayAbortProgram: DisplayAbortProgram, setAbortProgram:setAbortProgram}
    } ())
    window.MyLib = MyLib;
})(window);

MyLib.setAbortProgram(false);
alert('AbortProgram outside=' + MyLib.AbortProgram);
MyLib.DisplayAbortProgram();

Answer №2

Indeed, the method of passing in this case is by value and not reference. To work around this, you can create a parameters object that will be passed by reference:

 var params = { ToggleOption: true };

Instead of passing ToggleOption directly, pass around params. Then, you can access the boolean value using params.ToggleOption.

Answer №3

The primary reason is that JavaScript only returns values for primitive types and not references.

It's worth noting that all primitive types are passed as values, while objects are references to their properties.

After researching this topic, it seems there is no way to return a reference to a boolean variable. As a solution, I will create a function called SetAbortProgram(value).

Indeed, if you need to modify the variable, implementing a function would be necessary. Alternatively, using the object's property throughout may also suffice.

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

Avoid displaying the image when encountering a 404 error, but sometimes a broken image may still appear momentarily

Here is the code snippet I'm currently using: <img ng-show="json.user.picture" ng-src="{{json.user.picture}}" ng-error="json.user.picture = false"> When accessing an image from an external website without permission, a 404 error code is return ...

Accessing stored data in Android webview when server connection is unavailable

I have an Android application that utilizes a webview. The backend server is written in Java and serves all the front-end files, creating the cache manifest through Apache Tomcat. My predicament lies in figuring out how to make the webview load from the a ...

Ways to conduct a comparison of elements within an array within the same document

Is there a way to compare elements, by their index, within the same array in a MongoDB document? For example, consider the following entry: { "_id" : ObjectId("1"), "arr" : [ { "int" : 100 }, { "int" : 10 } ] } I have a collection with numerous similar e ...

unable to retrieve parent ID

I am having trouble retrieving the ID of the parent's parent of the event target. It keeps coming back as undefined, but I have verified through firebug that the ID does exist. Below is my HTML markup: <div class="grid-stack-item ui-draggable ui- ...

I'm curious why my background generator is only altering a portion of the background instead of the entire thing

I've been attempting to create a JavaScript random background changer, but I'm encountering some challenges. The main issue is that instead of changing the entire page's background, it only alters a strip of it. Additionally, I'm curiou ...

Guide on retrieving information from mongodb with nodejs and expressjs

Check out my code in the file named student.js var mongoose = require('mongoose'); var studentSchema = new mongoose.Schema({ name:{ type: String, required: true }, rollno:{ type: Number, required: tr ...

Delete the initial instance of a specific element with JavaScript or Lodash

I am working with an array that looks like this - ["a", "a", "b", "c", "d", "e"] My goal is to filter this array in a way that removes only the first occurrence of each element. Based on the exa ...

Guide to organizing a program for adding items to a list using Backbone.Marionette

One thing that continues to confuse me about Marionette is how to structure it efficiently. Let's consider a simple interface for displaying a list of comments and adding a new comment. I am currently structuring this using a CommentApp as shown belo ...

What is the process for inserting a new item into a JavaScript dictionary?

I have a specific dictionary structure that lists different movies along with their respective actors. I want to create a function that allows me to manipulate this dictionary to include additional actors based on certain criteria. Here is an example of t ...

The Bootstrap datepicker functions properly when used in plain HTML, but encounters issues when implemented within the .html()

Using HTML: <input class="m-ctrl-medium date-picker" size="16" type="text" id='lateETD1' name="dateRecv" value=""/> Not working with script: var ETD = $("#ETD"); ETD.html("<input class='m-ctrl-medium date-picker' id='la ...

The tally of seconds within a year has been altered

I have developed a function that converts inputted seconds into an output format of Years, Days, Hours, Minutes, and Seconds for the user. While I am still refining the various outputs and improving the syntax, I am currently focused on identifying a calcu ...

Is there a way to programmatically scan through all directories and include only files with a .js extension into my Discord collection?

I'm currently working on the following code and I'm looking for a way to adjust it in order to check each sub-directory: const fs = require('fs') module.exports = (client, Discord) =>{ const command_files = fs.readdirSync(' ...

The challenge with handling matrix arrays in Javascript

In my simplified drag and drop shopping cart project using jqueryui, I am encountering an issue with adding data (id, name, price) to an array. Despite trying various methods to add the data array to the main container, I consistently encounter the error ...

Solve the problem with SCSS at the component level in NextJS

I've decided to transition my regular React app to Next.js. In the past, I would simply import SCSS files using: import from '.componentName.scss' However, now I need to import them using: import style from 'componentName.module.scss ...

Dynamically divide canvas screens based on fabricjs dropdown selection

I am attempting to implement split screens in fabric js, such as 1, 2, 4, 8, and 16. The screen should split based on the selection from the dropdown menu. Check out my current code where I have successfully uploaded images. If I click on the images, th ...

Save JSON data from Javascript to a file on the server without using a server-side application

I am currently working with a .js client and need to save an object to a file on the server. This is new to me as I am not familiar with file i/o using JavaScript. My plan is to utilize jquery and json for this task, and I am using java serverside. Althoug ...

Using Rails 5 to return HTML in response to an AJAX request (rather than javascript)

(Running on Rails version 5.1.2) I am interested in returning HTML instead of javascript as a response to AJAX calls, for similar reasons mentioned in this particular discussion on Stack Overflow. Despite my efforts, I have been unable to make it work su ...

Switch between hiding and showing the DIV element flaw

I am currently working on a piece of code that involves simple HTML and JS to show/hide elements. Here is the code snippet: // Enabling forEach for 'querySelectorAll' and 'getElementsByClassName' HTMLCollection.prototype.forEach = No ...

Advantages of using index.js within a component directory

It seems to be a common practice to have an index file in the component/container/module folders of react or angular2 projects. Examples of this can be seen in: angular2-webpack-starter react-boilerplate What advantages does this bring? When is it recom ...

Using Javascript to perform redirects within a Rails application

Currently working on a Facebook application using Rails. There are certain pages that require users to be logged in, otherwise they will be directed to a "login" page. I am unable to use redirect_to for this purpose as the redirection must be done through ...