Bundle up work into functions

INPUT · Slides

Putting a function in a variable

01 / 04

A function is also a value

The function you defined last lesson is in fact a value. It can be handled like a number or a string.

Try handing it to console.log without the () and back comes "this is a function". With () the inside runs; without, it means the function itself.

function hello() {  console.log("hey");}console.log(hello);hello();

Result

function
hey

02 / 04

The way of writing that puts it in a variable

A value can go in a variable. Writing const name = function() { work }; is called a function expression.

The point is that you do not write a name after function — the variable holds the name. And since it is a statement that puts a value somewhere, do not forget the ; after the final }.

const greet = function() {  console.log("good morning");};greet();

Result

good morning

03 / 04

You call it the same way

To call it you just write greet(). Exactly as with last lesson's way of writing it (a function declaration).

The difference is that you cannot call it before its definition. A function expression is a statement that puts a value in a variable, so until you pass that line there is nothing in it.

Write it top to bottom as "define, then call" and you will not get lost.

const cheer = function() {  console.log("go on");};cheer();cheer();

Result

go on
go on

04 / 04

Which should you use

For now, take it that either works. The difference is about this much.

  • a function declarationfunction name() { }. Plain and easy to read
  • a function expressionconst name = function() { };. Makes it plain that a function is a value

Get used to the function expression form and the shorter writing coming next slides right in. Start by rewriting a few until your hands know it.