JavaScript: Receiving Varied Outputs from Comparable Functions

Here are two code snippets that contain an object and a function, both with identical content. They should theoretically return the same value. The only difference between the two is the presence of brackets and an 'else' statement in the 'for loop' of the function in the second code snippet.

Why do these functions return different values instead of the expected same value? Thank you!

var employees = [{
  firstName: 'Ollie',        
  lastName: 'Hepburn',
  role: 'Boss'
}, {
  firstName: 'Morty',
  lastName: 'Smith',
  role: 'Truck Driver'
}, {
  firstName: 'Peter',
  lastName: 'Ross',
  role: 'Warehouse Manager'
}, {
  firstName: 'Cal',
  lastName: 'Neil',
  role: 'Sales Assistant'
}, {
  firstName: 'Jesse',
  lastName: 'Saunders',
  role: 'Admin'
}, {
  firstName: 'Anna',
  lastName: 'Jones',
  role: 'Sales Assistant'
}, {
  firstName: 'Carmel',
  lastName: 'Hamm',
  role: 'Admin'
}, {
  firstName: 'Tori',
  lastName: 'Sparks',
  role: 'Sales Manager'
}, {
  firstName: 'Peter',
  lastName: 'Jones',
  role: 'Warehouse Picker'
}, {
  firstName: 'Mort',
  lastName: 'Smith',
  role: 'Warehouse Picker'
}, {
  firstName: 'Anna',
  lastName: 'Bell',
  role: 'Admin'
}, {
  firstName: 'Jewel',
  lastName: 'Bell',
  role: 'Receptionist'
}, {
  firstName: 'Colin',
  lastName: 'Brown',
  role: 'Trainee'
}];

function findEmployeesRole(name) {
  for(var i = 0; i < employees.length; i++)
    if(name === employees[i].firstName + " " + employees[i].lastName) return employees[i].role;
  return "Does not work here!";
}
                                      
                                      console.log(findEmployeesRole("Colin Brown"));

The function below the object in the following code snippet includes brackets within the for loop.

var employees = [{
  firstName: 'Ollie',
  lastName: 'Hepburn',
  role: 'Boss'
}, {
  firstName: 'Morty',
  lastName: 'Smith',
  role: 'Truck Driver'
}, {
  firstName: 'Peter',
  lastName: 'Ross',
  role: 'Warehouse Manager'
}, {
  firstName: 'Cal',
  lastName: 'Neil',
  role: 'Sales Assistant'
}, {
  firstName: 'Jesse',
  lastName: 'Saunders',
  role: 'Admin'
}, {
  firstName: 'Anna',
  lastName: 'Jones',
  role: 'Sales Assistant'
}, {
  firstName: 'Carmel',
  lastName: 'Hamm',
  role: 'Admin'
}, {
  firstName: 'Tori',
  lastName: 'Sparks',
  role: 'Sales Manager'
}, {
  firstName: 'Peter',
  lastName: 'Jones',
  role: 'Warehouse Picker'
}, {
  firstName: 'Mort',
  lastName: 'Smith',
  role: 'Warehouse Picker'
}, {
  firstName: 'Anna',
  lastName: 'Bell',
  role: 'Admin'
}, {
  firstName: 'Jewel',
  lastName: 'Bell',
  role: 'Receptionist'
}, {
  firstName: 'Colin',
  lastName: 'Brown',
  role: 'Trainee'
}];

function findEmployeesRole(name) {
  for (var i = 0; i < employees.length; i++){
    if(name === employees[i].firstName + " " + employees[i].lastName){
      return employees[i].role;
    } else {
      return "Does not work here!";
    }
  }
}

console.log(findEmployeesRole("Colin Brown"));

Answer №1

The second block of code only checks the first item and then stops. If there is a match with the first item, it returns the role; otherwise, it simply returns "Does not work here." The loop does not continue beyond the initial check.

In contrast, the first block of code has the return statement placed outside the loop. This setup ensures that all items are checked before returning "Does not work here." By adding braces, the code would be structured like this:

function findEmployeesRole(name) {
    for (var i = 0; i < employees.length; i++) {
        if (name === employees[i].firstName + " " + employees[i].lastName) {
            return employees[i].role;
        }
    }
    return "Does not work here!";
}

Using braces consistently is recommended to avoid confusion or misinterpretation of code logic.

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

Converting Javascript Variables into a PHP Script

After noticing that the same question was being asked repeatedly, I delved into thorough research to discover effective methods for transferring a couple of JavaScript variables to a PHP script. Include data in a form as hidden values Send to URL, like & ...

