Google
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Event Propagation

When the target of an event is the Window object, or some other standalone object (such as an XMLHttpRequest), the browser responds to an event simply by invoking the appropriate handlers on that one object.
however, when the event target is a Document or document Element,  the situation is different .

Event flow describes the order in which events are received on the page. the IE and Netscape development teams came up with an almost exactly opposite concept of event flow . IE would support an event bubbling flow , whereas Netscape Communicator would support an event capturing flow.

Event Bubbling


After the event handlers registered on the target element are invoked, most events bubble up the DOM tree . The event handlers of the target’s parent are invoked . Then the handlers registered on the target’s grandparent are invoked . This continues up to the Document object, and then beyond to the Window object . Event bubbling provides an alternative to registering handlers on lots of individual document elements : instead you can register a single handler on a common ancestor element and handle events there . You might register an “change” handler on a <form> element, for example, instead of registering a “change” handler for every element in the form.

Most events that occur on document elements bubble . Notable exceptions are the focus, blur, and scroll events. The load event on document elements bubbles, but it stops bubbling at the Document object and does not propagate on to the Window object . The load event of the Window object is triggered only when the entire document has loaded .

Event bubbling is the third “phase” of event propagation. The invocation of the event handlers of the target object itself is the second phase. The first phase, which occurs even before the target handlers are invoked, is called the “capturing” phase.


Consider the following HTML document :

< html >
< head >
< title > Event Propagation < /title >
< /head >
< body >
< div id=”myDiv” > Click Me < /div >
< /body >
< /html >

When you click the < div > element in the page, the click event occurs in the following order :

1. < div >
2. < body >
3. < html >
4. document


Event Capturing


The capturing phase of event propagation is like the bubbling phase in reverse. The capturing handlers of the Window object are invoked first, then the capturing handlers of the Document object, then of the body object, and so on down the DOM tree until the capturing event handlers of the parent of the event target are invoked. Capturing event handlers registered on the event target itself are not invoked.

If the previous example is used with event capturing, clicking the < div > element fires the click event in the following order :

1. document
2. < html >
3. < body >
4. < div >

Recall that addEventListener() takes a boolean value as its third argument. If that argument is true, the event handler is registered as a capturing event handler for invocation during this first phase of event propagation.
Event bubbling is universally supported: it works in all browsers including IE, and it works for all handlers, regardless of how they are registered (unless they are registered as capturing event handlers).
Event capturing only works with event handlers registered with addEventListener() when the third argument is true. This means that event capturing is not available in IE prior to IE9 .

DOM Event Flow


The event flow specified by DOM Level 2 Events has three phases: the event capturing phase, at the target, and the event bubbling phase. Event capturing occurs first, providing the opportunity to intercept events if necessary. Next, the actual target receives the event. The final phase is bubbling, which allows a final response to the event. Considering the simple HTML example used previously, clicking the < div > fires the event in the order

1. document
2. < html >
3. < body >


In the DOM event flow, the actual target (the < div > element) does not receive the event during the capturing phase. This means that the capturing phase moves from document to < html > to < body > and stops.

4. < div >
5. < body >
6. < html >
7. document


The next phase is “ at target ,” which fires on the < div > and is considered to be part of the bubbling phase in terms of event handling . Then, the bubbling phase occurs and the event travels back up to the document.


Handler Return Value


The return value of an event handler registered by setting an object property or an
HTML attribute is sometimes significant. In general, a return value of false tells the
browser that it should not perform the default action associated with the event. The
onclick handler of a Submit button in a form, for example, can return false to prevent
the browser from submitting the form. (This is useful if the user’s input fails client-side
validation.)
In browsers that support addEventListener(), you can also cancel the default action for an event by invoking the preventDefault() method of the event object .
In IE prior to IE9, however, you do the same by setting the returnValue property of the event object to false.

Event Cancellation


The following code shows a dummy event handler that uses all three cancellation techniques:

