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().
function ex1() {
 var va = 8;
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.
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)
- 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.
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
- 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:
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);
- 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:
function sumNrs(a=0, b=0, c=0){
 return a + b + c;

var sum1 = sumNrs(1, 2);

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:
The second argument can be access using:
- and so on.

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

Example, a function that returns the sum of any numbers of arguments.
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));

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:

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

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).
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>');
- 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

Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
Click on the "echo" correct instruction.
echo "" echo ""; echo """;
echo "Address URL:";
Functions - scope, arguments and recursive

Last accessed pages

  1. PHP-MySQL free course, online tutorials PHP MySQL code (69086)
  2. Add sounds and audio effects in Flash (3492)
  3. Detect when ScrollBar reaches the bottom of the page (4384)
  4. JQZoom Image Magnifier (12996)
  5. Simple arithmetic calculator in PHP (2104)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (326)
  2. PHP Unzipper - Extract Zip, Rar Archives (86)
  3. Read Excel file data in PHP - PhpExcelReader (82)
  4. The Mastery of Love (78)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (66)