JS Functions

Built-in Functions

The JavaScript language has many built-in functions. In fact, some of the code you are calling when you invoke a built-in browser function couldn't be written in JavaScript — many of these functions are calling parts of the background browser code, which is written largely in low-level system languages like C++, not web languages like JavaScript.

And some built-in browser functions are not part of the core JavaScript language — some are defined as part of browser APIs, which build on top of the default language to provide even more functionality.

Definition

Use function JS Keyword to define a function

function myFunction(arg1, arg2) {
    doSomeOperations;
    let result = expression;
    return result;
}

Return

Invoking

Unlike Python, where functions must be defined before any invoking; and unlike MATLAB, where functions must be listed at the end of the script; JS allows to define the functions anywhere and invoke them anywhere.

Default values

If a function is called, but an argument is not provided, then the corresponding value becomes JS Types - undefined. However, we can provide its default value in the function definition

function myFun(para1, para2 = "no text given") {
  console.log(para1 + para2);
}

myFun("Notice: "); // 'Notice: no text given'

Now if the para2 parameter is not passed, it will get the value 'no text given'. The default value can even be another function call.

#R If the default value is an expression or function, it will and only will be evaluated when the function is called and the respective parameter is not passed.

Alternative Default Parameters

Sometimes it makes sense to assign default values for parameters not in the function declaration, but at a later stage. In these cases we can check if the parameter is passed during the function execution, by comparing it with undefined

function showMessage(text) {
    // ...

    if (text === undefined) { // if the parameter is missing
    text = 'empty message';
  }

  alert(text);
}

showMessage(); // empty message

Or we could use the Or we could use the||and??logical operators Or we could use the

function showMessage(text) {
  // if text is undefined or otherwise falsy, set it to 'empty'
  text = text || 'empty';
  //...
}
function showCount(count) {
  // if count is undefined or null, show "unknown"
  alert(count ?? "unknown");
}

showCount(0); // 0
showCount(null); // unknown
showCount(); // unknown

Arguments

Within every function, there is an JS Type - Array-like JS Types - Object called arguments that contains the values of the arguments passed to that function.

Anonymous Function

When we don't need to store a function in a name, we can define an anonymous function

function() {
    // Do something
}

You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked:

const myButton = document.querySelector('button');

myButton.onclick = function() {
  alert('hello');
}

With event handler, anonymous function is like a when statement: it executes some code when an event is triggered.

Function Expression

Just like any other type, an anonymous function can be assigned to a JS Variable. Such form of creating a function is also known as function expression.

/* Define */
let varFun = function() {
    // Do somethinf
};

/* Invoke */
varFun();
Callback Functions

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

function showOk() {
  alert( "You agreed." );
}

function showCancel() {
  alert( "You canceled the execution." );
}

// usage: functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);

The arguments showOk and showCancel of ask are called callback functions or just callbacks.

The idea is that we pass a function and expect it to be "called back" later if necessary. In our case, showOk becomes the callback for “yes” answer, and showCancel for “no” answer.

We can use Function Expressions to write the same function much shorter:

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

ask(
  "Do you agree?",
  function() { alert("You agreed."); },
  function() { alert("You canceled the execution."); }
);
A Function is a Value Representing an "Action"

Regular values like strings or numbers represent the data. A function can be perceived as an action. We can pass it between variables and run when we want.

Arrow Function

$

n-h1

JS Array Function

Another way to create a function and assign it to a variable (this process is called #Function Expression) is called arrow function, which is similar to Python Lambda Function

let myFun = (para1, para2) => expression

This creates a function myFun that accepts arguments para1 and para2, then evaluates the expression on the right side with their use and returns its result.

In other words, it’s the shorter version of the #Function Expression:

let myFun = function(para1, para2) {
  return expression;
};
  • If we have only one parameter, then parentheses around parameters can be omitted
    • This gives the simplest form of a function: para => expression
  • If there are no parameters, parentheses will be empty (but they should be present)
  • For more complex expressions, like multiple expressions or statements, we should enclose them in curly braces {}, then use a normal return within them
Dynamically Create a Function

let age = prompt("What is your age?", 18);

let welcome = (age < 18) ?
  () => alert('Hello') :
  () => alert("Greetings!");

welcome();

Function Scope

Creative Commons License by zcysxy