function cancelHandler(event) {
var event = event || window.event; // For IE

/* Do something to handle the event here */

// Now cancel the default action associated with the event
if (event.preventDefault) event.preventDefault();      // Standard technique
if (event.returnValue) event.returnValue = false;        // IE
return false;                    // For handlers registered as object properties
}

Canceling the default action associated with an event is only one kind of event cancellation.
We can also cancel the propagation of events.
In browsers that support addEventListener(), the event object has a stopPropagation() method that you can invoke to prevent the continued propagation of the event. If there are other handlers defined on the same object, the rest of those handlers will still be invoked, but no event handlers on any other object will be invoked after stopPropagation() is called. The stopPropagation() method can be called at any time during event propagation. It works during the capturing phase, at the event target itself, and during the bubbling phase.

Prior to IE9, IE does not support the stopPropagation() method. Instead, the IE event object has a property named cancelBubble. Set this property to true to prevent any further propagation. IE8 and before do not support the capturing phase of event propagation, so bubbling is the only kind of propagation to be canceled.

Events



the web browser generates an event whenever something happens to the document or browser or to some element or object associated with it . For example, the web browser generates an event when it finishes loading a document, or when the user moves the mouse over a link .


The event type, or event name , is a string that specifies what kind of event occurred .  for example, the type “load” means that a document has finished loading . this name is used to identify the specific kind of event we’re interested in .

Events also have a target, which is the object on which they occurred. When we speak of an event, we must specify both the event type (the name) and the target, for example : 
a click event on an HTMLButtonElement object , or a readystatechange event on an XMLHttpRequest object.
or in other words :
A load event on a Window, or a click event on a <button> Element.

If we want our program to respond to an event, we write a function known as an “event handler,” “event listener,” or  “callback” . Programs register this function , specifying an event type and an event target . so that it is invoked (“fired”, “triggered”, or “dispatched” the event)when the event occurs. 

this can be done using HTML attributes, but this is discouraged. 

Handling Events via HTML Attributes
 
<html> 
<head>
<title>JavaScript</title> 
<script language="JavaScript"
type="text/javascript">
function showText() { 
window.alert("Welcome to JavaScript!");
} 
</script> 
</head> 
<body onload="showText();"> 
</body> 
</html>


Instead, the simplest way to register an event handler is usually to assign a JavaScript function to a property of the target object, with code like this :


window.onload = function() { ... };
document.getElementById("mid").onclick = function() { ... };


var btn = document.getElementById(“myBtn”); 
btn.onclick = function(){ alert(this.id); };
// alerts -> myBtn
 
function handleResponse() { ... }
request.onreadystatechange = handleResponse;







two methods to deal with the assignment and removal of event handlers: 

addEventListener() and removeEventListener() .

These methods accept three arguments:
the event name to handle,
the event handler function,
and a Boolean value indicating whether to call the event handler during the capture phase ( true ) or during the bubble phase ( false ).

To add an event handler for the click event on a button :

var btn = document.getElementById(“myBtn”);
btn.addEventListener(“click”,
                                       function(){ alert(this.id); },
                                       false);


IE implements methods similar to the previous ones called attachEvent() and detachEvent() . These methods accept the same two arguments: the event handler name and the event handler function. Since IE only supports event bubbling, event handlers added using attachEvent() are attached on the bubbling phase.

To add an event handler for the click event on a button using attachEvent() :

var btn = document.getElementById(“myBtn”);
btn.attachEvent(“onclick”, function(){ alert(“Clicked”); });

Note that the first argument of attachEvent() is “ onclick ” as opposed to “ click ” in the  addEventListener() method.

Synchronous, Asynchronous, and Deferred Scripts

Synchronous, Asynchronous, and Deferred Scripts


When JavaScript was first added to web browsers, there was no API for traversing and manipulating the structure and content of a document. The only way that JavaScript
code could affect the content of a document was to generate that content on the fly while loading the document. using the document.write() method.



When a script passes argument to document.write(), this argument is added to the document input stream . The use of document.write() is no longer considered good style, but it is still possible and this fact has an important implication. 

