Return number from function javascript

Возврат значений — Основы JavaScript

Функции, которые мы определяли в предыдущих уроках, заканчивали свою работу тем, что печатали на экран какие-то данные:

const greeting = () =>  console.log('Hello, Hexlet!'); >; 

Пользы от таких функций не очень много, так как результатом их работы невозможно воспользоваться внутри программы. Рассмотрим это на примере.

Возьмем задачу обработки электронной почты. Когда пользователь регистрируется на каком-то сайте, то он может ввести email любым способом:

  • Добавив случайно пробелы в начале или в конце _support@hexlet.io__
  • Использовав буквы в разном регистре SUPPORT@hexlet.io

Если мы сохраним его в таком виде в базу данных, то пользователь не сможет войти на сайт, если будет вбивать адрес без пробелов и в другом регистре. Чтобы этого не произошло, email нужно подготовить к записи в базу, привести его к нижнему регистру и обрезать пробельные символы по краям строки. Вся задача решается в пару строчек:

const saveEmail = () =>  // В реальности email приходит из формы const email = ' SuppORT@hexlet.IO'; // обрезаем пробельные символы const trimmedEmail = email.trim(); const preparedEmail = trimmedEmail.toLowerCase(); console.log(preparedEmail); // здесь будет запись в базу данных >; 

Этот код стал возможен только благодаря возврату значения. Методы trim() и toLowerCase() ничего не печатают на экран (в консоль), они возвращают результат своей работы и поэтому мы можем записать его в константы. Если бы они вместо этого печатали на экран, мы бы не могли присвоить результат их работы константе. Как мы не можем сделать с определенной выше функцией greeting() :

const message = greeting(); console.log(message); // => undefined 

Изменим функцию greeting() таким образом, чтобы она начала возвращать данные, вместо их печати. Для этого нам понадобится выполнить возврат вместо печати на экран

const greeting = () =>  return 'Hello, Hexlet!'; >; 

return – особая инструкция, которая берет выражение, записанное справа, и отдает его наружу, тому коду, который вызвал функцию. Как только JavaScript натыкается на return , выполнение функции на этом завершается.

// Теперь мы можем использовать результат работы функции const message = greeting(); console.log(message); // => Hello, Hexlet! // И даже выполнить какие-то действия над результатом console.log(message.toUpperCase()); // => HELLO, HEXLET! 

Любой код после return не выполняется:

const greetingWithCodeAfterReturn = () =>  return 'Hello, Hexlet!'; console.log('Я никогда не выполнюсь'); >; 

Даже если функция возвращает данные, это не ограничивает ее в том, что она печатает. Кроме возврата данных мы можем и печатать:

const greetingWithReturnAndPrinting = () =>  console.log('Я появлюсь в консоли'); return 'Hello, Hexlet!'; >; // И напечатает текст на экран и вернет значение const message = greetingWithReturnAndPrinting(); 

Возвращать можно не только конкретное значение. Так как return работает с выражениями, то справа от него может появиться почти все что угодно. Здесь нужно руководствоваться принципами читаемости кода:

const greeting = () =>  const message = 'Hello, Hexlet!'; return message; >; 

Здесь мы не возвращаем переменную, возвращается всегда значение, которое находится в этой переменной. Ниже пример с вычислениями:

const doubleFive = () =>  // или return 5 + 5 const result = 5 + 5; return result; >; 

Вопрос на самопроверку. Что вернет вызов функции run() , определенной ниже?

// Определение const run = () =>  return 5; return 10; >; // Что будет выведено на экран? console.log(run()); 

Дополнительные материалы

Остались вопросы? Задайте их в разделе «Обсуждение»

Вам ответят команда поддержки Хекслета или другие студенты

Об обучении на Хекслете

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно

  • 130 курсов, 2000+ часов теории
  • 1000 практических заданий в браузере
  • 360 000 студентов

Наши выпускники работают в компаниях:

Источник

Function return values

There’s one last essential concept about functions for us to discuss — return values. Some functions don’t return a significant value, but others do. It’s important to understand what their values are, how to use them in your code, and how to make functions return useful values. We’ll cover all of these below.

Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps, Functions — reusable blocks of code.

What are return values?

Return values are just what they sound like — the values that a function returns when it completes. You’ve already met return values several times, although you may not have thought about them explicitly.

Let’s return to a familiar example (from a previous article in this series):

const myText = "The weather is cold"; const newString = myText.replace("cold", "warm"); console.log(newString); // Should print "The weather is warm" // the replace() string function takes a string, // replaces one substring with another, and returns // a new string with the replacement made 

The replace() function is invoked on the myText string, and is passed two parameters:

When the function completes (finishes running), it returns a value, which is a new string with the replacement made. In the code above, the result of this return value is saved in the variable newString .