The useParams() function is returning undefined, even though the parameter does exist in the destination URL

I have a complete inventory of items called "Commandes" (PS: the app is in French), displayed in a table with a column for each row that should redirect me to another component showing more details about the selected row. To achieve this, I need to utilize ...

Can a reducer be designed to accommodate varying states dynamically?

Welcome to my React Application for ages 16 and above, featuring Redux. Within my bookRoom.js file, I have a component called bookRoom which is responsible for rendering a single rectangle on the screen, symbolizing a room. You can see a sample render of ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...

I'm having trouble getting NextJS dynamic routes to function properly on my local server

src/app/user/[username].js [username].js content: import { useRouter } from 'next/router' export default function User() { const router = useRouter() return ( <p> {router.query.username} </p> ); } Upon visiting ...

ReactJS tweet screenshot capture

Currently seeking a solution to capture a tweet screenshot, store it in a PostgreSQL database, and display it on my ReactJS webpage using Typescript. I have been utilizing react-tweet-embed for displaying the tweet, but now I require a method to save the i ...

Under what circumstances would window.location fail to function in a web browser? (excluding disabled JavaScript)

Is there a scenario where window.location may not function properly? I have considered that certain older versions of Internet Explorer may block the javascript redirect due to security restrictions. Can anyone confirm this? Are there any specific browse ...

Is there a way to conceal the toggle division following a postback in ASP.NET?

Here is the script code I am working with: <script type="text/javascript> $(document).ready(function () { var $content = $(".contentPersonalDetail").hide(); $(".togglePersonalDetail").on("click", function (e) { $(this ...

What measures can be taken to stop AngularJS binding from occurring repeatedly?

Currently, I am facing an issue with my select element: <select ng-model="p.value" ng-options="q for q in p.value"> <option value="">Select an animation</option> </select> The initial values in p.value are ['AAAAA', &apo ...

Disrupting a Program Operation

We are utilizing the gauge Google Chart applet to visually track the failure rates of message transfers on a SOAP interface via AJAX. My goal is to make the page's background flash red and white when the failure rate reaches 50% or higher, and remain ...

I am hoping for JavaScript to perform three distinct actions depending on the names of the files that are currently open in Photoshop

Currently, I am in the process of developing a JavaScript script for Photoshop. The main objective of this script is to prompt the user to choose a folder containing multiple files. Subsequently, the script will open each file within the folder and perform ...

Convert the class to a file upload using jQuery

I am currently working on a project involving a file upload script. I have multiple directories where the files need to be uploaded, and I'm attempting to use a single form for this purpose. So far, I have been able to change the form class using jQu ...

What exactly is the purpose of calling upon 'express' - a reference to a function or an object?

It is my belief that by utilizing var express = require('express');, the variable express receives a function reference of createApplication(). So, when we invoke express(), it will yield an app object. However, my question is, if var express is ...

Set options for nested arrays with up to n levels of children

My project involves building a category module using Laravel for the backend and Vue.js for the frontend. I have incorporated the library Laravel Nestable The library has been successful in producing the desired output. [ { "id": 1, "name": "C ...

Is it possible to alter the content of a <h1> tag in order to display different text?

Is there a way to dynamically change the displayed text in my program based on different states such as 'loading' or 'updating', without having to refresh the page? For example, if the state is loading it should display "loading your da ...

Preventing a timer from pausing in NextJS during periods of inactivity

Recently, I developed a straightforward timer application using Next.js that should continue counting even when the browser window is inactive. However, I noticed that if I switch to another window for approximately 5 minutes, the timer stops counting whi ...

Does it typically occur to experience a brief pause following the execution of .innerHTML = xmlhttp.responseText;?

Is it common to experience a brief delay after setting the innerHTML with xmlhttp.responseText? Approximately 1 second delay occurs after xmlhttp.readyState reaches 4. This issue is observed when using Firefox 3.0.10. ...

Create a global SCSS file in ReactJS that stores all variables, mixins, and more

Looking for a solution to manage multiple components in your SCSS project efficiently? Consider creating a central file that houses all your variables and mixins, making them globally accessible without the need to manually import the file into every SCSS ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

JSON with an undefined or null value

Trying to access an API that contains a specific tree structure: {"19777621": [{ "queue": "RANKED_SOLO_5x5", "name": "Vladimir's Maulers", "entries": [{ "leaguePoints": 0, "isFreshBlood": false, "isHotStreak": true, " ...