When the HTML parser encounters a <script> element, it must, by default, run the script before it can resume parsing and rendering the document. This is not much of a problem for inline scripts, but if the script source code is in an external file specified with a src attribute, this means that the portions of the document that follow the script will not appear in the browser until the script has been downloaded and executed.



This synchronous or blocking script execution is the default only. The <script> tag can have defer and async attributes, which (in browsers that support them) cause scripts
to be executed differently. 

These are boolean attributes, they don’t have a value, they just need to be added to the <script> tag :

<script defer src="deferred.js"></script>
<script async src="async.js"></script>


Both the defer and async attributes are ways of telling the browser that the linked script does not use document.write() and won’t be generating document content, and that
therefore the browser can continue to parse and render the document while downloading the script. The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. 


The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded. If a <script> tag has both attributes, a browser that supports both will honor the async attribute and ignore the defer attribute.



Note that deferred scripts run in the order in which they appear in the document. Async scripts run as they load, which means that they may execute out of order.

At the time of this writing, the async and defer attributes are not yet widely implemented, and they should be considered optimization hints only: your web pages should be designed to work correctly even if deferred and asynchronous scripts are executed synchronously.


You can load and execute scripts asynchronously, even in browsers that do not support the async attribute, by dynamically creating a <script> element and inserting it into the document.



<h1>Table of Factorials</h1>
<script>
function factorial(n) {

if (n <= 1) return n;
else return n*factorial(n-1);
}
document.write("<table>"); // Begin an HTML table
document.write("<tr><th>n</th><th>n!</th></tr>"); // Output table header
for(var i = 1; i <= 10; i++) { // Output 10 rows
document.write("<tr><td>" + i + "</td><td>" + factorial(i) + "</td></tr>");
}
document.write("</table>"); // End the table
document.write("Generated at " + new Date()); // Output a timestamp
</script>



Events


The JavaScript program above is a synchronous one : 
it starts running when the page loads, produces some output, and then terminates. This kind of program is very uncommon today. Instead, we write programs that register event handler functions. These functions are then invoked asynchronously when the events occur.
  

Boolean Operators


Boolean Operators


Boolean operators help manage true and false values. They are most useful in if statements and the like, but they also have some interesting uses in and of themselves.

Logical NOT: !


The logical NOT operator turns a “truth” value into false and a false value into true. It’s another way of determining inequality. These two if statements operate identically :

if (myVar != true) {
// It's not true
}

if (! myVar) {
// It's still not true
}

It’s useful for determining that something isn’t true or that it’s missing.

var element = document.getElementById("myId");
if (! element) {
console.log("The element does not exist");
}

Logical AND: &&


The logical AND operator (&&) takes two operands. It returns the right operand only if the left operand is  truth.  If the left operand is false , it returns that value.

var tValue = 1;
var fValue = null;

true && tValue;   //   1

fValue && tValue;   //   null

The interesting thing about the logical AND operator is that it stops evaluating
and immediately returns if the left operand is “falsey.” Consider this example :

function myFunc() {
alert("executing myFunc!");
return true;
}

falseyValue && myFunc();  //  null

Because the left operand is “falsey,” the expression stops there and doesn’t execute myFunc(). In this case, you’ll never see the alert dialog box. This is useful for safeguarding yourself against potential errors. JavaScript will throw an error if you try to access a property on null.

var element = document.getElementById("doesNotExist");
element.nodeName;
TypeError: element is null
element && element.nodeName;
null
var element2 = document.getElementById("exists");
element2 && element2.nodeName;
"DIV"

Evaluating the nodeName property of a nonexistent element returns an error, but you can quickly determine whether the element exists with the logical AND operator.

Logical OR: ||


The logical OR operator (||) returns the left operand if it’s true, and the right operand otherwise. You can think of it as “Keep trying until you find the truth (or something like it).”

fValue || tValue;    // Second value
1
tValue || fValue;    // First value
1
false || fValue || anotherFalseValue || tValue;
1

