Javascript Course


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 tag adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
Functions - scope, arguments and recursive

Last accessed pages

  1. html2canvas - Save page screenshoot on server (4880)
  2. Redirects (4799)
  3. SHA256 Encrypt hash in JavaScript (31203)
  4. PuzzleImg - Script to Create Image Puzzle Game (9406)
  5. Get Time Elapsed (1886)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (322)
  2. Read Excel file data in PHP - PhpExcelReader (117)
  3. The Four Agreements (96)
  4. PHP Unzipper - Extract Zip, Rar Archives (93)
  5. The Mastery of Love (85)
Chat
Chat or leave a message for the other users
Full screenInchide