JavaScript Function

Many programming languages just run function to perform actions, but JavaScript can assign the function to a variable or even an object property which them become a method.

1. Function can be assign to variables and properties of the object

const a = function () {
    return null;
}

const obj = {
    a: function () {
        return null;
    }
}

2. You can pass functions as arguments into a function

function a(func){
    func()
}

a(function(){return console.log("a function as arguments")})
a function as arguments

3. You can return functions.

function a() {
    return function b(num){
        console.log(num);
    }
}

const fn = a();
fn(2)
2

More information for Initializing functions and variables inside a function.

  • Be careful of initializing functions
for (let i = 0; i < 5; i++) {
    function a() {
        return console.log("a")
    }
    a()
}

Initializing function five times

function a() { return console.log("a") }
for (let i = 0; i < 5; i++) {
    a()
}

Initializing function one time

  • Variables inside a function.
function a(){
    return x;
}

a();
ReferenceError: x is not defined

Prevent referenceError

function a() {
    if (x) {
        return x;
    }
}

a();
  • By if statement
function a(x = 3) {
    return x;
}

a();
  • With ES6 default parameter

Leave a Reply

Your email address will not be published.

ANOTE.DEV