Combining Boolean Operators


The fun part of Boolean operators comes from combining them to create complex logical expressions.

var element = document.body.firstChild;
if (element &&
(element.nodeName === "DIV" ||
element.nodeName === "SPAN") &&
element.childNodes.length) {
alert("All of these expressions are true");
}

Learning to read and write complex expressions like this is a challenge,
but it just amounts to understanding the smaller expressions one at a
time. Sometimes it helps to store some of the smaller expressions on
variables to enhance readability.

var isDiv = element && element.nodeName === "DIV"
var isSpan = element && element.nodeName === "SPAN";
var isDivOrSpan = isDiv || isSpan;
if (isDivOrSpan && element.childNodes.length) {
alert("All of these expressions are true");
}

Coding often requires balancing the number of lines and the readability of the code.


Ternary Expressions


Ternary expressions are a slightly more efficient way to manage values based on booleans. they let you write a basic if/else statement in one line of code.

result = expression ? "it's true" : "it's false";

This expression is equivalent to the following:

if (expression) {
result = "it's true";
} else {
result = "it's false";
}


Expressions

An expression is a phrase of JavaScript that a JavaScript interpreter can evaluate to
produce a value. JavaScript code is made up mostly of expressions in various forms.
A variable name is a simple expression that evaluates to the value assigned to that variable.

Complex expressions are built from simpler expressions.The most common way to build a complex expression out of simpler expressions is with an operator.
using the multiplication operator * , The expression x * y evaluates to the product of the values of the expressions x and y.


in firebug , enter the following expression, it outputs the resulting value :

1 + 2; // 3

Primary Expressions


primary expressions,  do not include any simpler expressions. Primary expressions in JavaScript are constant or literal values, certain language keywords, and variable references.

examples

1.23               // A number literal
"hello world"           // A string literal
/pattern/        // A regular expression literal
true               // Evalutes to the boolean true value
false             // Evaluates to the boolean false value
null                 // Evaluates to the null value
this                 // Evaluates to the "current" object
i                      // Evaluates to the value of the variable i.
undefined      // undefined is a global variable


Compound Expressions


You can combine any number of values and operators to create complex compound expressions. Different data types work with various operators in specific ways. we will cover important operators for Numbers, Strings, and Arrays, but since all values are true or false, it’s useful to cover the Boolean operators on their own.


Boolean Operators

operators

Operators are symbols, such as +, –, =, >, and <, that produce a result based on some rules. Data manipulated by an  operator called operands; for example, 5 and 4 are operands in the expression 5 + 4. Operators and operands create expressions. An expression combines a group of values to make a new value, x = 5 + 4.

operators can be categorized by number of operands :
operators manipulate two operands, are called a binary operators.
If there is only one operand, the operator is called a unary operator.
If there are three operands, it is called a ternary  operator.

 The operands can be either strings, numbers, Booleans, or a combination of these.

Precedence and Associativity

the following table is organized by operator precedence. 
The operators listed first have higher precedence than those listed last. 
with background color separating groups of operators at the same precedence level. 
The column labeled A gives the operator associativity, 
which can be L (left-to-right) or R (right-to-left), 
and the column N specifies the number of operands

Operator
Operation
A
N
++


- -


-

+

~

!


delete


typeof


void
Pre- or post-increment

Pre- or post-decrement

Negate number

Convert to number

Invert bits

Invert boolean value

Remove a property

Determine type of operand

Return undefined value
R


R


R

R

R

R


R


R


R
1


1


1

1

1

1


1


1


1






















*, /, %
Multiply, divide, remainder
L
2

+, -

+
Add, subtract

Concatenate strings
L

L
2

2



<<

>>


>>>
Shift left

Shift right with sign extension

Shift right with zero extension
L

L


L
2

2


2






<, <=,>, >=


<, <=,>, >=


instanceof

in
Compare in numeric order

Compare in alphabetic order

Test object class

Test whether property exists
L


