"Using the every() method in underscore.js with an undefined parameter

I recently wrote some code and encountered an unexpected result:

var a = new Array(10); // should be [undefined * 10] 
var b = _.every(a, function(m){
    if(_.isUndefined(m)){
        return false;
    }
    return true;
});

I anticipated that b would be 'false', but to my surprise it returned 'true'. Why did it return 'true' instead?

Curious about this outcome, I made a modification:

var c = [undefined, undefined];
var d = _.every(c, function(m){
    if(_.isUndefined(m)){
        return false;
    }
    return true;
});

In contrast to the previous case, d returned 'false'. What caused these different results?

If you're interested, feel free to test this scenario using http://jsfiddle.net/3qj4B/3/

Answer №1

Creating an array using the class initializer allocates 10 spaces of memory, but they are not initialized yet. This means there is no looping over any elements in the array.

Take a closer look at the every source code:

_.every = _.all = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = true;
    if (obj == null) return result;       
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
};

The variable result is initialized as true and returned because there are no iterations performed by each. This explains why true is being returned.

In your fiddle, if you add a console.log(m) inside the handler, no logs will be displayed in the console since each does not iterate at all.

Answer №2

There is a fine distinction between initializing an array using the Array constructor with an initial size and initializing it with a specific list of undefined entries. The former, utilizing the Array constructor, does not generate properties corresponding to the indexes, whereas explicit initialization does.

I have a suspicion that Underscore makes use of the built-in .forEach() function whenever possible, which means it will not invoke its callback for uninitialized indexes. Consequently, in the initial test scenario, the callback to _.every() is never triggered at all.

edit — Essentially, the Array constructor behaves somewhat like this:

var a = []; a.length = 10;

When you extend an array by increasing its length in that manner, the new implicit index positions remain uninitialized. This marks the fundamental disparity between the absence of a property and the presence of a property without a value. In both instances, accessing the property results in undefined. Thus:

var o = {};

if (o.something == undefined) // this condition evaluates to true

and subsequently:

var o = { something: undefined };

if (o.something == undefined) // also true

One way to distinguish between these two scenarios is by utilizing the in operator:

if ('something' in o) // only true in the latter case

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

Is there a way for me to obtain output from a different Angular component?

After watching an Angular tutorial and following the steps, I am facing difficulties with the @Output feature. I am unable to receive values from another component in my home component. I attempted to use Output with EventEmitter but for some reason, it i ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

What is the best way to retrieve an attribute from an object dynamically using JavaScript?

Inside my object, I have the following values: obj.resposta1 obj.resposta2 obj.resposta3 obj.resposta4 How can I access each value inside a loop like this: for ( var int = 1; int < 5; int++) Thank you, Celso ...

Interested in trying out Express and socket.io for chatting?

I've successfully set up the chat application, but now I'm faced with a dilemma: how can I make the chat work on the default port:80, where my main site is hosted? One solution that comes to mind is using an iframe - but is there another way? B ...

The mobile screen size shortcuts are malfunctioning, while the regular links are functioning properly

ISSUE: Links in alias buttons are not working on mobile screen size, while normal links to other webpages like social media work fine. Description I created a project using an HTML, CSS, JS building tool from The project was exported and placed into a ...

Tips for organizing a list in Angular 1 when a button is clicked

I'm looking for help with sorting a list in Angular 1 when a button is clicked. I want the ability to toggle between ascending and descending order on each click. Here is a link to the code: https://plnkr.co/edit/HYuk7DAgOY6baWhrvXko?p=preview var ap ...

Issue with undefined object in ExpressJS PUT method

Attempting to utilize the PUT method for updating a record in my database, I encountered an issue with the object not being defined. ReferenceError: blogpost is not defined Following this tutorial for routing steps, I noticed that while the variable is d ...

The Next.js component only appears after a page reload

Essentially, I have a nested component that is supposed to render with the parent component and it works fine when the server initially starts. However, the issue arises when switching back from another page – some of the nested components disappear. A ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Exploring all the options within a dropdown menu using JQuery

Within the MVC 4 view, there is a dropdown box that, when its value changes, needs to capture all selected values. Each selection consists of three items: the Id, the visible value on the form, and a path to a file. While the functionality works for readin ...

What is the best way to reset an a-select component in Ant Design Vue?

I need to programmatically reset the selection in my a-select component after a specific event is triggered. Here's an example of my a-select code snippet: <a-select style="marginTop: 8px;width: 20%" @change="onChanged" > ...

What is the best way to provide Monaco editor's loader.js and its dependencies on a local server for my React project?

Currently, I have integrated Monaco Editor in my project by utilizing the npm package Monaco Editor. When I build and serve my code on localhost, I noticed that the Loader Script is being loaded from a Content Delivery Network (CDN). I am curious to know ...

Enhancing MongoDB query efficiency using Promise technology

At the moment, I am deeply involved in a personal project that is presenting a challenge with two different approaches to querying MongoDB. CustomerSchema.methods.GetOrders = function(){ return Promise.all( this.orders.map(orderId => Order. ...

Troubleshooting: Issues with updating a text field in Vue test utils using Jest

Hello, I am new to Jest and unit testing. I have a question about how to set the value of a text input using Vue Test Utils. Here is the code for my custom text input component: <input v-model="local_value" @keyup.enter="submitTo ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

Tips for presenting JSON date in JavaScript using Google Chart

I am in urgent need of assistance with this issue. I am trying to display the date from PHP JSON data retrieved from my database in a Google Chart using JavaScript. Below is the PHP code snippet: $data_points = array(); while($row = mysqli_fetch_array($r ...

The program encountered an unexpected identifier 'getProject' instead of ';'. It was expecting to find a semicolon after the async variable declaration

When using this JavaScript on a webpage, I encounter an issue: <script async type="module"> import {projectCode} from "./assets/js/config.js"; import {getProject} from "./assets/js/saleproject.js"; import {getAccount} fr ...

Execute the JavaScript [ window:print() ] function once the webpage has finished loading along with any

I am facing an issue with my web page that has around 10 Google Analytics charts. I want to trigger a print dialog box once the page is fully loaded, including all the charts and JavaScript. Currently, the problem is that the print dialog box opens after t ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Tap on the HTML5 video to exit the fullscreen mode

Objective I have successfully implemented a fullscreen video setup that triggers when a link is tapped on a mobile device. To maintain a clean aesthetic, I have hidden the HTML5 video controls using CSS. The desired functionality includes closing the full ...