How can function expressions result in a returned value?

Function expressions result in a value, unlike function declarations which do not. This distinction was clarified for me by others in a different SO thread (link provided). All functions default to returning undefined, hence the emphasis on "expression" in function expressions. My confusion lies in what exactly causes this difference. My initial assumption was that it is due to variable assignment, as anything to the right of the assignment operator is considered an expression. However, function expressions do not require variable assignment. As far as I know, the only other disparity between function expressions and function declarations is the ability to omit the function name in a function expression. Any further explanations would be greatly appreciated.

Answer №1

For more information, visit: https://javascript.info/function-expressions-arrows#function-expression-vs-function-declaration

Function Expressions are created when they are reached during execution and can be used thereafter.

Once the execution passes to the right side of the assignment like let sum = function..., the function is created and available for use (assigned, called, etc) from that point on.

On the other hand, Function Declarations behave differently.

A Function Declaration is accessible throughout the whole script or code block.

In essence, before executing a script or a code block in JavaScript, it searches for Function Declarations within it and generates the functions. This can be thought of as an "initialization stage."

After all Function Declarations are processed, the execution continues.

Due to this, a function declared as a Function Declaration can be invoked before it is defined.

sayHi("John"); // Hello, John

function sayHi(name) {
  alert( `Hello, ${name}` );
}

The Function Declaration sayHi is created while preparing to run the script in JavaScript and remains visible throughout it.

If it were a Function Expression, it wouldn't work:

sayHi("John"); // error!

let sayHi = function(name) {  // (*) no magic any more
  alert( `Hello, ${name}` );
};

Function Expressions are generated when they are reached during execution. This occurs only at line (*), which is too late.

When a Function Declaration is inside a code block, it is visible throughout that block but not outside of it.

Sometimes it's beneficial to declare a local function required solely in that block. However, this feature may lead to issues.

Consider a scenario where we need to define a function welcome() based on the age variable received during runtime and then use it later.

let age = prompt("What is your age?", 18);

// conditionally declare a function
if (age < 18) {

  function welcome() {
    alert("Hello!");
  }

} else {

  function welcome() {
    alert("Greetings!");
  }

}

// ...use it later
welcome(); // Error: welcome is not defined

This is because a Function Declaration is only visible within the code block it resides in.

Here's another example:

let age = 16;

if (age < 18) {
  welcome();
  
  function welcome() {
    alert("Hello!");
  }
  
  welcome();

} else {

  function welcome() {
    alert("Greetings!");
  }
}

// Function Declarations made inside curly braces are not visible outside.

welcome(); // Error: welcome is not defined

To make welcome visible outside of if, you should use a Function Expression and assign welcome to a variable declared outside with proper visibility.

Now it works correctly:

let age = prompt("What is your age?", 18);

let welcome;

if (age < 18) {

  welcome = function() {
    alert("Hello!");
  };

} else {

  welcome = function() {
    alert("Greetings!");
  };

}

welcome(); // now working as intended

Alternatively, you can simplify it using the ternary operator ?:

let age = prompt("What is your age?", 18);

let welcome = (age < 18) ?
  function() { alert("Hello!"); } :
  function() { alert("Greetings!"); };

welcome(); // now working as intended

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

Incorporate personalized design elements within the popup component of Material-UI's DataGrid Toolbar

I am in the process of customizing a Data Grid Toolbar component by making adjustments to the existing Grid Toolbar components sourced from Material-UI. For reference, you can view the official example of the Grid Toolbar components here. Upon clicking o ...

Multiple components are returned with switch case

I am trying to iterate over an object and display a result based on Object.entries. However, the loop currently stops at the first return statement. Is there a way for me to capture and display all components returned simultaneously, perhaps using a vari ...

Caution: The server is expected to have a matching navigation within the div tag

I am currently working with next.js framework and encountering the following error message: "Warning: Expected server HTML to contain a matching nav in div". Below is a snippet of my code: export default function Member() { const router = useRouter(); ...

Steps for adding a JSON object to an unordered list

After receiving data from a web server, I created a JSON object using the code obj = JSON.parse(data). This object contains information about dinosaurs such as their name, group, diet, and period. This is what the JSON object looks like: [{"name":"Stauri ...

Issue encountered with SQL server 2008 due to connection error

My current struggle lies in the connection I am attempting to establish with SQL Server. Unfortunately, whenever I try pressing the period key or entering the server name, I encounter difficulty connecting to SQL Server. ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

The error "Cannot access property of undefined during an Ajax POST request" indicates

I am currently facing an issue with uploading a music file using AJAX to save the data into my MongoDB when I click the 'upload' button. Unfortunately, I keep receiving an error stating that "fieldname is undefined". It seems like there might be ...

Completing the pledge using ionic/ui-routing

I've encountered an issue with my promise not resolving as expected while using Ionic/ui-routing. This is the structure of my service: return { all: function () { $localForage.getItem('foo').then(function (bar) { re ...

Ways to modify the color of a container's border by interacting with radio buttons through JavaScript

I'm currently facing a challenge with creating a settings dropdown menu that allows users to select different themes. Each theme is supposed to modify the background color and border color, but I have successfully implemented only the background color ...

Code needed to efficiently include a d3 module through webpack

Having some trouble importing and using a d3 module in my webpack project. The function I need from the module is declared like so: https://github.com/d3/d3-plugins/blob/master/hive/hive.js d3.hive.link = function() { I attempted to follow this guide to ...

Arrange two divs with a full width of 100% next to each other

Is there a way to create two divs, each taking up 100% of the page width and side by side within a wrapper with overflow:hidden? How can I achieve this? I attempted using inline-block, but it didn't produce the desired outcome. Similarly, when I tri ...

What is the best way to add data to a URL in an ActionResult Method using window.location.href?

I am having trouble understanding how to retrieve data using window.location.href = '/Product/Success/'+data.OrderTrackNo+'';. I am able to get data using ajax, but it seems different when retrieving data with window.location.href, whic ...

Launching the forEach function within an ng-repeat loop was it can be done by

I need to implement a function within the ng-repeat that will convert the value of Qprogress object in my JSON into a percentage. I already have the function written, but I am struggling with how to trigger it. I attempted to use a forEach loop inside the ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

Check the schedule for any upcoming events

I am currently designing a website for a friend and I have a question regarding the functionality of the FullCalendar jQuery plugin. Is there a way to determine if there is an event scheduled for today using FullCalendar? If so, I would like to display t ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Is there a way to retrieve cookie data from a component that has been rendered in _app.js using Next.js?

Within my next.js application, I have implemented a functionality where a hashed token from an OAuth2 provider is stored using cookies. Once the user completes the necessary steps, they are logged in and the cookie storing the token is set. The log in but ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

Customized webpage content using AJAX for interactive map selections

I have integrated JQVMaps into a WordPress website to display a dynamic world map. The goal is to update the content of the page based on the region that the user clicks. Below is a snippet of the code I have implemented as a proof of concept: <div ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...