Variable Scope

The scope of a variable refers to the portions of the program where it can be directly accessed.
A variable declared within a function is called a local variable, its value is recognized only within that function, it doesn't exist out of that function. Thus, another function can declare a variable with same name, JS (JavaScript) treats the two as different variables.
The variables created outside the functions can be used everywhere in that script, inclusively inside the functions and other JS script from that HTML page.
Let's see some examples.

1. In the next example we declare a variable 'va' inside a function and then we try to use that variable outside function.
- This will cause an error in browser console and prints nothing becouse the script don't knows the variable 'va' outside the function ex1().
<script>
function ex1() {
 var va = 8;
}
document.write(va);
</script>
We can declare a variable with the same name outside and inside functions.
2. In the next example we use a variable 'va' declared outside function ex2() and also inside it.
<script>
var va = 'tutorials';
function ex2() {
 var va = 'lesson';
 document.write(va+ '<br>');
}

// Calling the function
ex2(); // lesson

document.write(va+ '<br>'); // tutorials (uses the 'va' declared outside function)
</script>
- In this code, the function ex2() declares a variable called 'va' and prints its value. When you reference that variable on the next line inside the function, the interpreter first checks the local scope (the function context) to see if it has been defined. If finds this variable declared in the local scope, it uses that one instead of any others of the same name that might appear higher up in the scope chain.
- But, when the variable 'va' is used outside function, the interpreter uses the value of the global variable. And the two 'va' variabiles does not interfere with each other.

• If inside function we use a global variable declared outside, without explicity define it with the word 'var' in local scope (inside function), the function will use and also will change the value of the global variable. As you can see in the next example.
<script>
var va = 5;
function ex3() {
 va += 3; // the same as ( va = va+3; )
 document.write(va+ '<br>');
}

// Calling the function
ex3(); // 8

document.write(va+ '<br>'); // 8
</script>
- In this example, you do not explicitly define (with 'var') the variable 'va' in function local scope, so it relies on the global scope and knows you are reassigning the global variable. When the function change its value, it is changing the value of the variable in the global scope.

Ussing different number of arguments

When we create a function and define the number of its arguments, we must keep them in mind when calling that function.
But, there are situations where we have to transmit a different number of arguments when we call the function, which may be lower or higher than the number of function parameters.

if you neglect to include arguments in your function call, the interpreter will not view this as a syntax error. The interpreter assigns a value of undefined to the missing arguments.
The value of undefined is evaluated to false when tested as a Boolean.

In such a situation we can asign a default value to the parameters, inside the function, for the case when the arguments are not transferred.
Below is presented a function that return the sum of its parameters. To be shure that the parameters are not undefined we test to see if each parameter is not defined (using the Boolean ! not), in that case we create a local variable by that name and by the time you get to the line beginning with return, every argument is defined and has a default value, if not already available.
- Example:
<script>
function sumNrs(a,b,c) {
 if (!a) a = 0;
 if (!b) b = 0;
 if (!c) c = 0;

 return a + b + c;
}

var sum1 = sumNrs(1, 2);
document.write('<p>'+sum1+'</p>');
</script>
- As you can see, the function sumNrs() has 3 parameters but was called with 2 arguments.

Define parameters with default value

When creating a function, you can define parameters with a default value, thus you not need to check if the argument is transmitted to the function.
- Syntax:
function fName(p1=v1, p2=v2){
 //code to be executed
}
- 'p1' and 'p2' are the parameters; 'v1' and 'v2' are the default values for each one.

If one of the arguments is not transmitted, the function will use the default value assigned to that parameter.
- Here is the previous example, but here wit default value defined to parameters:
<script>
function sumNrs(a=0, b=0, c=0){
 return a + b + c;
}

var sum1 = sumNrs(1, 2);
document.write('<p>'+sum1+'</p>');
</script>

The arguments property

In some cases the function can receive more arguments than its parameters. The values of additional arguments are not lost, they are stored in an Array called arguments, this object is a local property of all functions.
- For example, the arguments passed to a function called setMsg() are stored in the object-like Array setMsg.arguments.


To access an element of a typical Array you use the bracket operator []. The arguments are in the array in the order they were passed to the function. To access the first element you would use:
functionName.arguments[0]
The second argument can be access using:
functionName.arguments[1]
- and so on.

You can know the total number of arguments with the length property:
functionName.arguments.length

Example, a function that returns the sum of any numbers of arguments.
<script>
function addNumbers() {
 // Sets a variable that will return the amount
 var re = 0;
 // go through the arguments Array and adds every value to 're' variable
 for(var i=0; i<addNumbers.arguments.length; i++) {
 re += addNumbers.arguments[i];
 }

 return re;
}

document.write('1+2+3+4+5+6+7+8 = '+ addNumbers(1,2,3,4,5,6,7,8));
</script>

Nested Functions

You can create and use a function inside another function. This is known as function nesting.
- Example, inside a sumAB() function it's defined another function that is called when the sumAB() returns its result:

<script>
function sumAB(a,b) {
 // Get the amount of 'a' and 'b'
 var re = a+b;

 // Nested function
 function multiply(x) {
 return x*x;
 }

 // Return the call of nested function multiply(), with the variable 're' to argument
 return multiply(re);
}

document.write( sumAB(3,4) ); // 49
</script>

Recursive functions

A JavaScript function can be recursive, meaning it can auto-call itself.
A good way to demonstrate the ability of the recursive function is to solve a factorial equation.
In this example we have a JavaScript recursive function that finds the factorial of a number 'n' (here 8).
<script>
function factorial(n) {
 var re;
 if (n>0) re = n*factorial(n-1);
 else if (n==0) re = 1;
 else re = null;

 return re;
}

document.write('<p>Factorial 8 = '+ factorial(8) +'</p>');
</script>
- This function check first if the 'n' is greater than 0, and if so, 'n' is multiplied by the result returned by auto-calling function with the argument (n-1) and stores the value in a variable, 're'. When 'n' reaches 0, the auto-calling ends, and the function returns the final value stored in the variable 're'.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Functions - scope, arguments and recursive

Last accessed pages

  1. Register and show online users and visitors (25584)
  2. Integer and Float value in Select with PDO from string to numeric (5104)
  3. Follow the mouse cursor with a DIV inside a Parent (2916)
  4. AJAX with POST and PHP (12240)
  5. Insert, Select and Update NULL value in MySQL (30265)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (561)
  2. Read Excel file data in PHP - PhpExcelReader (468)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (344)
  4. PHP getElementById and getElementsByTagName (267)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (254)