Differences between Arrow function and regular function when used in Array.map()

While working on some JS challenges, I observed that when using arrow functions, the result is as expected. However, when I try the same code with a regular function, it doesn't work. Can someone please explain the difference or point out if there is a typo?

Here is the first solution (which works):

function titleCase(str) {
    str = str.split(' ').map(i =>  i[0].toUpperCase() + i.substr(1).toLowerCase()).join(' ')
    return str;
  }
   console.log(titleCase("I'm a liTTle tea pot")); // I'm A Little Tea Pot

And here's the second solution using a normal function (but it returns an empty string):

function titleCase2(str) {
    str = str.split(' ').map(function(i, index){ i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
    return str;
  }
   console.log(titleCase2("I'm a liTTle tea pot")); // empty string

https://i.sstatic.net/Gk7bN.png

You can access My Plunker from here

Answer №1

Ensure to include the return keyword within the callback function.

When using a fat-arrow function, the return keyword is automatically included for returning a value. However, in a regular function expression, you must explicitly use the return keyword to return a value.

function titleCase2(str) {
  str = str.split(' ').map(function(i, index) {
    return i[0].toUpperCase() + i.substr(1).toLowerCase()
  }).join(' ')
  return str;
}
console.log(titleCase2("I'm a liTTle tea pot"));

Answer №2

Non-arrow functions require an explicit return statement, while 1-line arrow functions automatically return the result on that line.

function convertToTitleCase(str) {
  return str.split(' ').map(function(word, index){ return word[0].toUpperCase() + word.substr(1).toLowerCase()}).join(' ')
}
console.log(convertToTitleCase("I'm a liTTle tea pot")); // I'm A Little Tea Pot

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

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...

React typescript is handling various promise response types, causing strange behavior in type-checking

I recently started utilizing the and I seem to be encountering a perplexing issue. If further context is needed, please let me know and I will provide it. All the necessary functions and types are mentioned below my explanatory paragraphs. Your assistance ...

Initiate the React application with the given external parameters

I have created a React app that is embedded within a webpage and needs to start with specific parameters obtained from the page. Currently, I am passing these parameters in the index.HTML file within a div element. The issue arises when these parameters ar ...

Problems encountered with React Image Magnifiers while attempting to zoom in with Next.js

When I try to use the react-image-magnifiers plugin to make an image zoom in on hover, it works fine without next.js. However, when I integrate it with next.js, the zoom functionality does not work. Could there be an issue in my next.config.js file? This ...

Transition effortlessly between web pages with subtle fading effects

I want to implement smooth page transition effects between two web domains: mcpixel.co.uk/new and mcpaper.co.uk. I am the owner of both domains. When a link in the header is clicked, I'd like the page to fade transition to the new page without any whi ...

Retrieve the attribute of the clicked element by utilizing the on click event handler

Within my HTML, there is a page displaying approximately 25 thumbnails, each with a like button in this specific format: <input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like"> It's important ...

Ways to fix vulnerabilities found in an NPM audit

Upon conducting an NPM audit, I found 5 critical issues. To address 4 of them, I attempted to update @storybook/addon-essentials & @storybook/react, as they were marked as "patched in >=x.x.x", indicating that the latest versions should have resolve ...

Utilizing ng-repeat in the select tag to include an additional blank choice in AngularJS

Working with AngularJS, I am creating a listbox using the select element and ng-repeat. Everything seems to be functioning correctly, but I am encountering an issue where a blank item is displayed at the top of the listbox. Here is the snippet of my HTML ...

JavaScript Scroller that keeps on scrolling

Unique Continuous JavaScript Scroller I am currently working on a JavaScript scroller script that enables left to right and right to left scrolling on the click of next and previous buttons. The script is designed to work with 1 to 3 div elements in a con ...

Tips for enhancing undo/redo functionality when working with canvas drawings in React

Currently, I am working on implementing undo/redo functionality for html-canvas drawing on medical (.nii) images in a React application. The images consist of slices stored in a Uint8ClampedArray and usually have dimensions around 500 (cols) x 500 (rows) x ...

Take users to another page upon form submission

I'm working on a React form using Typescript and Material-UI. Here's an example: import React, { useState } from "react"; import TextField from "@material-ui/core/TextField"; import { createStyles, makeStyles, Theme } from &qu ...

What is the best way to update the current route in Angular 2 programmatically?

In my Angular 2 application, I am facing an issue with the navigation flow between the home component and the nav panel component. When a user clicks on the logout button in the nav panel, the current URL is correctly shown as "/login" in the console log. ...

Encountering a problem while trying to scrape using cheeriojs

While attempting to scrape article links from a website, I encountered an issue where only one link was successfully scraped and the other elements were not being looped over. My current setup involves using nodejs in conjunction with the cheerio and req ...

Accessing PHP variables in JavaScript

Hi there, I am new to all this. I am trying to figure out how to use a PHP variable in JavaScript. Here is a snippet of my code (popup.php): <?php $id_user = $this->session->userdata('id'); ?> <script type="text/javascript"> ...

Revamping Slideshows: Bringing CSS Animation to JavaScript

/* JavaScript */ var slides=0; var array=new Array('background.jpg','banner.jpg','image.jpg'); var length=array.length-1; $(document).ready( function(){ setInterval(function(){ slides++; ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Updating classes when useState changes in React JS

I'm currently working on implementing a carousel slider in React. As I track the state to determine the specific class to add based on the state value (e.g., adding "-left-1/3" when the state is 2), everything seems to be functioning correctly. Howeve ...

Click the edit button to access the options in the material table

https://i.stack.imgur.com/Inyow.png Currently, I am utilizing Material Table within Reactjs to display the table Data. However, I have encountered a hurdle where I need to alter state upon clicking on the edit option/icon. My objective is not to modify th ...

Showing perspectives that include 'partial'/'nested' components in EXTjs 4

I am struggling to comprehend how I should define and implement the MVC model for my test application in EXTjs4. Let's take a look at the structure below. app.js Ext.application({ name: 'AM', appFolder: 'app', control ...

How can I prevent v-model from filling multiple fields?

Having just started with Vue.js, I've managed to solve most of the issues I've encountered so far, but there's one that's stumping me. I'm working on displaying a list of posts fetched from an API and I want to include a comments ...