Javascript Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

http://www.tutorialspoint.com/javascript/javascript_operators.htm http://webcheatsheet.com/javascript/variables.php http://www.wikihow.com/Declare-a-Variable-in-Javascript http://forums.asp.net/t/1648614.

aspx/1

JavaScript
JavaScript is a cross-platform, object-oriented scripting language invented in web browsers to make web pages more dynamic and give feedback to your user. Adding JavaScript to your HTML code allows you to change completely the document appearance, from changing text, to changing colors, or changing the options available in a drop-down list, or switching one image with another when you roll your mouse over it and much more. JavaScript is mainly used as a client side scripting language. This means that all the action occurs on the client's side of things. When a user requests an HTML page with JavaScript in it, the script is sent to the browser and it's up to the browser to do something with it. In fact, JavaScript is often used to perform operations that would otherwise encumber the server, like form input validation. This distribution of work to the relatively quick client-side service speeds up the process. What can JavaScript do?

Display information based on the time of the day JavaScript can check the computer's clock and pull the appropriate data based on the clock information. Detect the visitor's browser JavaScript can be used to detect the visitor's browser, and load another page specifically designed for that browser. Control Browsers JavaScript can open pages in customized windows, where you specify if the browser's buttons, menu line, status line or whatever should be present. Validate forms data JavaScript can be used to validate form data at the client-side saving both the precious server resources and time. Create Cookies JavaScript can store information on the visitor's computer and retrieve it automatically next time the user visits your page.

Add interactivity to your website JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on a button. Change page contents dynamically JavaScript can randomly display content without the involvement of server programs. It can read and change the content of an HTML elements or move them around pages.

How to implement Javascript to an HTML page <html> <head> <title>My First Script</title> </head> <body> <script type="text/javascript"> <!-//--> </script> </body> </html>

<html> <head> <title>My First Script</title> </head> <body> <h1>My First Script</h1> <script type="text/javascript"> <!-var today = new Date()

document.write("What a <b>wonderfull</b> day! Today is "); document.write(today) //--> </script> </body> </html>

JavaScript Variables:

A variable's purpose is to store information so that it can be used later. A variable is a name, or identifier, that represents some data that you set. JavaScript is an untyped language. This means that JavaScript variables can hold data of any valid type.
It takes its type from the data type of what it is holding. You cannot declare a type for variables in JavaScript. There is no facility for saying this variable must be a string, or this one must be a number. JavaScript also converts types as needed, automatically and behind the scenes.

Declaring the variables


You declare variables in JavaScript with the var keyword. You can declare multiple variables at once. You can also declare a variable and assign it a value at the same time. Until you assign a value to a variable it is undefined.
If you try to declare a variable that already exists, JavaScript will treat it as a simple assignment statement and assign any new value in the declaration statement to the variable. If the duplicate declaration has no assignment, then nothing happens. If you try to assign a value to a non-existent variable, JavaScript will create the variable for you. <script type="text/javascript"> myText = "Have a nice day!";

myNum = 5; //Note that myText is a string and myNum is numeric. //Next we will display these to the user. document.write(myText); //To concatenate strings in JavaScript, use the '+' operator document.write("My favourite number is "+ myNum); </script>

JavaScript Variable Scope:


The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code. Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

<script type="text/javascript"> <!-var x= 45; // Declare a global variable function checkscope( ) { var y = "local"; // Declare a local variable document.write(x); } //--> </script>

Operators

What is an operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. JavaScript language supports following type of operators.

Arithmetic Operators Comparision Operators Logical (or Relational) Operators Assignment Operators Conditional (or ternary) Operators

Lets have a look on all operators one by one.

The Arithmatic Operators:


There are following arithmatic operators supported by JavaScript language: Assume variable A holds 10 and variable B holds 20 then: Operator + * / Adds two operands Subtracts second operand from the first Multiply both operands Divide numerator by denumerator Modulus Operator and remainder of after an integer division Description Example A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2

B % A will give 0

++

Increment operator, increases integer value by one A++ will give 11

