Can you tell me why the outputs of these two codes are different when I ran them?

Recently I was tackling a challenge in JavaScript where the task involved dividing the number of volunteers by the number of neighborhoods.

To achieve this, I decided to use the array method .length which would return the length of an array. However, what puzzled me was that while one approach passed the test, the other failed. Here are the two sets of code:

The code that passed the test:

const function(volunteers, neighborhood){
  let neighborhoodLength = neighborhood;
  let volunteersLength = volunteers.length
  let evaluate =  neighborhoodLength / volunteersLength;

  return evaluate;
}

The code that failed the test:

const function(volunteers, neighborhood){
  return volunteers.length / neighborhood.length
}

When provided with arrays like the following:

const volunteers = [
  'Sally',
  'Jake',
  'Brian',
  'Hamid'
];

const neighbourhoods = [
  'Central Valley',
  'Big Mountain',
  'Little Bridge',
  'Bricktown',
  'Brownsville',
  "Paul's Boutique",
  'Clay Park',
  'Fox Nest'
];

The expected output should be 2.

My main concern now is understanding why there was a variance in results between the two approaches. I am seeking clarification on why one passed and the other failed. Any insights or assistance in explaining this discrepancy would be greatly appreciated!

Answer №1

Was your initial code successful? Dividing an array by a number can result in Not-a-Number. You may want to give this a go.

function calculate(volunteersList, neighborhoodsList) {
    return volunteersList.length / neighborhoodsList.length
}

Answer №2

It seems like there is an error with the way you are declaring a function. Remember that function is a reserved keyword in JavaScript, so using it as part of const function {...} is not valid syntax. Make sure to name your function after the function keyword. Here's a corrected example:

const volunteers = [
    'Sally',
    'Jake',
    'Brian',
    'Hamid'
];

const neighbourhoods = [
    'Central Valley',
    'Big Mountain',
    'Little Bridge',
    'Bricktown',
    'Brownsville',
    "Paul's Boutique",
    'Clay Park',
    'Fox Nest'
];

function calculateAverage(volunteers, neighborhood) {
    return neighborhood.length / volunteers.length;
}

const arrowCalculation = (volunteers, neighborhood) => {
    return neighborhood.length / volunteers.length;
}

console.log(`regular function declaration:`, calculateAverage(volunteers, neighbourhoods));
console.log(`arrow function calculation:`, arrowCalculation(volunteers, neighbourhoods));


Answer №3

The outcome must remain consistent

  • Within the function two, instead of using
    volunteers.length / neighbourhoods.length
    , it should be
    neighbourhoods.length / volunteers.length
    because the sequence of factors in division impacts the final result

Revised code:

const volunteers = ['Sally','Jake','Brian','Hamid']
const neighbourhoods = ['Central Valley','Big Mountain','Little Bridge','Bricktown','Brownsville',"Paul's Boutique",'Clay Park','Fox Nest']

const one = (volunteers, neighbourhoods) => {
  const neighbourhoodsLength = neighbourhoods.length
  const volunteersLength = volunteers.length
  const evaluate = neighbourhoodsLength / volunteersLength

  return evaluate
}

const two = (volunteers, neighbourhoods) => {
  return neighbourhoods.length / volunteers.length
}

console.log('one:', one(volunteers, neighbourhoods))
console.log('two:', two(volunteers, neighbourhoods))

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

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

The html function does not contain the value of the textarea

While attempting to retrieve the HTML content of a div using the code below, I noticed that it does not include the text entered in the textarea or input field. var mywindow = $(printDiv).html(); The variable mywindow will contain all the HTML except fo ...

Utilizing the Java Script SDK for Facebook API to Publish Actions

I've been encountering difficulties with the Facebook API. I have created an app, an object, and an action, and I'm trying to test publishing in my stream (I understand that public publishing needs authorization from Facebook, but as an administr ...

Sending Location Data From JavaScript to PHP via Cookies

I encountered an issue while attempting to send Geolocation coordinates from JavaScript to PHP using Cookies. The error message I am receiving is: Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 The file name ...

Iterating through a collection of objects, triggering a promise for each object and recording its completion

I have encountered a challenge where I need to iterate through an array of objects obtained from a promise, and for each object in the array, I must invoke another promise. After all these promises are executed, I want to display "DONE" on the console. Is ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

Tips for handling notifications that have been read and unread in a React application

In my current project using React JS, I am tasked with creating a notifications component that will display account-related activities. The notifications need to be sorted into read and unread categories. My main question is how should I manage the read a ...

Activating a link without clicking will not trigger any javascript functions

I have been attempting to display an image when I hover over a link, but for some reason, the .hover() event is not functioning as expected. Initially, I am just aiming to have an alert pop up. Once I have that working, I can proceed with fading elements i ...

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...

Stop the inheritance of CSS and JavaScript in ASCX files

Currently, I have an application that consists of only one aspx page called Default.aspx. This page dynamically loads .ascx controls as required, all of which utilize the same JS and CSS file. I am now considering implementing Bootstrap on specific control ...

Angular does not seem to be triggering $watch for changes in arrays

Trying to activate a $watch function after a delay in Angular: Controller Information .controller('MyCtrl', ['$scope', function ($scope) { $scope.chickens = ["Jim", "Joe", "Fred"]; $scope.chickens.push("Steve"); setTimeou ...

I am encountering some difficulties with the functionality of the angularjs dialog

I've been attempting to integrate an AngularJS dialog feature into my application by following the examples provided on material.angularjs.org. However, despite copying everything accurately, I am unable to get it to function. Can anyone help identify ...

Transferring data between actions following an AJAX request in Zend Framework

I am currently utilizing an ajax call to communicate with a controller in order to update the number of articles displayed on the webpage. I have established an action within the controller to handle this ajax request. Below is a snippet of the code: publ ...

Switching between fixed and unfixed divs causes two absolute divs to alternate

I am currently working on a code to keep a fixed div ("two") in place between two absolute positioned divs ("one" and "footer") while scrolling. However, there is an issue that arises when the browser window is resized. The distance between the footer and ...

Generate a new passport session for a user who is currently logged in

I am currently utilizing passport js for handling the login registration process. After a new user logs in, a custom cookie is generated on the browser containing a unique key from the database. Here's how the program operates: When a new user logs ...

What steps can I take to optimize my code and eliminate any redundancies?

In a current project, I need to make calls to three different endpoints. The functions handling these requests are identical except for the URLs being called. Below is an example of the code: const handleSubmitRequest = (e, next, endpoint, requestData) =&g ...

Understanding how to activate a React navbar button is essential for creating a seamless user

How can I make my sidebar button change color when I navigate to the page it links to? ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

Solving the problem of Axis label alignment in Three.js grid and techniques for visualizing x, y, z data on

I have been tasked with plotting well deviation surveys on a 3D grid. After referencing several articles online, I successfully created a 3D grid of the required size. However, I am currently struggling with positioning the labels for the x, y, and z axis ...