美文网首页英语吧想法成长励志
JavaScript Functions: Study Note

JavaScript Functions: Study Note

作者: 此之木 | 来源:发表于2019-06-17 08:05 被阅读55次

    In the last post, I shared the argument note. The arguments allow the function take inputs but not send back any output value.

    The return keyword allows a function to send back an output value.

    If we use the return keyword, it means that we can capture the value that is coming back out of the function.

    For example:

    function square(x) {

    return x * x;

    }

    When I enter the function in the console and call square(4), it will give us a return sign “<” in front of 16.

    However, in the argument function, the result only print out the value. The return value is undefined.

    The other thing we can do with the return keyword is save it in a variable such as:

    var result = square(100)

    result

    So this function call square of 100 is evaluated that return 10000 which is then stored in result.

    Function Declaration V.S. Function Expression

    Function Declaration:

    function sayHi(){console.log (“Hello!”);}

    Function Expression:

    var sayHi = function() {console.log (“Hello!”);}

    As we can see, there is a difference on how we write between function declaration and function expression. The function expression is written like a var name = function (), but the function declaration is written asthe function name().

    For example, we enter function sayHi in different way. As you see, when we call “sayHi()”, it will give us the same result “Hello!”. 

    For the function expression, when I give a value of sayHi, and call it back, it will return the value. However, if I call “sayHi()”, it doesn’t run the function anymore.

    Therefore, no matter how we name a function, be it with a variable in a function expression or directly in a function declaration, it can be overwritten if you assign the same variable to something else, later in the code. (From the course note)

    相关文章

      网友评论

        本文标题:JavaScript Functions: Study Note

        本文链接:https://www.haomeiwen.com/subject/wqhnoqtx.html