Computer Science

Javascript Function Expressions

Javascript Function Expressions are a way to define a function as a variable and assign it to a value. This allows for more flexibility in how functions are used and can be particularly useful in situations where a function needs to be passed as an argument to another function. Function expressions can also be used to create anonymous functions.

Written by Perlego with AI-assistance

5 Key excerpts on "Javascript Function Expressions"

  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    If you were checking whether an e-mail address were in a valid format before subscribing that e-mail address to a newsletter, the return value would determine whether the form was submitted. Function Expressions and Anonymous Functions As you’ve seen, there are a couple different ways to define functions in JavaScript. Technically, the format you first learned with the calculateArea() function is called a function declaration. This is the standard way to define reusable blocks of JavaScript statements. Because you give the function an identifier , you can refer to it throughout the life of your application. This is a good thing. Creating reusable code is something you should strive for. This format also uses the function keyword. This is a standard function declaration for a function named name(). function name(){ /*Code*/} Function declarations can’t be nested within other blocks of JavaScript, which means if all you had available to you was a function declaration you would have to define all of your functions in that way before you could use them. Sometimes, as you’ve already seen, that doesn’t need to be the case. If you define a function that will be used as an event handler (the code to be run when an event happens) it can be easier to define the function in place without using an identifier. Doing so uses the second form you’ve seen, the function expression. A function expression is a func- tion that can be defined more flexibly, as part of a larger piece of JavaScript. For example, you can use a function expression as the value of a variable or as an argument to another function. Commonly Conditional Statements ❘ 357 function expressions used in this way will be defined without using an identifier. Because it doesn’t have an identifier, this is an anonymous function. A function created in this way works in the same way as a function created with a function declaration.
  • Book cover image for: JavaScript: Novice to Ninja
    • Darren Jones(Author)
    • 2017(Publication Date)
    • SitePoint
      (Publisher)

    Chapter 4: Functions

    A function is a chunk of code that can be referenced by a name, and is almost like a small, self-contained mini program. Functions can help reduce repetition and make code easier to follow. In this chapter, we’ll be covering these topics:
    • Defining functions―function declarations, function expressions, Function() constructors and the new arrow syntax
    • Invoking a function
    • Return values
    • Parameters and arguments
    • Hoisting―variables and functions
    • Callbacks―functions as a parameter
    • Project ― we’ll be using functions to make the Quiz Ninja code easier to follow
    In JavaScript, functions are considered to be first-class objects. This means they behave in the same way as all the other primitive data types and objects in the language. They can be be assigned to variables, stored in arrays and can even be returned by another functions.
    This makes functions a very important and powerful part of the JavaScript language with many of its features relying on them. Fully understanding functions is an essential skill of the JavaScript ninja.

    Defining a Function

    There are a number of ways to define a function in JavaScript. Three of the most common are covered below. ES6 introduced a new way to define functions, using what is known as 'arrow' notation. This is covered later in the chapter.

    Function Declarations

    To define a function literal we can use a function declaration:
    function hello(){ console.log('Hello World!'); }
    This starts with the function keyword and is followed by the name of the function, which in this case is called 'hello ', followed by parentheses. Following this is a block that contains the code for the function.
    This is known as a named function as the function has a name: 'hello '.

    Function Expressions

    Another way of defining a function literal is to create a function expression. This assigns an anonymous function
  • Book cover image for: Start Programming Using HTML, CSS, and JavaScript
    At the end of a function expression there is a function body , which comprises any number of JavaScript statements within curly brackets. Note that, unlike statement blocks of while and other statements, the function body requires curly brackets. They cannot be omitted even when the function body is composed of only a single statement. Because a function is an object in JavaScript, a function expression in fact returns a function object, a reference to which you usually assign to a variable. In the above definition, the returned reference is assigned to a variable fun_name . Later, you can use fun_name to call, or invoke the function, which will e ff ectively execute the code placed in its body. Notice a semicolon at the end of the function expression, which is needed to make a statement out of the expression. Maria : Can you give us a simple example? Professor : All right, here’s a really simple one, without any parameters for starters: var cheer = function() { var i; for (i = 0; i < 2; i++) { document.write(Hip ); } document.write(Hooray!); }; You invoke this function by referring to the variable cheer using an additional pair of parentheses. Like this: cheer(); //Writes Hip Hip Hooray! When you call a function, the main program execution sequence is temporarily sus-pended and the code within the function body starts to execute. After the function has terminated, the execution returns to the main program. The following diagram shows what happens when cheer() is invoked. cheer(); Main Program Function document.write(Hip ); document.write(Hooray!); for (i = 0; i < 2; i++) { } var i; Alternatively, you can define a function using a function definition statement : 10.2. Writing Function Definitions 189
  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    event handler (the code to be run when an event happens) it can be easier to define the function in place without using an identifier.
    Doing so uses the second form you’ve seen, the function expression . A function expression is a function that can be defined more flexibly, as part of a larger piece of JavaScript. For example, you can use a function expression as the value of a variable or as an argument to another function. Commonly function expressions used in this way will be defined without using an identifier. Because it doesn’t have an identifier, this is an anonymous function . A function created in this way works in the same way as a function created with a function declaration. It’s still a collection of JavaScript statements. It differs in that it can be created in place. This code shows an example of an anonymous function assigned to a variable anon :
    var anon = function(){/*code*/}
    This example shows an anonymous function used as an argument to another function, name() :
    name( function(){ return " Rob Larsen " ; });
    It may not make complete sense now, but as you continue to program JavaScript, your ability to create anonymous functions will become more apparent.

    Conditional Statements

    Conditional statements enable you to take different actions depending upon different statements. You will learn about three types of conditional statements:
    • if statements, which are used when you want the script to execute if a condition is true
    • if...else
  • Book cover image for: Pro Angular
    eBook - PDF
    • Adam Freeman(Author)
    • 2017(Publication Date)
    • Apress
      (Publisher)
    The approach I used in Listing 5-8 is known as a function expression . The same function can also be defined like this: ... function myFunc() { console.log(This is a statement); } ... This is known as a function declaration . The result is the same: a function called myFunc that writes a message to the console. The difference is how the functions are processed by the browser when a JavaScript file is loaded. Function declarations are processed before the code in a JavaScript file is executed, which means you can use a statement that calls a function before it is defined, like this: ... myFunc(); function myFunc() { console.log(This is a statement); } ... This works because the browser finds the function declaration when it parses the JavaScript file and sets up the function before the remaining statements are executed, a process known as function hoisting . Function expressions, however, are not subject to hoisting, which means that this code will not work: ... myFunc(); let myFunc = function() { console.log(This is a statement); }; ... CHAPTER 5 ■ JAVASCRIPT AND TYPESCRIPT: PART 1 72 This code will generate an error reporting that myFunc is not a function. Developers who are new to JavaScript tend to prefer using function declarations because the syntax is more consistent with languages like C# or Java. The technique you use is entirely up to you, although you should aim to be consistent throughout your project to make your code easier to understand. Defining Functions with Parameters JavaScript allows you to define parameters for functions, as shown in Listing 5-9 . Listing 5-9. Defining Functions with Parameters in the primer.ts File let myFunc = function(name, weather) { console.log(Hello + name + .); console.log(It is + weather + today); }; myFunc(Adam, sunny); I added two parameters to the myFunc function, called name and weather .
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.