I believe that, unless typing error, your intention was to compare someone to a value but in fact you are assigning a value to someone if (somaSubtracao = "+")
Equal sign assigns and two equals sign compares
there are still 3 signs of equal ===
which means strictly equal (checks content and type of variable).
When a function receives parameters, it assigns the values received to the variable names specified in the parentheses of the function definition. Consider the following script segment:
function somaSubtracao(num1) {
console.log(num1);
}
somaSubtracao(3);
After the function is defined, the next statement calls that same function, passing the number 3. somaSubtracao(3);
and the function will assign that value to the variable num1
and accomplish something with it.
In defining its function you should expect 3 parameters, that is, two numbers and a third one whose value will indicate what to do with the numbers passed, sum or subtraction.
function somaSubtracao(num1, num2, somaSubtracao) {
Thus the function lacked a third parameter that would be the operation between the other two parameters passed.
Done this call the function and pass the 3 parameters it expects, two numbers and a sign that represents sum or subtraction
somaSubtracao(3, 6, '+');
The correct conditional structure is:
if (condição 1) {
faça isso
} else if (condição 2) {
faça isso
} else {
faça isso
}
In your case it would be
function somaSubtracao(num1, num2, somaSubtracao) {
if (somaSubtracao == "+") {
return num1 + num2;
} else if (somaSubtracao == "-") {
return num1 - num2;
} else {
return "nenhuma das opções";
}
}
console.log(somaSubtracao(3, 6, '+'));
console.log(somaSubtracao(3, 6, '-'));
console.log(somaSubtracao(3, 6));
What? function name equal to variable name? This is the answer to another question :-)
Maybe you’d like to study a little more
function somaSubtracao(num1, num2) {
let Accum=0;
( !isNaN(num1) && !isNaN(num2) ) ? Accum=(num1+num2) : Accum=("nenhuma das opções");
return Accum;
}
console.log(somaSubtracao(3, 6));
console.log(somaSubtracao(3, -6));
console.log(somaSubtracao(-3, -6));
console.log(somaSubtracao(3));
console.log(somaSubtracao('x', 3));
isNaN - used to check when it is not a number, so if you want to know if it is numeric you can use !isNaN
. the symbol !
is negation, therefore the negation of não numérico
is numérico
The expression ( !isNaN(num1) && !isNaN(num2) ) ? Accum=(num1+num2) : Accum=("nenhuma das opções");
is ternary conditional operator. It evaluates conditional expressions, in a manner similar to if, see this response from bfavaretto on ternary operator.
I would like you to describe how to read this line of code I haven’t seen this type yet: ( !isNaN(num1) && !isNaN(num2) ) ? Accum=(num1+num2) : Accum=("none of the options"); It was perfect your comment, clarified a lot!
– Marcelinha MCZ
@Marcelinhamcz, I edited my reply and indicated a good answer on the subject
– user60252