Are JavaScript closures supposed to prevent the array from being editable through getArray()?

Primary objective: Allow arr information retrieval exclusively through the getArray method.
Secondary objective: Enable arr data modification solely through the addToArray method.

function TestObj(){
  var arr = [];
  var b = 3;

  this.getArray = function(){
    return arr;
  };
  this.addToArray = function(val){
    arr.push(val);
  };

  this.getNumber = function(){
    return b;
  }
  this.setNumber = function(val){
    b = val;
  }

}

var obj = new TestObj();

obj.addToArray('derp');
console.log(obj.getArray());

//['derp']

obj.getArray().push('aderp');

console.log(obj.getArray().length);

// 2

There is some confusion. Isn't getArray supposed to return a reference to the arr array, not the array itself? This concept extends from closures, am I missing something here?


Reflective process:

Considering,
obj.getNumber()
yields 3,

and
obj.setNumber(4)
followed by
obj.getNumber()
results in 4

trying:
obj.getNumber() = 5
fails with "invalid left-hand..."

in that case, why does

obj.getArray().push('thing')

have the ability to modify the array...since it is a variable within the function's scope... it should be encapsulated within the closure, accessible only through the getArray / addToArray interface...

Answer №1

If you want to create a new array without referencing the original one, you have two options:

Shallow Copy

this.createArrayCopy = function(){
    return originalArray.slice(0);
};

Deep Copy

this.createArrayCopy = function(){
    return JSON.parse(JSON.stringify(originalArray));
};

Answer №2

To achieve either read-only or write-only access to an array without the need for duplicating the array, consider wrapping the array in an object. Implement specific functions for reading and writing to access the individual elements within the array.

Simply referencing the entire array does not offer the desired level of access control.

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

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

Displaying and hiding a div element using Vue.js dynamically

I have a scenario with two different sized divs: <div class = "bigger"> </div> <div class = "smaller"> </div> The goal is to hide the bigger div and show the smaller div when the screen width is ...

I am looking to utilize the data from a POST request to dynamically update the DOM through a script.js file. How can

After sending a post request, I am looking to update my database and then use an array to dynamically update the HTML content. However, I am struggling with how to pass this data to my script.js file. Here is my progress so far: SERVER let expenseAmo ...

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

Struggling to fill in fields using express and Mongodb

I am facing an issue with populating the fields of two models, Post and User. const PostSchema = new Schema({ text: { type: String }, author: { type: mongoose.Schema.Types.ObjectId, ref: 'user' } }) cons ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

The message sent by the node containing a large body (1.3 mb) encountered an error: 413 Request Entity Too Large

Using Fiddler, I am creating a POST message with a header. Content-Type: application/text-enriched app.post('/books',function(req,res){ var writeStream = fs.createWriteStream('C://Books.txt' ,{ flags : 'w' }); ...

What could be causing the Firebase email verification to result in a 400 error?

I've been struggling to implement email verification in my React website. Every time I try to use the sendSignInLinkToEmail function, I keep encountering this error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=XXXXXXXXXXX ...

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

Challenges with Scope in Using AJAX Calls within an Infowindow

Could it be a scope issue? Feel free to correct me if I'm mistaken. I've got a for loop that's placing markers on my map. Each marker has a different infowindow that loads content using ajax callbacks. This is a simplified version of the s ...

Encountering the "Headers have already been sent" error in NodeJS

I recently started working with node and I'm in the process of developing a rest node API. I've implemented Express for HTTP and JWT for authentication. However, when I make a request to /node/me with the header 'x-auth', I encounter th ...

angular2 : problem encountered with communication to rest api

Transitioning from PHP to Angular2 has been quite challenging for me, especially when trying to use a real rest API like "Tour of Heroes". I initially thought it would be simple... Currently, I have set up a functional API with Express: curl -XGET http:/ ...

Having trouble accessing Vuex's getter property within a computed property

Can you help me troubleshoot an issue? When I call a getter inside a computed property, it is giving me the following error message: TS2339: Property 'dictionary' does not exist on type 'CreateComponentPublicInstance{}, {}, {}, {}, {}, Com ...

Combining parametrized type arrays using Guava

I needed a simple way to loop through two arrays, and since they are not expected to be large, I thought I could just concatenate them. However, the Guava code for this operation looks messy: Class<? extends MyInterface>[] a2 = ... ...

The graph visualization fails to update properly even after attempting to redraw it

A new feature has been added to the website that allows users to zoom into specific areas of graphs created using Flot objects. An array containing all the Flot objects on the screen has been implemented, and the selection plugin is being used for this pur ...

Math operations limited by boundaries: adding and subtracting

What is the proper way to implement this logic in JavaScript: Row-=21; if (Row < 1) { Row = 1; } ...

How can I create a script for a sliding/toggling menu?

Not sure if it's appropriate to ask, but I'm currently in search of a slide/toggle menu. Despite my efforts on Google, I haven't been able to find exactly what I need. As someone who is more skilled in HTML/CSS than jQuery or other scripting ...

React: Issue with array rendering order after initial render

After the initial rendering of my array in the correct order, any subsequent changes to it result in the same rendered order. Let's consider this scenario: initializeArray() { this.state = { test_array: [1,2,3,4] } let self = t ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...