Does a Javascript function have to be defined before calling it?

前端 未结 4 962
时光取名叫无心
时光取名叫无心 2020-12-14 16:53

If I run the function below before defining it, I will get this error...

Uncaught ReferenceError: openModal is not defined

run then def

4条回答
  •  自闭症患者
    2020-12-14 17:04

    I would say, YES. A function always must be defined before calling. But some functions can be Invoked(called) before where they have been defined (HOISTING)

    Two different types of functions that I want to write about are :

    Expression Functions & Deceleration Functions

    1- Expression Functions: A function expression can be stored in a variable so they do not need function names.They will also named as an anonymous function (a function without a name). To invoke (called) they are always need using a variable name.These kind of functions won't work if calls before where it has been defined which means Hoisting is not happening here. We always must define the expression function first and then invoke it.

    let lastName = function (family) {
     console.log("My last name is " + family);
    };        
    let x = lastName("Lopez");
    

    This is how you can write in ES6:

    lastName = (family) => console.log("My last name is " + family);
    x = lastName("Lopez");
    

    2- Deceleration Functions: Functions are declared with the following syntax are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).These type of functions work if you call them BEFORE or AFTER where they have been defined. If you call a deceleration function before where it has been defined - Hoisting - works properly.

    function Name(name) {
      console.log("My cat's name is " + name);
    }
    Name("Chloe");
    

    Hoisting example:

    Name("Chloe");
    function Name(name) {
       console.log("My cat's name is " + name);
    }
    

提交回复
热议问题