--

Decrement operator, decreases integer value by one

A-- will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10". To understand these operators in better way you can Try it yourself. <html> <body> <script type="text/javascript"> <!-var a = 33; var b = 10; var c = "Test"; var linebreak = "<br />"; document.write("a + b = "); result = a + b; document.write(result); document.write(linebreak); document.write("a - b = "); result = a - b; document.write(result); document.write(linebreak); document.write("a / b = "); result = a / b; document.write(result); document.write(linebreak); document.write("a % b = "); result = a % b; document.write(result); document.write(linebreak); document.write("a + b + c = "); result = a + b + c; document.write(result); document.write(linebreak);

a = a++; document.write("a++ = "); result = a++; document.write(result); document.write(linebreak); b = b--; document.write("b-- = "); result = b--; document.write(result); document.write(linebreak);

//--> </script> <p>Set the variables to different values and then try...</p> </body> </html> Output: a + b = 43 a - b = 23 a / b = 3.3 a%b=3 a + b + c = 43Test a++ = 33 b-- = 10

The Comparison Operators:


There are following comparison operators supported by JavaScript language Assume variable A holds 10 and variable B holds 20 then: Operator Description Example

==

Checks if the value of two operands are equal or not, if yes then condition becomes true. Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A == B) is not true.

!=

(A != B) is true.

>

(A > B) is not true.

<

(A < B) is true.

>=

(A >= B) is not true.

<=

(A <= B) is true.

To understand these operators in better way you can Try it yourself.

The Logical Operators:


There are following logical operators supported by JavaScript language Assume variable A holds 10 and variable B holds 20 then: Operator Description Called Logical AND operator. If both the operands are non zero then then condition becomes true. Example

&&

(A && B) is true.

||

Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

(A || B) is true.

!(A && B) is false.

To understand these operators in better way you can Try it yourself.

The Bitwise Operators:


There are following bitwise operators supported by JavaScript language Assume variable A holds 2 and variable B holds 3 then: Operator Description Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments. Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments. Example

&

(A & B) is 2 .

(A | B) is 3.

Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either (A ^ B) is 1. operand one is true or operand two is true, but not both. Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand. Called Bitwise Shift Left Operator. It moves all bits

(~B) is -4 .

<<

(A << 1) is 4.

in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc. Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, (A >> 1) is 1. the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is equivalent to integer division by 4, and so on. Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero,

>>

>>>

(A >>> 1) is 1.

To understand these operators in better way you can Try it yourself.

The Assignment Operators:


There are following assignment operators supported by JavaScript language: Operator Description Simple assignment operator, Assigns values from right side operands to left side operand Add AND assignment operator, It adds right operand to the left operand and assign the result Example C = A + B will assigne value of A + B into C C += A is equivalent to C = C + A

+=

to left operand Subtract AND assignment operator, It subtracts right operand from the left operand and assign the C -= A is equivalent to C = C - A result to left operand Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

-=

*=

C *= A is equivalent to C = C * A

/=

C /= A is equivalent to C = C / A

%=

C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

Miscellaneous Operator
The Conditional Operator (? :) There is an oprator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax: Operator Description Example If Condition is true ? Then value X : Otherwise value Y

?:

Conditional Expression

To understand this operator in better way you can Try it yourself.

The typeof Operator

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand .
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation. Here is the list of return values for the typeof Operator : Type Number String Boolean Object Function Undefined Null String Returned by typeof "number" "string" "boolean" "object" "function" "undefined" "object"

<html> <body>