If you look at the replace() function MDN reference page, you’ll see a section called return value. It is very useful to know and understand what values are returned by functions, so we try to include this information wherever possible.

Some functions don’t return any value. (In these cases, our reference pages list the return value as void or undefined .) For example, in the displayMessage() function we built in the previous article, no specific value is returned when the function is invoked. It just makes a box appear somewhere on the screen — that’s it!

Generally, a return value is used where the function is an intermediate step in a calculation of some kind. You want to get to a final result, which involves some values that need to be calculated by a function. After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation.

Using return values in your own functions

To return a value from a custom function, you need to use the return keyword. We saw this in action recently in our random-canvas-circles.html example. Our draw() function draws 100 random circles somewhere on an HTML :

function draw()  ctx.clearRect(0, 0, WIDTH, HEIGHT); for (let i = 0; i  100; i++)  ctx.beginPath(); ctx.fillStyle = "rgba(255,0,0,0.5)"; ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); ctx.fill(); > > 

Inside each loop iteration, three calls are made to the random() function, to generate a random value for the current circle’s x-coordinate, y-coordinate, and radius, respectively. The random() function takes one parameter — a whole number — and returns a whole random number between 0 and that number. It looks like this:

function random(number)  return Math.floor(Math.random() * number); > 

This could be written as follows:

function random(number)  const result = Math.floor(Math.random() * number); return result; > 

But the first version is quicker to write, and more compact.

We are returning the result of the calculation Math.floor(Math.random() * number) each time the function is called. This return value appears at the point the function was called, and the code continues.

So when you execute the following:

.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI); 

If the three random() calls return the values 500 , 200 , and 35 , respectively, the line would actually be run as if it were this:

.arc(500, 200, 35, 0, 2 * Math.PI); 

The function calls on the line are run first, and their return values are substituted for the function calls, before the line itself is then executed.

Active learning: our own return value function

Let’s have a go at writing our own functions featuring return values.

function squared(num)  return num * num; > function cubed(num)  return num * num * num; > function factorial(num)  if (num  0) return undefined; if (num === 0) return 1; let x = num - 1; while (x > 1)  num *= x; x--; > return num; > 
.addEventListener("change", () =>  const num = parseFloat(input.value); if (isNaN(num))  para.textContent = "You need to enter a number!"; > else  para.textContent = `$num> squared is $squared(num)>. `; para.textContent += `$num> cubed is $cubed(num)>. `; para.textContent += `$num> factorial is $factorial(num)>. `; > >); 

Here are some explanations for the addEventListener function in step 3 above:

  • By adding a listener to the change event, this function runs whenever the change event fires on the text input — that is when a new value is entered into the text input , and submitted (e.g., enter a value, then un-focus the input by pressing Tab or Return ). When this anonymous function runs, the value in the input is stored in the num constant.
  • The if statement prints an error message if the entered value is not a number. The condition checks if the expression isNaN(num) returns true . The isNaN() function tests whether the num value is not a number — if so, it returns true , and if not, it returns false .
  • If the condition returns false , the num value is a number and the function prints out a sentence inside the paragraph element that states the square, cube, and factorial values of the number. The sentence calls the squared() , cubed() , and factorial() functions to calculate the required values.

Note: If you have trouble getting the example to work, check your code against the finished version on GitHub (see it running live also), or ask us for help.

Now it’s your turn!

At this point, we’d like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number? Or the circumference of a circle with a given radius?

Some extra function-related tips:

  • Look at another example of writing error handling into functions. It is generally a good idea to check that any necessary parameters are validated, and that any optional parameters have some kind of default value provided. This way, your program will be less likely to throw errors.
  • Think about the idea of creating a function library. As you go further into your programming career, you’ll start doing the same kinds of things over and over again. It is a good idea to create your own library of utility functions to do these sorts of things. You can copy them over to new code, or even just apply them to HTML pages wherever you need them.

Test your skills!

You’ve reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you’ve retained this information before you move on — see Test your skills: Functions.

Conclusion

So there we have it — functions are fun, very useful, and although there’s a lot to talk about in regards to their syntax and functionality, they are fairly understandable.

If there is anything you didn’t understand, feel free to read through the article again, or contact us to ask for help.

See also

  • Functions in-depth — a detailed guide covering more advanced functions-related information.
  • Callback functions in JavaScript — a common JavaScript pattern is to pass a function into another function as an argument. It is then called inside the first function. This is a little beyond the scope of this course, but worth studying before too long.
  • Previous
  • Overview: Building blocks
  • Next

Found a content problem with this page?

This page was last modified on Jul 3, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Читайте также:  Возведение матрицы в квадрат python
Оцените статью