The Wayback Machine - https://web.archive.org/web/20241001070125/https://www.geeksforgeeks.org/javascript-function-expression/
Open In App

JavaScript Function Expression

Last Updated : 22 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Javascript Function Expression is used to define a function inside any expression. The Function Expression allows us to create an anonymous function that doesn’t have any function name which is the main difference between Function Expression and Function Declaration. A function expression can be used as an IIFE (Immediately Invoked Function Expression)which runs as soon as it is defined. A function expression has to be stored in a variable and can be accessed using variableName.  With the ES6 features introducing Arrow Function, it becomes more easier to declare function expression.

Syntax for Function Declaration:

function functionName(x, y) { statements... return (z) };

Syntax for Function Expression (anonymous):

let variableName = function(x, y) { statements... return (z) };

Syntax for Function Expression (named): 

let variableName = function functionName(x, y) 
{ statements... return (z) };

Syntax for Arrow Function: 

let variableName = (x, y) => { statements... return (z) }; 

Note: 

  • A function expression has to be defined first before calling it or using it as a parameter.
  • An arrow function must have a return statement.

The below examples illustrate the function expression in JavaScript:

Example 1: Code for Function Declaration.

Javascript




function callAdd(x, y) {
    let z = x + y;
    return z;
}
console.log("Addition : " + callAdd(7, 4));


Output: 

Addition : 11

