Getting the array's new length after a push operation in the application function

One of my app functions is responsible for storing data. It allows users to add new items and returns the length of the data array.

I've observed a strange behavior where returning the data itself in a function includes the pushed items, but returning data.length or using a filter does not. Surprisingly, when I request the data length outside of the app function scope, it does show the added items.

In this particular case, getfn, app.data.length, and app.data.filter properly reflect the added items, while getcntfn and filterinitialfn do not. What could be causing this unexpected outcome?

var app = (function () {
        var data = ["initial"];

        function add(x) { data.push(x) }

        function getfn() { return data };
        function getcntfn() { return data.length };
        function filterinitialfn(filter) { return data.filter(x => x == filter) }

        return {
            add: function (x) { add(x) },
            data:data,
            getfn: getfn(),
            getcntfn: getcntfn(),
            filterinitialfn: function(filter) {filterinitialfn(filter)}
        }
    }());

    app.add("added")

    console.log("app.getfn", app.getfn)                                             //["initial", "added"]
    console.log("app.getcntfn", app.getcntfn)                                       //1  ???
    console.log("app.data.length", app.data.length)                                 //2
    console.log("app.filterinitialfn", app.filterinitialfn("added"))              //[]  ???
    console.log("app.filterinitial=>", app.data.filter(x => x == "added"))          //["added"]

Answer №1

since the function is being called immediately upon returning, it remains in its original state and cannot be modified, to work around this issue:

return {
            add: function (x) { add(x) },
            data:data,
            getfn: getfn,
            getcntfn: getcntfn,
            filterinitialfn: filterinitialfn,
        }

remember to use parentheses when invoking the function.

Answer №2

For instance, the outcome of invoking getfn: getfn() is assessed during initialization and remains constant when called later.

You must pass the function itself without executing it to ensure evaluation upon invocation:

getfn: getfn,
getcntfn: getcntfn,
...

Given that all functions share the same name as their corresponding object keys, we can utilize the shorthand notation to construct the object:

var app = (function () {
var data = ["initial"];

function add(x) { data.push(x) }
function getfn() { return data };
function getcntfn() { return data.length };
function filterinitialfn(filterBy) { return data.filter(x => x == "added") }
function filterBy(filterBy) { return data.filter(x => x == filterBy); }

return {
    add,
    data,
    getfn,
    getcntfn,
    filterinitialfn,
    filterBy
}
}());

app.add("added")

console.log("app.getfn", app.getfn())
console.log("app.getcntfn", app.getcntfn())
console.log("app.data.length", app.data.length)
console.log("app.filterinitialfn", app.filterinitialfn())
console.log("app.filterinitial=>", app.data.filter(x => x == "added"))
console.log("app.filterBy", app.filterBy('initial'))

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

Traversing through an array within a Fetch request

My JSON object looks like this: [{"user": "poetry2", "following": ["Moderator", "shopaholic3000"]}] I have implemented a Fetch API in this way: fetch (`/profile/${username}/following`) .then(respon ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

displaying solely the bottom two rows while concealing the remainder

Looking for a Google Docs script that can automatically display only the last two rows in a spreadsheet. The goal is to have the new data added in a row and when ENTER is pressed, it will show only the latest two rows while hiding all others. I've st ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

Verify if an express module has a next() function available

Is there a method to check if there is a function after the current middleware? router.get('/', function(req, res, next){ if(next){//always returns true } }); I have a function that retrieves information and depending on the route, thi ...

What is the method for altering the color of the webkit-slider-thumb using JavaScript?

I am looking to adjust the color of an input range using JavaScript instead of CSS. Can someone help me with this request? Current CSS Code: input[type='range']::-webkit-slider-thumb { -webkit-appearance: none; background: goldenrod !importa ...

The npm system is encountering difficulties in parsing the package.json file

Having recently started using npm and node, I decided to create a react app with truffle unbox react using npm init react-app. Despite attempting to reinstall npm and clear the cache multiple times, I consistently encounter an error when trying to run sudo ...

Encountering a problem where updating the selected option in a dropdown does not properly refresh the HTML

I am currently working with a dropdown menu containing countries. Initially, the selected item is set to Ukraine. <select id="country" name="country"> <option value="US">USA</option> <option value="UG">Uganda</option> ...

Loading SVG images in advance

I am in possession of around one hundred simple SVG images, distributed among five different image folders. These images are currently retrieved on demand when they need to be displayed, which generally works well but occasionally results in flickering tha ...

How can I make Bootstrap Carousel slides transition as I scroll?

I have implemented the Bootstrap carousel on my website, but I am looking to customize its functionality. Specifically, I would like the slides to change whenever the user scrolls with their mouse. Is there a way to achieve this using Bootstrap Carousel? ...

React BrowserRouter causing issues with "invalid hook calls"

Just starting out with React and I am working on setting up paths using BrowserRouter, Route, and Routes in my code. import React from "react" import "./App.css"; import { BrowserRouter as Router, Route, Routes } from 'react-router ...

Access WordNet using JavaScript

Currently developing a web application that involves NLP tasks. In my past projects, I have used the JWNL library in Java which has always served me well. I am curious to know if you have any advice on the most effective approach for querying the WordNet ...

Getting around popup blockers on safari

Here is the HTML code I am working with: <a href = "#" class="fb">Facebook</a> I am using an onclick event handler that triggers window.open when the link above is clicked. This works fine in Chrome, but it does not work in Safari. How can I ...

PHP declares nullable types

Are there any distinctions between this function in PHP 7.4? public function foo(string $nullableArgument = null) {} public function bar(?string $nullableArgument = null) {} ...

Is it necessary to package files before releasing a library on npm?

Here's a rough overview of my project structure: dist/ - helper.compiled.js - entrypoint.compiled.js src/ - helper.js - entrypoint.js As I was going through the npm publishing guidelines, I noticed they recommend providing a single index.js fi ...

Is there a jQuery tool that can effortlessly add items to a list element?

I'm currently developing a task management application on the web. I have a textarea where users can input tasks, and when they press enter, it should automatically be added to a list element (li). The adding functionality works, but only after refres ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

Type inference in Typescript is especially powerful when used in conjunction with decorators

I am curious as to why the compiler in Typescript cannot infer the new type of a class when decorators or annotations are used. Interestingly, if I use the traditional ES5 method (manually calling the decorator), it works without any issues. Here is an ex ...

Issues with events not properly attaching to elements within Angular Directives

In my current Angular app project, I've encountered an issue with ng-click not binding to an element that is brought in via a Directive. The app itself is focused on goal planning and this particular section tackles the obstacles individuals face when ...