L


L

L
2


2


2

2









= =

!=

= = =


!= =
Test for equality

Test for inequality

Test for strict equality

Test for strict inequality

L

L

L


L
2

2

2


2








&
Compute bitwise AND
L
2

^
Compute bitwise XOR
L
2

|
Compute bitwise OR
L
2

&&
Compute logical AND
L
2

||
Compute logical OR
L
2

?:
Choose 2nd or 3rd operand
R
3

=



*=, /=, %=, +=,
-=, &=, ^=, |=,
<<=, >>=, >>>=
Assign to a variable or property

Operate and assign
R



R
2



2





,
Discard 1st operand, return second
L
2



Example :

The order of associativity is from left to right. 
Multiplication and division are of a higher precedence than addition and subtraction, and addition and subtraction are of higher precedence than assignment. 
To illustrate this, we'll use parentheses to group the operands as they are grouped by JavaScript. In fact, if you want to force precedence, use the parentheses around the expression to group the operands in the way you want them evaluated. 
The following two examples produce the same result:

var r = 1 + 2 * 3 / 4;  // 2.5
 
could be written

var r = (1 + ( ( 2 * 3 ) / 4));  // 2.5
 
The expression is evaluated and the result is assigned to variable r. 
 

Statements

statements are JavaScript sentences or commands.

A JavaScript program is simply a sequence of statements, terminated and separated from one another with semicolons, to execute. once you are familiar with the statements of JavaScript, you can begin writing JavaScript programs.

By default, the JavaScript interpreter executes these statements one after another in the order they are written. Another way is to alter this default order of execution, and JavaScript has a number of  Branching statements enable you to make choices  or control structures that allows you to control the flow of your program in three ways :

• Conditionals are The decision-making constructs  ( if,   if/else,  if/elseif,   switch ) statements  that make the JavaScript interpreter execute or skip other statements depending on the value of an expression.

• The looping constructs ( while, do...while ,  for ) are statements that execute other statements repetitively until some condition is met.

• Jumps are statements like break, return, and throw that cause the interpreter to jump to another part of the program.

functions

What Is a Function?

A pocket calculator performs certain functions. You push the buttons, provide information to the calculator, it performs a calculation, and returns the results. 
That's what a function does.

By definition, a function is a block of statements that performs a specific task such as  validating input, and also can return a value to the caller . A function is independent of your program and not executed until invoked by a caller. 
They are also used to break up a program into smaller units to keep it better organized and easier to maintain , and can be used over and over again and thus save you time .
 JavaScript has a large number of its own built-in functions, and you can create your own too .

when using the term method you refer to a normal function that is used with objects .

Function Declaration and Invocation


Functions must be declared before they can be used. 
To define a function, the function keyword is used, and followed by the name of the function, then a set of parentheses  () , which sometimes are used to hold parameters, values that are received by the function. The function's statements are enclosed in curly braces.

Format :


function sayHello() 
{
 alert("Hello");
}

functions are invoked by calling the function, for example :

sayHello();

 functions may have arguments :

function sayWhat(g, user) 
{
 alert(g + " " + user );
} 

 when we call it we provide these arguments :

sayWhat("Hello", "admin");

the output is dialog box containing : Hello admin

Note : read about Scope of Variables  here 

Return Values


Functions may return values with a return statement. The return keyword is optional . A return can be used to send back the result of some task, such as a calculation, or to exit a function early if some condition occurs.

Format :


return;
return expression; 
 
 Example :
 
function sum (a, b) {
var result= a + b;
return result;
} 
 
 
the return value can be assigned to a variable in function call 

var total=sum(1, 2);
 
the sum function is called with two arguments, 5 and 10. The sum function's return value (3) will be assigned to the variable total.



 
 

if - switch

the if statement enables you to execute a series of statements if a test condition is true.

Here's what the syntax of this statement looks like,note that the code to execute is between curly braces, { and } :

Format :


