How to write a function expression in JavaScript

Function expressions assign functions to variables, providing flexibility in function creation and enabling conditional function definition. As the creator of CoreUI, a widely used open-source UI library, I’ve used function expressions extensively for dynamic function creation and modular code organization. From my expertise, function expressions are ideal when you need to conditionally create functions or pass them as arguments. This approach offers more control over function scope and timing compared to function declarations.

Assign an anonymous function to a variable to create a function expression.

const greet = function(name) {
  return `Hello, ${name}!`
}

Here the function keyword creates an anonymous function that gets assigned to the variable greet. Unlike function declarations, function expressions are not hoisted, meaning they can only be called after they’re defined. This gives you precise control over when functions become available in your code scope.

Best Practice Note:

Function expressions are not hoisted like function declarations, so they must be defined before use. This is the same pattern we use in CoreUI for conditional function creation and maintaining predictable execution order.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Manage Date and Time in Specific Timezones Using JavaScript
How to Manage Date and Time in Specific Timezones Using JavaScript

How to Hide Scrollbar with CSS
How to Hide Scrollbar with CSS

How to Center a Button in CSS
How to Center a Button in CSS

How to Use Bootstrap Modal in Vue 3 – Clean Integration with CoreUI
How to Use Bootstrap Modal in Vue 3 – Clean Integration with CoreUI

Answers by CoreUI Core Team