DEV Community

Jasmin Song
Jasmin Song

Posted on • Edited on

Functions

Functions allow us to wrap and reuse parts of our code. Allows us to control the flow of execution. We get to control when, where, and why our code runs.

A function is an object that contains a sequence of JavaScript statements. We can execute or call it multiple times.

call, invoke, or execute functions means to run the pieces that make it.

using function declaration using the function keyword:

  • Need 2 main pieces: () and {}

  • can invoke function before and after it's been defined.

using a variable with function expression:

  • can only be called after the function declaration.

  • return ends our function

  • not hoisted

if we don't specify the return value, end up getting undefined. if we do specify the return value, we get that value.

() is the invocation operator. It invokes the function.

the function call can actually come before the function declaration in the code file, due to hoisting. But it needs to exist somewhere; if you try to call a function that hasn't been declared somewhere in the code, you'll get an error.

Hoisting

JavaScript's ability to call functions before they appear in the code is called hoisting. For hoisting to work, the function must be defined using a function declaration.

Arrow Functions

Created with an arrow and using an assignment operator
cannot be hoisted

when there are no braces, arrow functions have an implicit return, i.e., they automatically return the result of the last expression! This is the only situation in which a JavaScript function doesn't require explicit return with the return keyword.

Callback Functions

  • when functions are passed as an argument to a function functions are objects
  • is not invoked immediately

Anonymous Functions

  • functions functions without an identifier or a name

Top comments (0)