if (condition){
// statements;
} 
The if statement also includes an optional else clause .
The if evaluates the expression, that is test condition, in parentheses, 
and if the expression evaluates to true, the block after the opening curly
braces is executed; otherwise the block after the else is executed.
 

Format :

 
if (condition){
// statements1;
}
else{
// statements2;
}
 
 
if/else if
 

Format :

 
if (condition) {
// statements1;
}
else if (condition) {
// statements2;
}
else if (condition) {
// statements3;
}
else{
// statements4;
} 
 
If the first conditional expression following the if keyword is true, the  block of statements following the expression are executed and control starts after the whole if statement. 
Otherwise, if the conditional expression following the if keyword is false, control branches to the first else if and the expression following it is evaluated. If that expression is true, the  block of statements following it are executed, and if false, the next else if is tested. 

All if/else if statements are tested and if none of their expressions are true, control goes to the else statement. Although the latter else is not required, it serves as a default action if all previous conditions were false.
 
 

The switch Statement

This statement enables you to evaluate an expression and match the expression's 
value to a number of test values, and the code will be executed 
when a match is found. 
You place the expression to evaluate in parentheses after the switch 
keyword, and the test values you want to match in a set of case statements. 
If a match found,the code in that case statement is executed,
and a break statement ends the switch statement. 
 

Format :

 
 
switch (expression){
case label1:
// statements
break;
case label2:
// statements
break;
// ...
[default:
statements]
} 
 
Note , If the value of the expression doesn't match any test value, the code in the default statement, which is optional, is executed. 
If you include a default statement, it should be the last statement .

loops

Loops are used to execute a segment of code repeatedly until some condition is met. JavaScript's looping constructs are : while - do...while - for.

 

The while Loop

The while statement executes its statement block as long as the expression after the while evaluates to true, that is . If the condition never changes and is true, the loop will iterate forever (infinite loop). If the condition is false control goes to the statement right after the closing curly brace of the loop's statement block.

 Format :


while (condition) {
statements;
increment/decrement counter;
} 
 
 

The do/while Loop

The do/while statement executes a block of statements repeatedly until a condition becomes false.  this loop executes the statements in the body of the loop at least once before testing its expression .

 Format :


do
{ statements;}
while (condition); 
 
 

The for Loop

The for loop consists of the for keyword followed by three expressions separated by semicolons and enclosed within parentheses. 
The first expression is used to set the initial value of variables and is executed just once, the second expression is used to test whether the loop should continue or stop, and the third expression updates the loop variables; that is, it increments or decrements a counter, which will usually determine how many times the loop is repeated .

Format :


for(Expression1;Expression2;Expression3) 
{
statement(s);
} 



variables

Variables are containers that hold data such as numbers and strings.
Variable names consist of any number of letters ,  underscore and digits. The first letter must be a letter or an underscore.
Variable names are case sensitive; e.g., Name, name, and NAme are all different variable names.

Declaring and Initializing Variables

Variables must be declared before they can be used. There are two ways to declare a variable: either explicitly preceded by the keyword var, or not.  it is a better practice to always use the var keyword.  You can assign a value to the variable (or initialize a variable) when you declare it, but it is not mandatory, unless you omit the var keyword. If a variable is declared but not initialized, it is "undefined."


Scope of Variables

Scope describes where a variable is visible, or where it can be used, within the program. JavaScript variables are either of global or local scope. A global variable can be accessed from any JavaScript script on a page .

Local variables are created when a variable is declared within a function. Local variables must be declared with the keyword, var. They are accessible only from within the function from the time of declaration to the end of the enclosing block, and they take precedence over any global variable with the same name .

Data Types

Computers process information, by process, we mean the information is modified , filtered in some way . In computing the information is reffered to as data.

JavaScript supports a number of fundamental data types , These types can be broken down into two categories, primitive data types and composite data types.
 

Primitive Data Types

 Primitive data types are the simplest building blocks of a program.
