The Use of Return in JavaScript

The basic use of return in JavaScript is to run some function and asiagn a result to a variable. For exampe,
var number;

function getSquare(x){
	return x*x;
};

number = getSquare(2);
console.log(number);
//4

Print the Result

The use of return in combination with HTML can be shortern the code if you want to output it on the website.

<input type = "number" value = "2" id = "numberInput"><br>
<button onclick = "calculate()">Get Square</button>
<div id = "show"></div>
<script>
function calculate(){
	show.innerHTML = getSquare(numberInput.value);
};

  function getSquare(x){
	return x*x;
};
</script>
Here the line of code we are interested in is "show.innerHTML = getSquare(numberInput.value);" where we don't need to assign to another variable.

Use Return When Runing Multiple If Statement

We can use the switch case loop to check if a variable has a certain value and do something. but if we need to check multiple conditions which are loosly related.
We can use multiple if statements and we need to add return at the end of each, otherwise our program may have errors.

<input id="numberInput1" type="number" value="2" /><br />
  <button onclick="run();hi();">Run</button>
  <div id="show1"></div>
  <script>
  function run(){
  	var v =  Number(numberInput1.value);
    if(v == 1){
    	show1.innerHTML = v;
      	return;
    };
    if(v == 2){
    	show1.innerHTML = v;
      	return;
    };
     if(v == 3){
    	show1.innerHTML = v;
      	return;
    };
      alert("hi");
  };
</script>
Notice that when the input number is 1, 2 or 3, the alert("hi") is not triggered. This is useful when we want to check some conditions and if the conditions are met we run a block of code and terminate the rest of the execution of the same function.
The hi() function in the onclick event listerner of the button gets triggered, which means the return expression only stops the current function and the browser will proccedd with the next.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser