Doubts about JS function

0

I have the function myFunction that calculates the product of two numbers and displays them on the screen. I would like to divert this function to the listen function when the value of p1 = 10. As it stands, it only displays the value of myFunction, and ignores the equality p1 = 10 to make the deviation. Can you help me?

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p id="demo"></p>

<script>
function myFunction(p1, p2) {

if (p1=10)  {listen(a)}
    return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(10, 3);


var a ="jj";

function listen(k){
 var s1 = k;
 alert(s1);
 return k
 }

</script>

</body>
</html>
    
asked by anonymous 28.05.2017 / 22:20

2 answers

1
  

In your code, besides doing an assignment here:

if (p1=10) // deveria ser if (p1==10)
  

You are setting a after calling the function:

document.getElementById("demo").innerHTML = myFunction(10, 3); 
var a ="jj";
  

So a is undefined - Move var a="jj"; to before function:

var a ="jj";
document.getElementById("demo").innerHTML = myFunction(10, 3);
  

And I believe the program will work just the way you want it to. I've changed your code a bit, just to make it easier to test, click Run just below the code:

function myFunction(p1, p2) {
    if (p1==10)  {listen(a)}
    else alert(p1 * p2);
}

function listen(k){
    var s1 = k;
    alert(s1);
    return k
}

var a ="jj";
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p id="demo"></p>
<input type="number" id="valor1" value=10>
<input type="number" id="valor2" value=3>
<button onclick="myFunction(document.getElementById('valor1').value,
  document.getElementById('valor2').value)">Testar Função</button>

</body>
</html>
    
30.05.2017 / 05:55
0

When you use only = in JavaScript this is attribution and not comparison.

That is, what p1=10 does is p1 becomes 10 .

You should use == to compare the value, or === to compare the value and be of the same type.

Suggestion:

var a = "jj";

function myFunction(p1, p2) {
  if (p1 == 10) return listen(a);
  else return p1 * p2;
}

function listen(k) {
  return k
}

document.getElementById("demo").innerHTML = myFunction(10, 3);
<h2>JavaScript Functions</h2>

<p id="demo"></p>
    
28.05.2017 / 22:32