Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize a parameter in javascript function when i define the function

i have a defined a function with a parameter in javascript, and i don't know how to initialize it's parameter, any one help me. the code is bellow

<br/>Enter a number:
<input type="text" id="txt1" name="text1">
<p>Click the button to see the result</p>
<button onclick="myFunction(5)">show result</button>
<br/>
<p id="demo"></p>
<script>
  function myFunction(param) {
    alert(param);
    var z = param;
    var y = document.getElementById("txt1").value;
    var x = +y + +z;
    document.getElementById("demo").innerHTML = x;
  }
</script>

the problem which i have is: if i send an argument to the function as <button onclick="myFunction(5)">show result</button> it works, but if i don't send any argument it is not working and the result is NaN. now i want to know how i can initialize the parameter wen i define the function? as we have in php function myFunction(param=0)

like image 591
Ali Avatar asked Jun 07 '15 10:06

Ali


2 Answers

Use param = param || 0; like

function myFunction(param) {
    param = param || 0;
    console.log(param);
    var z = param;
    var y = document.getElementById("txt1").value;
    var x = +y + +z;
    document.getElementById("demo").innerHTML = x;
  }

The above statement is saying set param to param if it is not falsey(undefined, null, false), otherwise set it to 0.

like image 158
AmmarCSE Avatar answered Sep 21 '22 19:09

AmmarCSE


whenever you do not initialize a value to a parameter javascript will consider it as undefined, so you can reap the benefit of this issue and do it like:

function myFunction(param)
     {

       param = typeof param !== 'undefined' ? param : 0;

     }

hope it would be useful.

like image 41
Masoud Mustamandi Avatar answered Sep 21 '22 19:09

Masoud Mustamandi