What does «return» do in Javascript?
I just taught myself how to code with tutorials from the internet. I’m currently trying to learn Javascript and I don’t really undesrtand the purpose of «return». I made a «rock, paper, scissors» game at the end of my lesson, using the return function. The game looks like this:
var userChoice = prompt("Do you choose rock, paper or scissors?"); var computerChoice = Math.random(); if (computerChoice < 0.34) < computerChoice = "rock"; >else if(computerChoice else < computerChoice = "scissors"; >console.log("Computer: " + computerChoice); var compare = function(choice1, choice2) < if(choice1 === choice2)< return "The result is a tie!"; >else if(choice1 === "rock") < if(choice2 === "scissors")< return "rock wins"; >else < return "paper wins"; >> else if(choice1 === "paper") < if(choice2 === "rock")< return "paper wins"; >else < return "scissors wins"; >> else if(choice1 === "scissors") < if(choice2 === "paper")< return "scissors wins"; >else < return "rock wins"; >> >; compare(userChoice, computerChoice);
Surprisingly enough it «returns» whatever is after it. So if you call the function like var f = test() and test() return a value then f will be that value.
when you call the function, it will return value based on some conditions console.log( compare(1,1) ); will output the first condition ( «The result is a tie!» ) because the values sent to the function match
console.log() only prints something in your browsers console. While return give back an expected value from a function which later can be used from another function or class to do more stuff.
5 Answers 5
The return statement stops the execution of a function and returns a value from that function.
console.log writes into the browser console.
In other words, you can’t see the output of console.log unless you open ‘Developer Tools’
According to MDN (a much more reliable source),
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead. The following return statements all break the function execution:
return; return true; return false; return x; return x + y / 3;
console.log() outputs a message to the Web Console.
would return 3.141592653589793 when the function is called.
But using console.log instead, would not show anything, on a webpage (except in developer tools).
In JavaScript, most things are expressions, and every expression has a value. That can be a number ( 5 ), a string ( «Hello, World!» ), an object ( < foo: 'bar' >) or something other, like a regex.
When you use an operator, e.g. choice1 === «rock» , that’s also an expression, which has a boolean value (true or false). The expression 5 + 3 has a value, too. It is 8 .
When you call a function, that’s also an expression, which has a value. The prompt function, for example, has the value that the user entered. It’s what you get back when you call prompt(. ) . The value of a function call is refered to as the «return value» of that function.
When you define your own function, you can also give them a return value. And later, when you call the function, this return value is what you get back. Remember functions in the maths class in school? Things like f(x) = x * x ? When you «call» f with 5 , then 25 is the value of that «function call»: f(5) = 5 * 5 = 25 .
Now, let’s define our own JavaScript function that has a return value:
function add (a, b) < return a + b; // make the sum of a and b the return value of "add" >var result = add(5, 3); // store the value of the function call console.log(result); // should log 8
Many built-in JavaScript functions have a return value: Math.min() returns the smallest of the arguments passed to it, document.getElementById() returns the HTML element with the id that you passed to it.
For some functions, it doesn’t make any sense to return the result of an action. What should be the result of console.log() ? Those functions return the value undefined . When your own functions don’t have a return statement, their return value is undefined .
It is very important to note that the execution of a function stops when it hits a return statement. It then immediately returns to the location in the script where the function was called:
function test () < console.log('Hello 1'); return 5; // return to the caller console.log('Hello 2'); // will not execute >var result = test(); console.log(result); // 5
When you leave out the value after the return . ; , so you just say return; , then the return value will also be undefined . You can use that if you want to stop the execution without a value to return:
function divide (a, b) < return a / b; >function printQuotient (a, b) < if (b === 0) < // the divisor is zero, do nothing return; >// divisor is not zero, print the result of the division console.log(divide(a, b)); > printQuotient(10, 5); // prints 2 printQuotient(10, 0); // prints nothing
return
Функция возвращает результат, который будет передан в вызвавший её код. Для этого и используется ключевое слово return .
Пример
Скопировать ссылку «Пример» Скопировано
Примеры использования return. Функция проверки возраста на совершеннолетие и функция создания строки заданной длины со случайным содержимым — просто введите произвольные числа 😎
Как пишется
Скопировать ссылку «Как пишется» Скопировано
return используется только в функциях. Этот код приведёт к ошибке, так как не является функцией:
const result = 42if (result > 10) return true>return false
const result = 42 if (result > 10) return true > return false
function isAdult(age) return age > 18>
function isAdult(age) return age > 18 >
Как понять
Скопировать ссылку «Как понять» Скопировано
Определённый код «сгруппирован» и объединён в функцию, например проверка — чётное число или нет:
function isEven(value) if (undefined === value || null === value) return false > return value % 2 == 0>
function isEven(value) if (undefined === value || null === value) return false > return value % 2 == 0 >
Пример
Скопировать ссылку «Пример» Скопировано
Для возврата значения используется инструкция return
Она может находиться в любом месте функции. Как только до неё доходит управление — функция завершается и значение передаётся обратно.
Писать return в функции необязательно. Рассмотрим пример:
function notify(msg, type) if (type === 'error') alert('ОШИБКА:' + msg) > alert(msg)>
function notify(msg, type) if (type === 'error') alert('ОШИБКА:' + msg) > alert(msg) >
Такой функции нечего возвращать, она служит только для группировки набора команд.
Несмотря на отсутствие return , такая функция будет возвращать undefined , будто бы в ней последней строчкой написано return undefined
Ниже пример, который показывает что это действительно так:
function notify(msg, type) if (type === 'error') alert('ОШИБКА:' + msg) > alert(msg)>function notifyFull(msg, type) if (type === 'error') alert('ОШИБКА:' + msg) > alert(msg) return undefined>const a = notify('Сообщение')const b = notifyFull('Сообщение')console.log(a === b)// true
function notify(msg, type) if (type === 'error') alert('ОШИБКА:' + msg) > alert(msg) > function notifyFull(msg, type) if (type === 'error') alert('ОШИБКА:' + msg) > alert(msg) return undefined > const a = notify('Сообщение') const b = notifyFull('Сообщение') console.log(a === b) // true
На практике
Скопировать ссылку «На практике» Скопировано
Дока Дог советует
Скопировать ссылку «Дока Дог советует» Скопировано
🛠 Благодаря return можно использовать результат работы функции где угодно. Например, в условиях или при формировании новых значений. Пример ниже использует функцию с return для проверки условия — действительно ли счёт игрока больше 100:
function checkScore(score) return score > 100>const s1 = 10const s2 = 15const s3 = 20if (checkScore(s1)) alert('игрок 1 проходит')if (checkScore(s2)) alert('игрок 2 проходит')if (checkScore(s3)) alert('игрок 3 проходит')
function checkScore(score) return score > 100 > const s1 = 10 const s2 = 15 const s3 = 20 if (checkScore(s1)) alert('игрок 1 проходит') if (checkScore(s2)) alert('игрок 2 проходит') if (checkScore(s3)) alert('игрок 3 проходит')
const s1 = 10const s2 = 15const s3 = 20if (s1 > 100) alert('игрок 1 проходит')if (s2 > 100) alert('игрок 2 проходит')if (s3 > 100) alert('игрок 3 проходит')
const s1 = 10 const s2 = 15 const s3 = 20 if (s1 > 100) alert('игрок 1 проходит') if (s2 > 100) alert('игрок 2 проходит') if (s3 > 100) alert('игрок 3 проходит')
Почему эффективнее?
- если условие проверки очков изменится — его придётся писать в нескольких местах.
- если условие будет состоять более чем из одной проверки, то if усложнится и его будет сложнее понимать. Функцию, дающую ответ true или false легче читать в условном операторе.
Необходимо помнить, если выполнение функции завершилось не через return , то возвращаемое значение будет undefined ;
Самый простой способ этого избежать — всегда добавлять return с каким-либо значением перед концом функции.
- Ещё return останавливает выполнение функции. Обычно это ожидаемое поведение, но если про это забыть — возможны баги.
What does «return false;» do?
I wrote a webpage where a user can enter a log entry that is stored on a database and then retrieved and printed on the page using ajax . I am still quite new to ajax and was wondering if somebody could please explain to me what does return false; do at the end of my code? and is it even necessary? If I put the second ajax code after the return false the code does not work! can you please explain to me why?
//handles submitting the form without reloading page $('#FormSubmit').submit(function(e) < //stores the input of today's data var log_entry = $("#LogEntry").val(); // prevent the form from submitting normally e.preventDefault(); $.ajax(< type: 'POST', url: 'behind_curtains.php', data: < logentry: log_entry >, success: function() < alert(log_entry); //clears textbox after submission $('#LogEntry').val(""); //presents successs text and then fades it out $("#entered-log-success").html("Your Entry has been entered."); $("#entered-log-success").show().fadeOut(3000); >>); //prints new log entries on page upon submittion $.ajax(< type: 'POST', url: '/wp-content/themes/childOfFanwood/traininglog_behind_curtains.php', data: < log_entries_loop: "true" >, success: function(data) < alert(data); $("#log-entry-container").html(""); $("#log-entry-container").html(data); >>); return false; >);
5 Answers 5
What I’ll write here is true for jQuery events,
For vanilla javascript events read @T.J. Crowder comment at the bottom of the answer
return false inside a callback prevents the default behaviour. For example, in a submit event, it doesn’t submit the form.
return false also stops bubbling, so the parents of the element won’t know the event occurred.
return false is equivalent to event.preventDefault() + event.stopPropagation()
And of course, all code that exists after the return xxx line won’t be executed. (as with all programming languages I know)
A «real» demo to explain the difference between return false and event.preventDefault() :
$('#theDiv').submit(function() < alert('DIV!'); >); $('#theForm').submit(function(e) < alert('FORM!'); e.preventDefault(); >);
Now. when the user submit the form, the first handler is the form submit, which preventDefault() -> the form won’t be submitted, but the event bubbles to the div, triggering it’s submit handler.
Now, if the form submit’s handler would cancel the bubbling with return false :
$('#theDiv').submit(function() < alert('DIV!'); >); $('#theForm').submit(function(event) < alert('FORM!'); return false; // Or: event.preventDefault(); event.stopPropagation(); >);
The div wouldn’t even know there was a form submission.
What does return false do in vanilla javascript events
return false from a DOM2 handler ( addEventListener ) does nothing at all (neither prevents the default nor stops bubbling; from a Microsoft DOM2-ish handler ( attachEvent ), it prevents the default but not bubbling; from a DOM0 handler ( onclick=»return . » ), it prevents the default (provided you include the return in the attribute) but not bubbling; from a jQuery event handler, it does both, because that’s a jQuery thing. Details and live tests here – T.J. Crowder