JavaScript Notes
JavaScript Notes
JavaScript
Internal script
The <SCRIPT> tag is used to embed JavaScript code in HTML documents
<SCRIPT LANGUAGE="JavaScript">
[JavaScript Statements...]
</SCRIPT>
JavaScript can be placed anywhere between <HTML> and </HTML> tags
two possibilities are the <HEAD>…</HEAD> portion and the
<BODY>…</BODY> portion
<HTML>
<HEAD><TITLE>Using Multiple scripts</TITLE>
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
</HEAD>
<BODY>
<H1>This is another script</H1>
<SCRIPT LANGUAGE="JavaScript">
[JavaScript statements...]
</SCRIPT>
</BODY></HTML>
External script
We place script in a separate file and include this in HTML code
SRC attribute of the <SCRIPT> is used to include the external JavaScript file
in HTML
o <script src="myscripts.js"> </script>
Are useful when you have lengthy scripts
Improve the readability
JavaScript Convention
Using the Semicolon
document.write("Hello"); alert("Good bye")
document.write("Hello")
alert("Good bye")
document.write("Hello");
alert("Good bye");
Case Sensitivity
Comments:
o single line //
o Multiple lines /* */
Using Quotes
o document.write(“<font color=“red”>Hello World</font>”)
o document.write(“<font color=‘red’>Hello World</font>”)
Writing JavaScript
Variables in JavaScript
Variable is the name of a memory location which holds the data of a certain
type (data types)
There are four common data types in JavaScript
o numbers, strings, Boolean, null values
JavaScript is a loosely typed language
The word “var” is used to declare a variable
o var LastName = “Smith”
o var AccountNumber = 1111
Variable Naming
o First character cannot be a digit
o Other characters may be digits, letters or underscore
o Reserved words cannot be useds
o Case sensitive
Variable Initialization
o var variableName = initialValue
o var variableName1 = initialValue1, variableName2 = initialValue2, …
JavaScript Operators
An operator is simply a symbol that tells the compiler (or interpreter) to
perform a certain action
Assignment Operator: =
Arithmetic Operators: +, - , *, /, %, ++, --
Logical Operators: &&, ||, !
Comparison Operators: = =, = = =,! =, != =, <, >, <=, >=
JavaScript Functions
User defined functions
Predefined functions
Functions are defined using the keyword function, followed by the name of
the function and list of parameters
function functionName([parameters])
{
[statements]
}
Calling a function
The syntax of a function call is:
functionName([arguments])
Common events
onClick
onDblClick
onChange
onFocus
onMouseOver
onMouseOut
onSubmit
onload
Conditional statements
If statement
if (condition)
statement
if(condition)
{ statements }
If-else statement
if(condition)
{statement}
else
{statements}
Loops
For loop
for(var i=1; i<10; i++)
{
Document.write(“hello world”)
}
While loop
While(condition)
{
}