Learn Coding From Zero

JavaScript Functions: Study Note For The Return Keyword

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 as the 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)

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s