Why JavaScript Functions Always Return a Value

Why JavaScript functions always return a value?

It's true—because that's how JavaScript was designed.

But I don't think that's the answer you were looking for, so let's think about it...

Try to put yourself in the shoes of Brendan Eich, the person who designed JavaScript!

In static languages, there is usually a distinction between a function that doesn't return anything (void function), and a function that returns some value. Brendan chose to design a dynamic language, that is, a language that doesn't require you to define function return types. So JavaScript doesn't check what you return from the function, giving you full freedom.

You can have a function that returns a number...

function computeSomething() {
return 2;
}

... or a string ...

function computeSomething() {
return 'hi';
}

... or, in fact, any of them:

function computeSomething() {
if (Math.random() > 0.5) {
return 2;
} else {
return 'hello';
}
}

Sometimes you don't need to compute anything—you only need to do something.

So you don't return anything.

function doSomething() {
console.log('doing something');
}

We may, however, want to exit a function in the middle of it, and since return <value> already does exactly that, it makes sense to allow writing return without a value to support this use case:

function doSomething(num) {
if (num === 42) {
return;
}

while (true) {
doSomethingElse();
}
}

This is also consistent with C/Java syntax, which was one of the goals to ensure JavaScript adoption.

Aye, there's the rub: what happens if we put a plain return into a function supposed to compute something? Note that we can't outlaw this: one of our earlier decisions was to make JavaScript a dynamic language, where we don't check what the function returns.

function computeSomething(num) {
if (num === 42) {
return; // just return? o_O
}

if (Math.random() > 0.5) {
return 2;
} else {
return 'hello';
}
}

var x = computeSomething(2); // might be 2, might be 'hello'
var y = computeSomething(42); // ???

Of course Brendan could have decided to raise an error in this case, but he wisely decided not to, because it would lead to hard-to-find errors and too easily breakable code.

So an empty return got a meaning “return undefined”.

But what's the difference between the function returning early, or at its end? There shouldn't be any, from the calling code's point of view. Calling code is not supposed to know when exactly the function returned; it is only interested in return value (if any).

The only logical conclusion thus would be to make undefined the “default” return value if function does not specify one via explicit return <value> operator. Thus, return and function-executed-to-its-end semantics match.

Python, another dynamic language that came before JavaScript, solves this problem in the same way: None is returned if function doesn't specify return value.

Does A Function Always Return A Value

Yes it always returns a value, if explicit one is not given, it returns undefined. This is same as you will write return undefined or just return.

Should functions always return something (Javascript)

They don't have to return anything. If you leave it blank it simply returns 'undefined' which in this case is fine because you never intend to use the return value. The Javascript syntax is pretty simplistic and as far as I know there just isn't any real distinction between functions that do and functions that don't return a value (other than the 'return' keyword)

Does every Javascript function have to return a value?

The short answer is no.

The real answer is yes: the JS engine has to be notified that some function has finished its business, which is done by the function returning something. This is also why, instead of "finished", a function is said to "have returned".

A function that lacks an explicit return statement will return undefined, like a C(++) function that has no return value is said (and its signature reflects this) to return void:

void noReturn()//return type void
{
printf("%d\n", 123);
return;//return nothing, can be left out, too
}

//in JS:
function noReturn()
{
console.log('123');//or evil document.write
return undefined;//<-- write it or not, the result is the same
return;//<-- same as return undefined
}

Also, in JS, like in most every language, you're free to simply ignore the return value of a function, which is done an awful lot:

(function()
{
console.log('this function in an IIFE will return undefined, but we don\'t care');
}());
//this expression evaluates to:
(undefined);//but we don't care

At some very low level, the return is translated into some sort of jump. If a function really returned nothing at all, there would be no way of knowing what and when to call the next function, or to call event handlers and the like.

So to recap: No, a JS function needn't return anything as far as your code goes. But as far as the JS engines are concerned: a function always returns something, be it explicitly via a return statement, or implicitly. If a function returns implicitly, its return value will always be undefined.

Why does my function always return the same value?

Fixing only the problem that the computer can never choose SCISSORS, it runs and works. Maybe you just had a lucky run of draws.

const startGameBtn = document.getElementById('start-game-btn');
let ROCK = "ROCK";let PAPER = "PAPER";let SCISSORS = "SCISSORS";let RESULT_DRAW = "It's a draw";let RESULT_PLAYER_WINS = "Player Wins";let RESULT_COMPUTER_WINS = "Player Wins";
let GAME_IS_RUNNING = false;
let getPlayerChoice = function() { let selection = prompt(`${ROCK},${PAPER}, or ${SCISSORS}? `, '').toUpperCase(); if (selection !== ROCK && selection !== PAPER && selection !== SCISSORS) { alert("Invalid choice, defaulted to Rock"); selection = ROCK; } return selection}const getComputerChoice = function() { const randomValue = Math.floor(Math.random() * 3); // <---- if (randomValue === 0) { return ROCK; } else if (randomValue === 1) { return PAPER; } else if (randomValue === 2) { return SCISSORS; };}
const getWinner = function(cChoice, pChoice) { if (cChoice === pChoice) { return RESULT_DRAW; } else if (cChoice === ROCK && pChoice === PAPER || cChoice === PAPER && pChoice === SCISSORS || cChoice === SCISSORS && pChoice === ROCK ) { return RESULT_PLAYER_WINS; } else { return RESULT_COMPUTER_WINS; }}
startGameBtn.addEventListener('click', function() { if (GAME_IS_RUNNING) { return } GAME_IS_RUNNING = true; console.log("Game is starting...."); let playerChoice = getPlayerChoice(); console.log(playerChoice); let computerChoice = getComputerChoice(); console.log(computerChoice); let winner = getWinner(computerChoice, playerChoice); console.log(winner);});
<button id="start-game-btn">START-STOP</button>

Does the arrow function have to always return a value?

No, (arrow) functions don't have to return anything but when function is not supposed to be void (i.e return value is expected), it's a good practice to return from every path/return some kind of default value if every other path fails.

const getCookie = name => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length == 2) {
return parts
.pop()
.split(';')
.shift();
}

// default return, for example:
return false;
};

Should I always give a return value to my function?

A "pure" functional programming environment would have no side effects -- each function's work would be entirely in computing its return value; that's not really feasible in typical uses of Javascript, and so it's perfectly acceptable, when a function has done its work through side effects, to have it return nothing at all, i.e., be a "procedure" rather than a function.

Why do Javascript functions return undefined on creation?

This fuction definition is a statement. In JS, statements don't return values, which, in JS, is an undefined value.

In JS, assignments with var are statements too, but assignments without var behave as expressions : their whole value is the value being assigned.

Therefore, in the console :

> x=function() {return 0;}
< ƒ () {return 0;}


Related Topics



Leave a reply



Submit