<script type="text/javascript"> <!-var a = 10; var b = "ramu"; var linebreak = "<br />"; result = (typeof b == "ramu" ? "B is String" : "B is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); //--> </script> <p>Set the variables to different values and different operators and then try...</p> </body> </html>

JavaScript Functions
A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

Defining Functions Invoking Functions

Defining functions In JavaScript a function is defined as follows:


<script type="text/javascript"> function function_name (argument_1, ... , argument_n) { statement_1; statement_2; ... statement_m; return return_value; }

</script>

<html> <head> <script type="text/javascript"> function showmessage() { alert("WebCheatSheet - JavaScript Tutorial!"); } </script> </head> <body> <form name="myform"> <input type="button" value="Click me!" onclick="showmessage()"> </form> </body> </html>

JavaScript Functions
Function:
A function contains some code that will be executed by an event or a call to that function. A function is a set of statements. You can reuse functions within the same script, or in other documents. You define functions at the beginning of a file (in the head section), and call them later in the document. It is now time to take a lesson about the alert-box: This is JavaScript's method to alert the user.
alert("here goes the message")

How to Define a Function


To create a function you define its name, any values ("arguments"), and some statements:

function myfunction(argument1,argument2,etc) { some statements


}

A function with no arguments must include the parentheses:


function myfunction() { some statements }

Arguments are variables that will be used in the function. The variable values will be the values passed on by the function call. By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called. Some functions return a value to the calling expression

function result(a,b) { c=a+b return c }

How to Call a Function


A function is not executed before it is called. You can call a function containing arguments:
myfunction(argument1,argument2,etc)

or without arguments:
myfunction()

The return Statement


Functions that will return a result must use the "return" statement. This statement specifies the value which will be returned to where the function was called from. Say you have a function that returns the sum of two numbers:

function total(a,b) { result=a+b return result }

When you call this function you must send two arguments with it:
sum=total(2,3)

The returned value from the function (5) will be stored in the variable called sum.

Examples
Function How to call a function.
<html> <head> <script type="text/javascript"> function myfunction() { alert("HELLO") } </script> </head> <body> <form> <input type="button" onclick="myfunction()" value="Call function"> </form> <p>By pressing the button, a function will be called. The function will alert a message. </body> </html>

Function with arguments How to pass a variable to a function, and use the variable value in the function.
<html> <head> <script type="text/javascript"> function myfunction(txt) {

alert(txt) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Hello')" value="Call function"> </form> <p>By pressing the button, a function will be called. The function will alert using the argument text. </body> </html>

Function with arguments 2 How to pass variables to a function, and use these variable values in the function.
<html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt) } </script> </head> <body> <form> <input type="button" onclick="myfunction('Good Morning')" value="In the Morning"> <input type="button" onclick="myfunction('Good Evening')" value="In the Evening"> </form> <p>By pressing a button, a function will be called. The function will alert using the argument passed to it. </body> </html>

Function that returns a value How to let the function return a value.
<html> <head> <script type="text/javascript">

function myfunction() { return ("Hello, have a nice day!") } </script> </head> <body> <script type="text/javascript"> document.write(myFunction()) </script> <p>The function returns text. </body> </html>

A function with arguments, that returns a value How to let the function find the sum of 2 arguments and return the result.
<html> <head>

<script type="text/javascript">

function total(numberA,numberB) { return numberA + numberB }


</script>
</head> <body> <script type="text/javascript"> document.write(total(2,3)) </script> <p>The script in the body section calls a function with two arguments: 2 and 3. <p>The function returns the sum of these two arguments. </body> </html>

JavaScript Conditional Statements


Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have three conditional statements:

if statement - use this statement if you want to execute a set of code when a condition is true if...else statement - use this statement if you want to select one of two sets of lines to execute switch statement - use this statement if you want to select one of many sets of lines to execute

If and If...else Statement


You should use the if statement if you want to execute some code if a condition is true.
Syntax
if (condition) { code to be executed if condition is true }

Example
//If the time on your browser is less than 10, //you will get a "Good morning" greeting. <script type="text/javascript"> var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script>

Notice that there is no ..else.. in this syntax. You just tell the code to execute some code if the condition is true. If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.

Syntax
if (condition) { code to be executed if condition is true } else { code to be executed if condition is false }

Example
//If the time on your browser is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("Good morning!") } else { document.write("Good day!") } </script>

Switch Statement
You should use the Switch statement if you want to select one of many blocks of code to be executed.
Syntax
switch (expression) { case label1: break case label2: break default: code to be executed }

