0

As per learn and try I am working on very simple function to understand features of JavaScript function. But after create function I am getting some issues, I hope someone can help me for my following questions.

Questions are:-

a) Why console.log from browser is showing ReferenceError: c is not defined ?
b) Why p id="demo" is not able to show result ?
c) Why alert(c); outside of the function is not showing result once browser load/refresh?
d ) Why return(c); is not working?

function show(a, b){
  
  var c = a+b;
  alert(c);
  console.log(c);
  return(c);
  
}
alert(c);
document.getElementById("demo").innerHTML = c;        
<p onclick="show(10, 20)" >This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>
Sandy
  • 255
  • 1
  • 7
  • 16

5 Answers5

2

Because function braces in javascript define scope and all variables declared inside it aren't visible outside of it. So c is undefined where you're alerting it.

function show(a, b){
   var c;
   //'c' is visible only in the function
}
kidwon
  • 4,080
  • 4
  • 25
  • 44
2

As i say in my comment :

If you define c in function is only define in function

You can do this :

HTML

<p onclick="show(10, 20)" >This example calls a function which performs a calculation, and returns the result:</p>

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

JS

    function show(a, b){

      var c = a+b;
      document.getElementById("demo").innerHTML = c; 

    }
Benjamin Poignant
  • 1,020
  • 8
  • 18
1

Variable c is local to function show. So when you call it outside of the funciton,

you get the error ReferenceError: c is not defined and as c is nothing, p demo doesn't show anything

snehatulsi
  • 231
  • 1
  • 11
1

    function show(a, b){
      
      var c = a+b;
      return(c);
      
    }
    var d = show(10,20);
    document.getElementById("demo").innerHTML = d; 
    <p onclick="show(10, 20)" >This example calls a function which performs a calculation, and returns the result:</p>

    <p id="demo"></p>
snehatulsi
  • 231
  • 1
  • 11
  • thanks for your suggestions. can you please help me to learn more about return()? – Sandy Feb 19 '15 at 12:38
  • return is a statetement, when executed returns from the current function. The lines after that are never executed. And we can return values in the return statement. We can return both data/function in javascript. – snehatulsi Feb 19 '15 at 16:44
0

Try This:-

        var c = "10";
        function show(a, b){
  
            c = a+b;
            alert(c);
            console.log(c);
            document.getElementById("demo").innerHTML = c;  
        }       
        window.onload = function () {
            document.getElementById("demo").innerHTML = c;
        };
    
    
<p onclick="show(10, 20)">This example calls a function which performs a calculation, and returns the result:</p>

    <p id="demo"></p>
Sharique Ansari
  • 1,410
  • 1
  • 12
  • 20