Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
1. JavaScript: Basics
9Topics
|
10 Quizzes
2. JavaScript: Variables
9Topics
|
10 Quizzes
3. JavaScript: Conditional Statements
10Topics
|
11 Quizzes
4. JavaScript: Functions
10Topics
|
11 Quizzes
5. JavaScript: Scope
6Topics
|
7 Quizzes
6. JavaScript: Arrays
11Topics
|
12 Quizzes
7. JavaScript: Loops
8Topics
|
9 Quizzes
8. JavaScript: High Order Functions
3Topics
|
3 Quizzes

Participants 24

In Progress
Lesson 4, Topic 6
In Progress

JavaScript: Return

Yasin Cakal 7 Nov 2021
Lesson Progress
0% Complete

When a `function` is called, the computer runs through the code of the `function` and evaluates the result of calling it. The resultant value is `undefined` by default.

``````function squarePerimeter(legnth){
perimeter= legnth*4;
}

console.log(squarePerimeter(10));

//Output: undefined``````

In the example above, We defined our `function` to calculate the perimeter of a square by taking `length` as a parameter. The `squarePerimeter()` is then called with argument `10`. However, when we tried to print the results, they were `undefined`. Is it possible that we wrote our `function` incorrectly? No! In fact, the `function` worked as expected, and the computer calculated the perimeter to be `40` feet, but we failed to record it. So, what is the best way to go about it? Using the keyword `return`!

``````function squarePerimeter(legnth){
perimeter= legnth*4;
return perimeter;
}

console.log(squarePerimeter(10));

//Output: 40``````

A `return` statement is used to return information from a function call. We use the `return` keyword followed by the value we want to return to create a `return` statement. If the value is omitted, `undefined` is returned instead, as we saw earlier.

When a `return` statement is used in the body of a function, the function’s execution is stopped, and the code after it is not executed. Take a look at the following example:

``````function squarePerimeter(length) {
if (length < 0) {
return 'You need positive integer to calculate perimeter!';
}
return 4*length;
}

console.log(squarePerimeter(-9));

//Output: You need positive integer to calculate perimeter!

``````

If the `length` argument is less than 0, `squarePerimeter()` will return `You need positive integer to calculate perimeter!` The second `return` statement, `4*length`, will not be executed.

Because it allows functions to produce output, the `return` keyword is extremely useful. The output can then be saved to a variable for later use.

Quizzes