numeric (1.50) , strings ("hello,world') , boolean (true, false)

there are two other special types that consist of a single value:
 Null , Undefined

Numeric literals

JavaScript supports both integers and floating-point numbers.

Integers are whole numbers ; e.g., 123 and –1. Integers can be expressed in decimal (base 10), octal (base 8), and hexadecimal (base 16), and are either positive or negative values.

Floating-point numbers are fractional numbers such as 123.45 or –1.5 .

String literals

String literals are characters enclosed in either double or single quotes. The quotes must be matched. If the string starts with a single quote, it must end with a matching single quote, and likewise if it starts with a double quote, it must end with a double quote. Single quotes can hide double quotes, and double quotes can hide single quotes:

"a string"
' another string' "
This is 'a string' "
'This is "a string" '
"5"

Strings can contain escape sequences (a single character preceded with a backslash),
 as follows:


 \'      single quotation mark
\"      double quotation mark
\n      new line
 \\      BackSlash


 Strings Concatenation

 this is the process of joining strings together, using a plus sign + . Its operands are two strings. If one string is a number and the other is a string, JavaScript will still concatenate them as strings. If both operands are numbers, the + will be the addition operator.

alert("java" + "script");
alert(5+5);
alert("5" + 5);


Booleans

Boolean literals are logical values that have only one of two values, true or false. You can think of the values as yes or no, on or off, or 1 or 0.

 if (a == false) { code; }


 Null

the null keyword represents no value  or "nothing," not even an empty string or zero .

Undefined

A variable that has been declared, but given no initial value, contains the value undefined and will produce a runtime error if you try to use it.

If you declare the variable and assign null to it, null will act as a placeholder and you will not get an error.

The typeof Operator

The typeof operator returns a string to identify the type of its operand (i.e., a variable, string, or object). You can use the typeof operator to check whether a variable has been defined because if there is no value assigned to the variable, the typeof operator returns undefined.

typeof (operand)

 Example:  
 typeof(54.6)
 typeof(str)
 typeof("str")

Composite Data Types

also called complex types, consist of more than one component. Objects, arrays, and functions,  all contain a collection of components. Objects contain properties and methods; arrays contain a sequential list of elements; and functions contain a collection of statements.

JavaScript Pseudo URLs



Using JavaScript Pseudo URLs / pseudoprotocol


<a href="javascript:window.alert('Welcome to JavaScript!'):">click here </a>


Another way to call JavaScript code is to use a pseudo URL. When a URL that begins with javascript: is loaded, the code behind that is executed .

There are several ways to use such a URL in the form of an image, a link, or a CSS style but usually it's the link you will want to use. Note, however, that such a link obviously works only with a browser that supports JavaScript and has it activated.


Warning

When the code after the javascript: URL prefix returns something, the result is printed to the screen. Usually, this is not desirable. You can use the special JavaScript function void() to avoid this:


javascript:void(code_that_would_return_something());



you can use the URL pseudoprotocol, javascript: followed by any valid JavaScript expression or expressions separated by semicolons. The result of the expression is returned as a string to your browser window .


javascript:1+3



Lexical Structure

Case Sensitivity


JavaScript is a case-sensitive language. This means that you must pay attention to your uppercase and lowercase letters.
all language keywords, variables, function names, and other identifiers must always be typed with a consistent capitalization of letters.
as examples,
 javascript is not the same as javaScript .
the "for" keyword must be typed "for" not "For" or "FOR" .
Also, you must refer to built-in objects with the proper casing. Date start with uppercase letters, but not window. Most built-in methods are combined words by capitalizing all but the first,
such as getElementById (often referred to as camelCase).

Note, however, that HTML is not case-sensitive (although XHTML is). Because of its
close association with client-side JavaScript, this difference can be confusing. Many
client-side JavaScript objects and properties have the same names as the HTML tags
and attributes they represent. While these tags and attribute names can be typed in any
case in HTML, in JavaScript they typically must be all lowercase. For example, the
HTML onclick event handler attribute is sometimes specified as onClick in HTML, but
it must be specified as onclick in JavaScript code (or in XHTML documents).


Comments


Comments are an important  even though they don’t actually do anything. They are helpful hints for people who read the program.

JavaScript supports two styles of comments.
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript. Any text between the characters /* and */ is also treated as a comment; these comments may span multiple lines but may not be nested.

Single-line comments :


// This is a single-line comment
return true; // Comment after code

Multiline comments :


/* This comment can wrap
into the next line
 this comment has multiple lines.
 */

Whitespace and New Lines


Most whitespace such as spaces, tabs, and empty lines is ignored in JavaScript and you can them to format and indent your program to make  the code easy to read and understand.


Semicolons


JavaScript statements should end with semicolon (;).
Technically they are optional, but that’s only because JavaScript interpreters add them automatically at the end of most lines.It’s best to get into the habit of adding the semicolons yourself because there can be strange side effects when you let the interpreter do it for you.

In JavaScript, you can usually omit the semicolon between two statements if those statements are written on separate lines. (You can also omit a semicolon at the end of a program or if the next token in the program is a closing curly brace }.) Many JavaScript programmers  use semicolons to explicitly mark the ends of statements, even where they are not required.



