Functions explained - Gosiaisean/arch GitHub Wiki

Function in JS

  • Every function in JavaScript is a **Function **object.
  • To return a value other than the default, a function must have a **return **statement. A function without a return statement will return a default value.
  • The parameters of a function call are the function's arguments. Arguments are passed to functions by value.

Function expression

const getRectArea = function(width, height) { return width * height; };}

  • function name, which can be omitted in function expressions to create anonymous functions
  • Function expressions in JavaScript are not hoisted,
  • If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope)
  • The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name)

arrow function expression

  • Does not have its own bindings to this or super, and should not be used as methods.
  • Does not have arguments, or new.target keywords.
  • Not suitable for call, apply and bind methods, which generally rely on establishing a scope. *Can not be used as constructors.
  • Can not use yield, within its body.

function declaration

function calcRectArea(width, height) { return width * height; }

Generator function

It is a function that can be stoped in the middle and after some event it can go back and pickup from the place it stopped.

Convert regular to arrow:

Traditional Function function (a){ return a + 100; }

Arrow Function Break Down

  1. Remove the word "function" and place arrow between the argument and opening body bracket (a) => { return a + 100; }

  2. Remove the body brackets and word "return" -- the return is implied. (a) => a + 100;

  3. Remove the argument parentheses a => a + 100;

Questions

  1. dfference between function expression and decalrartion:
  • name - Function expresion doesnt need name (it will be anonymous function)
  • hoisting - F.expr are not hoisted unlike F.declar.
  1. what is anonymuous function.
  2. Difference between method and function.
  • Function can be called by its name, method is property of object:

Function

function functionName(parameters) { // Content }

Method


object = { methodName: function() { // Content } };object.methodName()

  1. When to use each function
⚠️ **GitHub.com Fallback** ⚠️