This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

Example
//You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. <script type="text/javascript"> var d=new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: document.write("Super Saturday") break case 0: document.write("Sleepy Sunday") break default: document.write("I'm looking forward to this weekend!") } </script>

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear "

If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting.

Examples
If statement How to write an If statement. Use this statement if you want to execute a set of code if a specified condition is true.

<html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("<b>Good Morning</b>") } </script> <p>This example demonstrates the If statement. <p>If the time on your browser is less than 10, you will get a "Good Morning" greeting. </body> </html>

If...else statement How to write an If...Else statement. Use this statement if you want to execute one set of code if the condition is true and another set of code if the condition is false.
<html> <body> <script type="text/javascript"> var d = new Date() var time = d.getHours() if (time < 10) { document.write("<b>Good Morning</b>") } else { document.write("<b>Good Day</b>") } </script> <p>This example demonstrates the If ... Else statement. <p>If the time on your browser is less than 10, you will get a "Good Morning" greeting. Otherwise you will get a "Good Day" greeting </body> </html>

Random link This example demonstrates a link, when you click on the link it will take you to W3Schools.com OR to W3AppML.com. There is a 50% chance for each of them.
<html> <body> <script type="text/javascript"> var r = Math.random() if (r>0.5) { document.write("<a href='http://www.w3schools.com'>Learn Web Development!<a>") } else { document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!<a>") } </script> <p>This example demonstrates the Math.random() method. <p>The Hyperlink included in the page depends on the state of a random variable. </body> </html>

Switch statement How to write a switch statement. Use this statement if you want to select one of many blocks of code to execute.
<html> <body> <script type="text/javascript"> var d = new Date() var theDay = d.getDay() switch (theDay) { case 5: document.write("<b>Finally Friday</b>") break case 6: document.write("<b>Super Saturday</b>") break case 0: document.write("<b>Sleepy Sunday</b>")

break default: document.write("<b>Looking Forward to the Weekend</b>") } </script> <p>This example demonstrates the switch statement. <p>The text presented depends on the day of the week (0=Sunday, 1=Monday, 2=Tuesday, etc.) </body> </html>

JavaScript Looping
Looping
Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this. In JavaScript we have the following looping statements:

while - loops through a block of code while a condition is true do...while - loops through a block of code once, and then repeats the loop while a condition is true for - run statements a specified number of times

while
The while statement will execute a block of code while a condition is true..
while (condition) { code to be executed }

do...while
The do...while statement will execute a block of code once, and then it will repeat the loop while a condition is true
do { code to be executed } while (condition)

for
The for statement will execute a block of code a specified number of times
for (initialization; condition; increment) { code to be executed }

Examples
For loop How to write a For loop. Use a For loop to run the same block of code a specified number of times
<html> <body> <script type="text/javascript"> for (i=0; i<=5; i++) { document.write("<b>The number is " + i + "</b>") document.write("<br>") } </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body>

</html>

Looping through HTML headers How to use the For loop to write the HTML headers.
<html> <body> <script type="text/javascript"> for (i=0; i<=6; i++) { document.write("<h" + i + ">This is header " + i) document.write("</h" + i + ">") } </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body> </html>

While loop How to write a While loop. Use a While loop to run the same block of code while or until a condition is true
<html> <body> <script type="text/javascript"> i=0 while (i<=5) { document.write("<b>The number is " + i + "</b>") document.write("<br>") i++ } </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body>

</html>

Do while loop How to write a Do While loop. Use a Do While loop to run the same block of code while or until a condition is true. This loop will always be executed once, even if the condition is false, because the statements are executed before the condition is tested
<html> <body> <script type="text/javascript"> i=0 do { document.write("<b>The number is " + i + "</b>") document.write("<br>") i++ } while (i<=5) </script> <p>Explanation: <p>The for loop sets <b>i</b> equal to 0. <p>As long as <b>i</b> is less than or equal to 5, the loop will continue to run. <p><b>i</b> will increase by 1 each time the loop runs. </body> </html>

You might also like