Reserved Words

JavaScript reserves certain words for specific uses, so be careful to avoid the following unless you mean to use them:


break    -    case    -   catch    -  continue    -  default

delete     -  do    -   else   -    finally  -     for   -   function

if  -  in  -  instanceof  - new - return - switch - this - throw

try   -   typeof   -   var   -   void   -    while   -    with


You should also avoid these words because they may be used in futureversions of JavaScript:


abstract    -   boolean   -  byte   -    char   -   class    -   const

debugger   -    double   -    enum   -   export   -   extends

final    -    float    -   goto    -   implements    -   import

int    -    interface    -   long    -   native   -   package   -   private

protected   -   public   -   short   -   static   -   super   -  synchronized

throws   -   transient   -   volatile


These words refer to useful objects in the language and Web pages, so be careful not to redefine them with your own values:


arguments  -   Array   -   Boolean   -   Date   -   decodeURI

decodeURIComponent   -   encodeURI   -   Error   -   escape

eval   -   EvalError   -   Function   -   Infinity   -    isFinite

isNaN   -   Math   -   NaN   -   Number   -   Object

parseFloat   -   parseInt   -   RangeError   -   ReferenceError

RegExp   -   String   -   SyntaxError   -   TypeError

undefined   -   unescape   -   URIError

Load JavaScript



Including JavaScript Code


JavaScript code could be included two ways: 
either embedded into an HTML page, or in an external file.

embedded


<script type="text/javascript">
window.alert("Welcome to JavaScript!");
</script>


You can place this <script> element anywhere, and the code is will be executed after this part of the HTML page has been loaded .

External JavaScript Files

Relative URL :
<script language="JavaScript" type="text/javascript"   src="jquery.js"></script>  

Absolute URL :  

<script language="JavaScript"    type="text/javascript"    src="http://hostname/jquery.js"> </script>
The external file contains only the JavaScript code, no <script> elements . however, A <script> element is used to load the external file .
 The src attribute holds the URL of the external script , and could be relative or absolute URLs .

Dynamically Loading JavaScript Files

Sometimes it is necessary to load JavaScript code on demand, while a site is running. For instance, depending on user input, a specific external JavaScript file must be loaded.

One attempt is to use document.write()  to dynamically add a new <script> element to the page. However, this fails with some browsers and also is not considered good style. 

A better solution is to use DOM. First, you create a new <script> element and set the appropriate attributes. Then, you add this element to the page's DOM . Usually, the code is put in the <head> section of the page. The following shows the complete code; note that there actually is a <head> element so that the code works.


<script language="JavaScript" type="text/javascript">

var e = document.createElement("script");
e.setAttribute("type", "text/javascript");
e.setAttribute("language", "JavaScript");
e.setAttribute("src", "jquery.js");
document.getElementsByTagName("head")[0].appendChild(e);

</script>