01/10/2014

JavaScript Scope

In JavaScript, objects and functions, are also variables.
In JavaScript, scope is the set of variables, objects, and functions you have access to.
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function. Local variables have local scopeg. They can only be accessed within the function.
Example:
<script> myFunction(); document.getElementById("demo").innerHTML = "I can display " + typeof carName; function myFunction() { var carName = "Volvo"; } </script>
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL. A global variable has global scope. All scripts and functions on a web page can access it.
Example:
<script> var carName = "Volvo"; myFunction(); function myFunction() { document.getElementById("demo").innerHTML = "I can display " + carName; } </script>
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare car Name as a global variable, even if it is executed inside a function.
Example:
<script> myFunction(); document.getElementById("demo").innerHTML = "I can display " + carName; function myFunction() { carName = "Volvo"; } </script>
The Lifetime of JavaScript Variables
The lifetime of a JavaScript variable starts when it is declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.
Function Arguments
Function arguments "parameters" work as local variables inside functions.
Global Variables in HTML
With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object: All global variables belong to the window object.
Example:
<script> myFunction(); document.getElementById("demo").innerHTML = "I can display " + window.carName; function myFunction() { carName = "Volvo"; } </script>
Did You Know?
Your global variables, or functions, can overwrite window variables or functions.
Anyone, inclusive the window object, can overwrite your global variables or functions.

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it.
Example:
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by aname, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs same rules as variables.
The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {} function Name (parameter1, parameter2, parameter3) { code to be executed }
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked. Inside the function, the arguments are used as local variables. A Function is much the same as a Procedure or a Subroutine, in other programming languages. Function Invocation The code inside the function will execute when something invokes the function:
*When an event occurs when a user clicks a button
*When it is invoked called from JavaScript code
*Automatically self invoked
Function Return
When JavaScript reaches are turn statement, the function will stop executing. If the function was invoked from a statement, JavaScript will return to execute the code after the invoking statement.
Functions often compute are turn value. The return value is returned back to the caller:
Example:
Calculate the product of two numbers, and return the result:
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
Why Functions?
You can reuse code:
Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
Example:
Convert Fahrenheit to Celsius:
<script>
function toCelcius(f)
{
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelcius(32);
</script>
JavaScript Functions are Objects
In JavaScript, functions are objects. JavaScript functions have properties and methods. You can add your own properties and methods to functions.
JavaScript Functions are Variables Too
In JavaScript, functions can be used as variables:
Example:
<script> document.getElementById("demo").innerHTML = "The temperature is " + toCelsius(32) + " Centigrade"; function toCelsius(fahrenheit) { 牋  return (5/9) * (fahrenheit-32); } </script>
JavaScript functions can be redefined like ordinary variables.
JavaScript functions can also be passed as values to other functions.

JavaScript Objects

Objects are just data, with added properties and methods.
Object Properties and Methods
Properties are values associated with objects.
A Real Life Example.
In real life, a car is an object. It has properties like weight and color, and methods like start and stop:
f
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but they are performed at different times.
JavaScript Objects
In JavaScript, objects are data variables with properties and methods. Almost "everything" in JavaScript are treated as objects. Dates, Arrays, Strings, Functions. In JavaScript you can also create your own objects. This example creates an object called "person" and adds four properties to it:
Example:

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var person = {firstName:"John", lastName:"Elwin", age:22, eyeColor:"blue"}; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
Spaces and line breaks are not important.
An object declaration can span multiple lines:
Example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var person = { firstName : "John", lastName : "Elwin", age : 22, eyeColor : "blue" }; document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old."; </script> </body> </html>
There are many different ways to create new JavaScript objects.
You can also add new properties and methods to already existing objects.
Accessing Object Properties
You can access the object properties in two ways:
Example:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Elwin", id : 45**** }; document.getElementById("demo").innerHTML = person.firstName + " " + person["lastName"]; </script> </body> </html>
Accessing Object Methods
You can call an object method with the following syntax: objectName.methodName()
This example uses the fullName() method of a person object, to get the full name:
Example:
<!DOCTYPE html> <html> <body> <p>Creating and using an object method:</p> <p id="demo"></p> <script> var person = { firstName: "John", lastName : "Elwin", id : 45****, fullName : function (){return this.firstName + " " + this.lastName} }; document.getElementById("demo").innerHTML = person.fullName(); </script> </body> </html>
Object methods are ordinary JavaScript functions defined as object properties.
Associative arrays in PHP. Hash tables, hash maps or hashes in C, C++, C#, Java, Perl, and Ruby. Dictionaries in Python.

JavaScript Variables

JavaScript Variables In a programming language and in algebra named variables are used to store data values. JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables just like algebra.
In this example, length is defined as a variable. Then, it is given the value 6:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var length; length = 6; document.getElementById("demo").innerHTML = length; </script> </body> </html>
A literal is aconstant value. A variable is a name. A variable can be assigned variable values.
JavaScript Operators
JavaScript uses arithmetic operators to compute values just like algebra:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = (5 + 6) * 10; </script> </body> </html>
JavaScript uses an assignment operator to assign values to variables like algebra:
<!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var x, y, z; x = 5 y = 6; z = (x + y) * 10; document.getElementById("demo").innerHTML = z; </script> </body> </html>
JavaScript Statements In HTML
JavaScript statements are written as sequences of "executable commands" Statements are separated by semicolons:
x =5+6; y = x *10;
JavaScript Keywords
A JavaScript statement often starts with akeyword. The var keyword tells the browser to create a new variable:
varx =5+6; vary = x *10;
JavaScript Identifiers
All programming languages must identify variables with unique names. These unique names are called identifiers. Identifiers can contain letters, digits, underscores, and dollar signs, but cannot begin with a number. Reserved words like JavaScript keywords cannot be used as identifiers.
JavaScript Comments
Not all JavaScript statements are "executable commands". Anything after double slashes // is treated as comments, ignored, and not executed:
// x = 5 + 6;
Will not be executed In this tutorial, we use colors to highlight reserved words, values, and comments.
JavaScript Data Types
JavaScript variables can hold many data types: numbers, text strings, arrays, objects and much more:
varlength =16; // Number assigned by a number literal varpoints = x *10; // Number assigned by an expression literal varlastName ="Johnelwin"; // String assigned by a string literal varcars = ["Saab","Volvo","BMW"]; // Array assigned by an array literal varperson = {firstName:"John", lastName:"Elwin"}; // Object assigned by an object literal
The Concept of Data Types
In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer can not safely solve this:
16+"Volvo"
Does it make any sense to add "Volvo" to sixteen?
Will it produce an error or a result?
"16Volvo"
You will learn much more about data types in a later chapter.