Reputation: 113
I have a function to check sums in an array :
function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();
for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}
answers.length != 0 ? console.log(answers) : console.log("nada")
}
I originally had the last line just return answers;
but let's say I don't want to return an empty array -- instead, I'd rather just log a statement.
why doesn't a return
in a ternary conditional work such as this:
answers.length != 0 ? return answers : console.log("nada")
Upvotes: 5
Views: 10759
Reputation: 755
I used ternary operators like this a lot in the past. It's fun, and keeps it to one line.
It can certainly be done, as Ankit shows, by putting the return statement out front
return answers.length != 0 ? answers : console.log('nada')
But I would recommend you use a classic if
statement for this. Particularly since you're testing whether to return a value or just log one.
if (answers.length != 0) {
return answers;
};
console.log('nada')
I would go even further and recommend that you return the same value type no matter what. This will go a long way for using your function, well - functionally. In this case, that would involve still returning the array (even if it's empty) and logging the nada
as well if empty.
if (answers.length == 0) {
console.log('nada');
};
return answers;
Upvotes: 0
Reputation: 370689
The ternary (conditional) operator expects the "expr1" part (where return answers
is) to be an expression - that is, something that can be evaluated to a value, which can be used in other expressions. But a return
statement is a statement, one which cannot possibly be interpreted as value, or as an expression; hence, a syntax error is thrown.
Instead of
answers.length != 0 ? console.log(answers) : console.log("nada")
either use a standard if statement:
if (answers.length !== 0) return answers;
console.log('nada');
or, if you just want to log, put the conditional operator inside the console.log
instead:
console.log(
answers.length === 0
? 'nada'
: answers
)
Upvotes: 3
Reputation: 30739
You need to use return answers.length != 0 ? answers : console.log("nada")
. The reason it fails is because ternary conditions do not support return
in their conditions. Infact, the ternary operator evaluates to an expression and expressions do not contain a return statement.
function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();
for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}
return answers.length != 0 ? answers : console.log("nada")
}
console.log(checkSum([1, 4, 6, 11], 10));
Upvotes: 5