JavaScript 12

JavaScript 12

With Examples

Hi everyone, My name is Arinze Calistus. The purpose of this blog is to teach you all you need to know about JavaScript return statements as well as Function Scope.

The return statement is used in a function to stop its execution and to return a value to the function caller. For example, the addNumbers( ) function below returns the sum of it's arguments to the function caller. Then, the function caller prints the returned value to an element.

function addNumbers(num1, num2) {
  var sum = num1 + num2;
  return sum;
}
/* the function caller*/
document.getElementById("demo").innerHTML = addNumbers(2, 7);

The example below assigns the returned value to a variable. The variable is the used in a statement.

function getFullName(firstName, lastNumber) {
  return firstName + " " + lastName;
}
var fullName = getFullName("John", "Doe");
document.write(fullName);

Function Scope

Variables declared inside a function are called Local Variables. Local Variables can only be used inside the function where it was declared. If a local variable is used outside, the value's data type is undefined.

Nothing will be printed on the paragraph element with the demo1 id, because the name of the variable cannot be used outside the function.

<p id ="demo" ></p>
<p id ="demo1" ></p>
<button onclick="getAge(19)"> Call Function </button>
// Script
function getAge(age) {
    var fullName = "John Doe";
    // the fullName variable can be used here
   document.getElementById("demo").innerHTML = fullName + " is" + age + "years old.";
}
// the fullName variable cannot be used here
document.getElementById("demo").innerHTML = fullName;

Global Scope

Global variables can be used by any function. Global variables are variables declared outside a function, for example, the fruit variable is declared outside a function.

Therefore, it can be used by any function.

var fruit = "apple";
function myFunc( ) {
   document.getElementById("demo ").innerHTML = "My favorite fruit is" + fruit;
}

This brings me to the end of this blog, follow me on Twitter

Thanks for reading