Example 2: Code for Function Expression (anonymous

Javascript




let calSub = function (x, y) {
    let z = x - y;
    return z;
}
 
console.log("Subtraction : " + calSub(7, 4));


Output: 

Subtraction : 3

Example 3: Code for Function Expression (named

Javascript




let calMul = function Mul(x, y) {
    let z = x * y;
    return z;
}
 
console.log("Multiplication : " + calMul(7, 4));


Output:

Multiplication : 28

Example 4: Code for Arrow Function 

Javascript




let calDiv = (x, y) => {
    let z = x / y;
    return z;
}
 
console.log("Division : " + calDiv(24, 4));


Output: 

Division : 6

We have a complete list of Javascript Functions, to check those please go through the Javascript Function Complete Reference article.

Supported Browser:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 3 and above
  • Opera 3 and above
  • Safari 1 and above


Previous Article
Next Article

Similar Reads

Difference between AngularJS Expression and Angular Expression
AngularJS is a JavaScript-based framework that can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. Angular on the other hand is a client-side TypeScript-based, front-end web framework by Google. Angular is
3 min read
Difference between ‘function declaration’ and ‘function expression' in JavaScript
Functions in JavaScript allow us to carry out some set of actions, important decisions, or calculations and even make our website more interactive. In this article, we will learn the difference between ‘function declaration’ and ‘function expression’. The similarity is both use the keyword function and the most prominent difference is that the func
2 min read
Difference between function expression vs declaration in JavaScript
Function Declaration: A Function Declaration( or a Function Statement) defines a function with the specified parameters without requiring a variable assignment. They exist on their own, i.e, they are standalone constructs and cannot be nested within a non-function block. A function is declared using the function keyword. Syntax:function gfg(paramet
1 min read
JavaScript function* expression
The function* is an inbuilt keyword in JavaScript which is used to define a generator function inside an expression. Syntax: function* [name]([param1[, param2[, ..., paramN]]]) { statements}Parameters: This function accepts the following parameter as mentioned above and described below: name: This parameter is the function name.paramN: This paramet
2 min read
How to prevent overriding using Immediately Invoked Function Expression in JavaScript ?
Overriding is basically when you define multiple functions or variables that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed. Overriding usually happens when you have multiple javascript files in your page. It can be an external
2 min read
JavaScript async function expression
An async function expression is used to define an async function inside an expression in JavaScript. The async function is declared using the async keyword or the arrow syntax. Syntax: async function function_name (param1, param2, ..., paramN) { // Statements}Parameters: function_name: This parameter holds the function name. This function name is l
2 min read
How to clone a given regular expression in JavaScript ?
In this article, we will know How to clone a regular expression using JavaScript. We can clone a given regular expression using the constructor RegExp(). The syntax of using this constructor has been defined as follows:- Syntax: new RegExp(regExp , flags) Here regExp is the expression to be cloned and flags determine the flags of the clone. There a
2 min read
JavaScript RegExp (x|y) Expression
The RegExp (x|y) Expression in JavaScript is used to search any of the specified characters (separated by |). Syntax: /(x|y)/ or new RegExp("(x|y)") Syntax with modifiers: /(x|y)/g or new RegExp("(x|y)", "g") Example 1: This example searches the word "GEEKS" or "portal" in the whole string. C/C++ Code function geek() { let str1 = "GEEKSFORGEEK
2 min read
How to return all matching strings against a regular expression in JavaScript ?
In this article, we will learn how to identify if a string matches with a regular expression and subsequently return all the matching strings in JavaScript. We can use the JavaScript string.search() method to search for a match between a regular expression in a given string. Syntax: let index = string.search( expression )Parameters: This method acc
3 min read
JavaScript RegExp [abc] Expression
The RegExp [abc] Expression in JavaScript is used to search any character between the brackets. The character inside the brackets can be a single character or a span of characters. [A-Z]: It is used to match any character from uppercase A to Z.[a-z]: It is used to match any character from lowercase a to z.[A-z]: It is used to match any character fr
2 min read
JavaScript RegExp [^abc] Expression
The RegExp [^abc] Expression in JavaScript is used to search for any character which is not between the brackets. The character inside the brackets can be a single character or a span of characters. [A-Z]: It is used to match any character from uppercase A to uppercase Z.[a-z]: It is used to match any character from lowercase a to lowercase z.[A-z]
2 min read
JavaScript RegExp [0-9] Expression
The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits. Syntax: /[0-9]/ or new RegExp("[0-9]") Syntax with modifiers: /[0-9]/g or new RegExp("[0-9]", "g") Example 1: This example searches the digits between [0-4] in the whole st
2 min read
JavaScript RegExp [^0-9] Expression
The RegExp [^0-9] Expression in JavaScript is used to search any digit which is not between the brackets. The character inside the brackets can be a single digit or a span of digits. Syntax: /[^0-9]/ or new RegExp("[^0-9]") Syntax with modifiers: /[^0-9]/g or new RegExp("[^0-9]", "g") Example 1: This example searches the digits which are not presen
2 min read
How to check for IP address using regular expression in javascript?
The task is to validate the IP address of both IPv4 as well as IPv6. Here we are going to use RegExp to solve the problem. Approach 1: RegExp: Which split the IP address on. (dot) and check for each element whether they are valid or not(0-255). Example 1: This example uses the approach discussed above. C/C++ Code <h1 style="color:green;
1 min read
How to detect whether a device is iOS without using Regular Expression in JavaScript?
The task is to detect whether the device is iOS or not without using RegExp with the help of JavaScript. There are two approaches that are discussed below. Approach 1: Use navigator.platform property to check for the particular keywords which belongs to iOS devices using indexOf() method. Example: <!DOCTYPE html> <html> <head>
2 min read
Convert user input string into regular expression using JavaScript
In this article, we will convert the user input string into a regular expression using JavaScript.To convert user input into a regular expression in JavaScript, you can use the RegExp constructor. The RegExp constructor takes a string as its argument and converts it into a regular expression object Regular expressions (RegExp) are patterns used to
2 min read
JavaScript yield* Expression
The yield* expression in JavaScript is used when one wants to delegate some other iterable object. This function iterates over the particular operand and yields each value that is returned by it. Syntax: yield* expression; Return Value: It returns the iterable object. Example 1: In this example, we will see the basic use of the Javascript yield* ex
2 min read
Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
Given an expression string exp, write a program to examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in exp. Example:  Input: exp = "[()]{}{[()()]()}" Output: Balanced Input: exp = "[(])" Output: Not Balanced  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
How to use a Variable in Regular Expression in JavaScript ?
Regexps can be used in JavaScript to build dynamic patterns that match various strings depending on the value of the variable. In this article, we will see how to utilize the variable with the regular expression. In this article, we will see, how to use a Variable in Regular Expression in JavaScript Below are the approaches on How to use a Variable
2 min read
How to build a Math Expression Tokenizer using JavaScript ?
A math expression tokenizer is a fundamental component in parsing mathematical expressions. It breaks down a mathematical expression into smaller units called tokens, which are easier to process and evaluate. In JavaScript, building a math expression tokenizer can be achieved through various approaches, each with its advantages and considerations.
2 min read
JavaScript program to Check the Expression has valid or Balanced Parenthesis or Not
Given the expression string, Our task is to Check whether the expression has valid or Balanced parenthesis or not in JavaScript. Valid input refers to every bracket having its corresponding bracket of the same type in the correct order. Example: Input: exp = "[()][()()]()" Output: True.Explanation: All of the brackets are balanced.Input: exp = "[(]
3 min read
How to validate URL using regular expression in JavaScript?
Validating URLs using regular expressions in JavaScript involves crafting patterns to match URL formats, ensuring they adhere to standards like scheme, domain, and optional path or query parameters. This regex pattern verifies the structure and components of a URL string for validity. Examples to validate URLs using regular expression in JavaScript
2 min read
JavaScript RegExp(Regular Expression)
A regular expression is a character sequence defining a search pattern. It's employed in text searches and replacements, describing what to search for within a text. Ranging from single characters to complex patterns, regular expressions enable various text operations with versatility and precision. A regular expression can be a single character or
4 min read
JavaScript Class Expression
JavaScript class is a type of function declared with a class keyword, that is used to implement an object-oriented paradigm. Constructors are used to initialize the attributes of a class. There are 2 ways to create a class in JavaScript. class declarationclass expressionIn this article, we'll discuss class expression to declare classes in JavaScrip
1 min read
How to Access Matched Groups in a JavaScript Regular Expression ?
Accessing matched groups in a JavaScript regular expression allows you to extract specific parts of a string based on patterns defined within parentheses in the regex pattern. This capability enables precise extraction and manipulation of text data, enhancing the versatility of regular expressions in string processing tasks. In this article, we wil
2 min read
How to validate form using Regular Expression in JavaScript ?
JavaScript is a scripting programming language that also helps in validating the user's information. Have you ever heard about validating forms? Here comes into the picture JavaScript, the Scripting language that is used for validations and verification. To get deeper into this topic let us understand with examples. Example 1: Form validation (vali
4 min read
How to Validate Email Address without using Regular Expression in JavaScript ?
Email validation in JavaScript is the process of ensuring that an email address entered by the user is in the correct format and is a valid email address or not. This is typically done on the client side using JavaScript before the form is submitted to the server. An email address must have the following components to be considered valid:Username:
5 min read
JavaScript SyntaxError - Invalid regular expression flag "x"
This JavaScript exception invalid regular expression flag occurs if the flags, written after the second slash in RegExp literal, are not from either of (g, i, m, s, u, or y). Error Message on console: SyntaxError: Syntax error in regular expression (Edge) SyntaxError: invalid regular expression flag "x" (Firefox)SyntaxError: Invalid regular express
1 min read
Named Function Expression
In JavaScript or in any programming language, functions, loops, mathematical operators, and variables are the most widely used tools. This article is about how we can use and what are the real conditions when the Named function Expressions. We will discuss all the required concepts in this article to know the named function Expression in and out. N
3 min read
Expected an assignment or function call and instead saw an expression in ReactJS
In React.js we create components, inside these components, there are functions that we export and then use inside another component by importing it. Sometimes when you try to render that component or use that component as a tag inside another component, It throws an error "React: Expected an assignment or function call and instead saw an expression
3 min read