JavaScript: The Battle of Anonymity - Anonymous Functions vs Helper

I'm currently grappling with a piece of functional style code that is featured in the book Eloquent Javascript:

Here's the issue I'm facing: When I have the count() function passing an anonymous function to reduce(), everything seems to work perfectly. However, once I try breaking out the function into a helper function (countHelper()), I encounter a reference error.

If anyone could shed some light on why count() works smoothly while countHelper() throws an error, I would greatly appreciate it!

var numbers = [1,2,3,0,1,2,3,0]

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

function reduce(combine, base, array) {
  forEach(array, function (element) {
    base = combine(base, element);
  });
  return base;
}

function equals(x) {
  return function(element) { return x === element;};
}

function count(test, array) {  
  return reduce(function(base, element) {
    return base + (test(element)?1:0);
  }, 0, array);
}

function countHelper(test, array) {
  function helper(base, element) {
    return base + (test(element)?1:0);
  }
  return reduce(helper(base, element), 0, array);
}

function countZeroes(array) {
  return count(equals(0), array);
}

print(countZeroes(numbers)) // 2

function countZeroesHelper(array) {
  return countHelper(equals(0), array);
}

print(countZeroesHelper(numbers)) // ReferenceError: base is not defined

Answer №1

When using countHelper(), ensure that you are passing a reference to the helper function rather than calling it immediately and passing its return value to reduce(). Here is the corrected code:

function countHelper(test, array) {
  function helper(base, element) {
    return base + (test(element)?1:0);
  }
  return reduce(helper, 0, array);
}

Remember not to include parentheses when passing a function as an argument, as this will execute the function instead of just passing a reference to it.

Making this distinction is crucial in Javascript, where any type can be passed as an argument. Even experienced programmers can fall into this trap, so understanding the difference between executing a function and passing a reference to it is essential.

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

limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property. For example, http://localhost:1234/api/wine?year= ...

What is the trick to have a CSS element overflow the boundaries of its containing div entirely?

Currently, I have a JS Fiddle project where I am attempting to achieve a specific effect. In the project, there is a circle positioned at the center of a div. When the script runs, the circle expands evenly in all directions until it reaches the borders on ...

Altering the input field's content in response to a button click through JavaScript's addEventListener function

I am struggling to get the input text from a form field to change when a button is clicked using JavaScript. I can't seem to figure out why it isn't working correctly. Any assistance would be greatly appreciated. <!doctype html> & ...

Prettier eliminates the need for parentheses in mathematical expressions

When working with mathematical expressions in React and attempting to slice an array based on those expressions, I encountered an issue with the Prettier extension. It automatically removes parentheses from the expressions, resulting in incorrect calculati ...

Using Jquery to change an id with the .attr method may not always produce the desired results

I have a div element that functions as a button when clicked, with the ID of knight. Every time I click on any of the 3 buttons (including knight), it changes the ID of knight to elf (yes, I'm creating a game). I have a hover effect for knight usi ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

Can one extract the content from a secure message received from a Telegram bot?

Currently, I am utilizing the sendMessage() function with protected_content: true in order to prevent Telegram users from forwarding my bot's messages to others. Prior to implementing this setting, the text below was easily copyable. However, after e ...

Is it possible to develop a function that can verify various input values and modify their appearance as needed?

I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left emp ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

Unable to render chart using angularjs-nvd3-directives

After developing a basic Angular - nvd3 project, I decided to utilize liveData.example from the angularjs-nvd3-directives Library on Github. To tailor it for my needs, I made enhancements to integrate with my REST API. Here is the REST API endpoint: http ...

The console log is not being displayed in my Redux reducer and it is returning an undefined

I'm facing an issue with my Redux application after integrating JWT into my Nest API. Below is the code snippet from my reducer: export default function reducer(state = {}, action) { switch (action.type) { case 'USER_LOGIN_SUCCESS&apo ...

Vue.js - when it comes to rounding off digits, I keep getting unexpected results

Currently, I am in the process of calculating my totals and I need to ensure that they are fixed to 2 decimal places. Here is a snippet of my code: this.selectedCompaniesDetails.forEach((company) => { if(company.id == p.compa ...

What is the best way to transfer data from one function to another file in React without directly calling the component or using props?

filename - Header.jsx import { useEffect, useState } from 'react' import { getValue } from './Input' import TextField from '@mui/material/TextField'; export const Header = () => { const [search, setSearch] = useState( ...

What is the best way to access nativeElements during the ngOnInit lifecycle hook?

Assume in my angular script I have the ability to access an HTML element with viewChild('someDiv') or constructor(private elem: ElementRef){}. When my angular component loads, I want to immediately retrieve a property of that element and store it ...

Execute controller action upon item selection within KODataTable MVC table

I am displaying data in a table using AJAX to call an Action that returns a JSON list. Output: I want each user (row in the table) to be clickable and linkable to an edit page (Admin/Edit/Id). This can be done either by clicking on them or by having an E ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

Retrieving the nth character from a given string

How can I extract every 3rd character from a given string, such as the word GOOGLE? I have attempted to accomplish this using JavaScript, but I am unsure of what code to include after the 'if' statement. function getNthElements(string) { v ...

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

Tips for informing flowtype of expanding a partial options object to ensure it is fully developed by a specific stage

Most of you are probably familiar with a very simple use case from your projects. Imagine you have a utility class or function that looks like this: type Options = { foo?: string }; class Something { static get defaultOptions(): Options { ...