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")
In a ternary operator, we cannot use the return statement.
"the ternary operator returns always an rvalue. surprisingly it does" Do you meant "doesn't", as it can return lvalue (when both side are lvalues). In C, the conditional operator never yields an lvalue. In C++, it sometimes does.
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
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));
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With