Javascript functions

From wikinotes
Revision as of 23:21, 14 June 2021 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Functions

function say_hello() {
    console.log("hello")
    return true
}
say_hello()

See Also javascript arguments

Return Values

javascript functions cannot return more than one variable.

Anonymous Functions

Functions do not need to be named.

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

Lambda Functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Also referred to as arrow function expressions.

(a, b) => a + b + 100     // lambda expression w/ args
() => console.log('hi')   // lambda expression w/o args

Closures

Javascript supports functions defined inside functions.

function foo() {
    function bar() {
        console.log('baz')
    }
    bar()
}

Binding this

bind() lets you change the value of this within a method.

B = { x: 2 }

class A {
  x = 1
  constructor() { this.printb = this.printx.bind(B) }  // this.printb uses value of 'x' from 'B'
  printx() { console.log(this.x); }                    // this.printx uses value of 'x' from 'A'
}

const a = new A().printx()
a.printx()
a.printb()