Professional Documents
Culture Documents
What is JavaScript ?
JavaScript was designed to 'plug a gap' in the techniques available for creating
web-pages.
HTML is relatively easy to learn, but it is static. It allows the use of links to load
new pages, images, sounds, etc., but it provides very little support for any other
type of interactivity.
Uses of JavaScript
With JavaScript you can show, hide, change, resize images, and
create image rollovers. You can create scrolling text across the status
bar.
It can do some processing of forms and can validate user input when
Writing JavaScript
run by the client's browser. Here are some tips to remember when writing
JavaScript commands.
statements
</SCRIPT>
Using JavaScript in your HTML
<html>
<head>
<script type=
"text/javascript">
function helloWorld() {
document.write("Hello World!");
</script>
</head>
<body>
<script type=
"text/javascript">
helloWorld();
</script>
</body>
</html>
Implementing JavaScript
There are three ways to add JavaScript commands to your Web Pages.
• Embedding code
• Inline code
• External file
External File
You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code
from an external text file. This is useful if you have a lot of code or you
want to run it from several pages, because any number of pages can call the
same external JavaScript file. The text file itself contains no HTML tags. It
is call by the following tag:
<SCRIPT SRC="filename.js">
</SCRIPT>
External Example
<!DOCTYPE html>
<html>
<body>
<h2>External JavaScript</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p>(myFunction is stored in an external file called "myScript.js")</p>
<script src="myScript.js"></script>
</body>
</html>
JavaScript is a loosely typed or a dynamic language. That means you don't have to
declare the type of a variable ahead of time. The type will get determined
automatically while the program is being processed. That also means that you can
have the same variable as different types:
2. Null
3. Undefined
4. Number
5. String
and Object
Primitive values
All types except objects define immutable values (values, which are incapable of
being changed). For example and unlike to C, Strings are immutable. We refer to
values of these types as "primitive values".
Boolean type
Boolean represents a logical entity and can have two values: true, and false.
Null type
The Null type has exactly one value: null. See null and Null for more details.
Undefined type
A variable that has not been assigned a value has the value undefined. See
undefined and Undefined for more details.
Number type
According to the ECMAScript standard, there is only one number type: the
double-precision 64-bit binary format IEEE 754 value (number between -(253
-1) and 253 -1). There is no specific type for integers. In addition to being able
to represent floating-point numbers, the number type has three symbolic
values: +Infinity, -Infinity, and NaN (not-a-number).
To check for the largest available value or smallest available value within +/-
Infinity, you can use the constants Number.MAX_VALUE or
Number.MIN_VALUE and starting with ECMAScript 6, you are also able to check
if a number is in the double-precision floating-point number range using
Number.isSafeInteger() as well as Number.MAX_SAFE_INTEGER and
Number.MIN_SAFE_INTEGER. Beyond this range, integers in JavaScript are not
safe anymore and will be a double-precision floating point approximation of
the value.
The number type has only one integer that has two representations: 0 is
represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost
no impact. For example +0 === -0 is true. However, you are able to notice this
when you divide by zero:
> 42 / +0
Output: Infinity
> 42 / -0
Output: -Infinity
Although a number often represents only its value, JavaScript provides some
binary operators. These can be used to represent several Boolean values within
a single number using bit masking. However, this is usually considered a bad
practice, since JavaScript offers other means to represent a set of Booleans
(like an array of Booleans or an object with Boolean values assigned to named
properties). Bit masking also tends to make code more difficult to read,
understand, and maintain. It may be necessary to use such techniques in very
constrained environments, like when trying to cope with the storage limitation
of local storage or in extreme cases when each bit over the network counts.
This technique should only be considered when it is the last measure that can
be taken to optimize size.
String type
Unlike in languages like C, JavaScript strings are immutable. This means that
once a string is created, it is not possible to modify it. However, it is still
possible to create another string based on an operation on the original string.
For example:
It can be tempting to use strings to represent complex data. Doing this comes
with short-term benefits:
Strings are easy to debug (what you see printed is always what is in the string).
Strings are the common denominator of a lot of APIs (input fields, local storage
values, XMLHttpRequest responses when using responseText, etc.) and it can
be tempting to only work with strings.
Use strings for textual data. When representing complex data, parse strings
and use the appropriate abstraction.
Symbol type
Objects
Properties
There are two types of object properties which have certain attributes: The
data property and the accessor property.
Data property
Default
Attribute Type Description
value
Any
The value retrieved by a
[[Value]] JavaScript undefined
get access of the property.
type
Accessor property
Associates a key with one or two accessor functions (get and set) to retrieve or
store a value and has the following attributes:
Default
Attribute Type Description
value
Variables
Programmers use variables to store values. A variable can hold several types
of data. In JavaScript you don't have to declare a variable's data type before
using it. Any variable can hold any JavaScript data type, including:
• String data
• Numbers
• Boolean values (T/F)
Variable Names
There are rules and conventions in naming variables in any programming
language. It is good practice to use descriptive names for variables. The
following are the JavaScript rules:
• The variable name must start with a letter or an underscore.
firstName or _myName
• You can use numbers in a variable name, but not as the first
character.
name01 or tuition$
• You can't use space to separate characters.
userName not user Name
• Capitalize the first letter of every word except the first
salesTax or userFirstName
• To declare variables, use the keyword var and the variable name:
var userName
• To assign values to variables, add an equal sign and the value:
var userName = "Smith"
var price = 100
Array
Syntax
You will use ordinal numbers to access and to set values inside an array as follows.
Array Properties
Here is a list of the properties of the Array object along with their description.
Property Description
In the following sections, we will have a few examples to illustrate the usage of
Array properties.
Array Methods
Here is a list of the methods of the Array object along with their description.
Method Description
Operators
JavaScript supports the following types of operators.
Arithmetic Operators
Comparision Operators
Assignment Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators −
1 + (Addition)
2 - (Subtraction)
Subtracts the second operand from the first
3 * (Multiplication)
4 / (Division)
5 % (Modulus)
6 ++ (Increment)
7 -- (Decrement)
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10
will give "a10".
Comparison Operators
JavaScript supports the following comparison operators −
1 = = (Equal)
2 != (Not Equal)
Ex: (A != B) is true.
Logical Operators
JavaScript supports the following logical operators −
2 || (Logical OR)
If any of the two operands are non-zero, then the
condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Bitwise Operators
JavaScript supports the following bitwise operators −
Ex: (A & B) is 2.
2 | (BitWise OR)
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each
bit of its integer arguments. Exclusive OR means that
either operand one is true or operand two is true, but
not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It moves all the bits 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 it by 2, shifting
two positions is equivalent to multiplying by 4, and so
on.
Ex: (A << 1) is 4.
Ex: (A >> 1) is 1.
This operator is just like the >> operator, except that the
bits shifted in on the left are always zero.
Ex: (A >>> 1) is 1.
Assignment Operators
JavaScript supports the following assignment operators −
1 = (Simple Assignment )
Ex: C += A is equivalent to C = C + A
Ex: C -= A is equivalent to C = C - A
Ex: C /= A is equivalent to C = C / A
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=,
>>=, &=, |= and ^=.
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript:
the conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value
and then executes one of the two given statements depending upon the result of
the evaluation.
1 ? : (Conditional )
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Expressions
Primary expressions
this
Use the this keyword to refer to the current object. In general, this refers to the
calling object in a method. Use this either with the dot or the bracket notation:
this['propertyName']
this.propertyName
Grouping operator
The grouping operator ( ) controls the precedence of evaluation in expressions.
For example, you can override multiplication and division first, then addition and
subtraction to evaluate addition first.
Comprehensions
[for (x of y) x]
Array comprehensions.
(for (x of y) y)
Generator comprehensions.
Left-hand-side expressions
new
You can use the new operator to create an instance of a user-defined object type
or of one of the built-in object types. Use new as follows:
super
Spread operator
Example: Today if you have an array and want to create a new array with the
existing one being part of it, the array literal syntax is no longer sufficient and you
have to fall back to imperative code, using a combination of push, splice, concat,
etc. With spread syntax this becomes much more succinct:
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.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been
executed.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var i;
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="demo"></p>
<script>
var x;
for (x in person) {
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
The while loop loops through a block of code as long as a specified condition is
true.
Syntax
while (condition) {
code block to be executed
}
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript while</h2>
<p id="demo"></p>
<script>
var i = 0;
i++;
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
If you forget to increase the variable used in the condition, the loop will never
end. This will crash your browser.
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
Syntax
do {
code block to be executed
}
while (condition);
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
do {
i++;
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
The break statement breaks the loop and continues executing the code after the
loop (if any):
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var i;
if (i === 3) { break; }
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Example
<!DOCTYPE html>
<html>
<body>
<script>
var i;
if (i === 3) { continue; }
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Functions
With functions, you can give a name to a whole block of code, allowing you
to reference it from anywhere in your program. JavaScript has built-in
functions for several predefined operations. Here are three functions.
• alert("message")
• confirm("message")
• prompt("message")
JavaScript Function Syntax
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, ...)
Function arguments are the real values received by the function when it is
invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
Function Return
When JavaScript reaches a return 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 a return value. The return value is "returned" back to
the "caller":
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the
result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
</script>
</body>
</html>
Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations
JavaScript Objects
objects are variables too. But objects can contain many values.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = car.type;
</script>
</body>
</html>
The values are written as name:value pairs (name and value separated by a
colon).
Object Methods
JavaScript objects are containers for named values called properties or methods.
Object Definition
Spaces and line breaks are not important. An object definition can span multiple
lines:
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
</script>
</body>
</html>
objectName.propertyName
or
objectName["propertyName"]
objectName.methodName()
Dialog Boxes
javaScript supports three important types of dialog boxes. These dialog boxes can
be used to raise and alert, or to get confirmation on any input or to have a kind of
input from the users.
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For
example, if one input field requires to enter some text but the user does not
provide any input, then as a part of validation, you can use an alert box to give a
warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives
only one button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
A confirmation dialog box is mostly used to take user's consent on any option. It
displays a dialog box with two buttons: Cancel.
If the user clicks on the OK button, the window method confirm() will return true.
If the user clicks on the Cancel button, then confirm() returns false. You can use a
confirmation dialog box as follows.
Example
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
return true;
else{
return false;
}
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
The prompt dialog box is very useful when you want to pop-up a text box to get
user input. Thus, it enables you to interact with the user. The user needs to fill in
the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two
parameters: (i) a label which you want to display in the text box and (ii) a default
string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button,
the window method prompt() will return the entered value from the text box. If
the user clicks the Cancel button, the window method prompt() returns null.
Example
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key, closing
a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.
Example
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put
your form validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling
a validate() function before submitting a form data to the webserver.
If validate() function returns true, the form will be submitted, otherwise it will
not submit the data.
<head>
<script type="text/javascript">
<!--
function validation() {
.........
//-->
</script>
</head>
<body>
.......
</form>
</body>
</html>
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and the
onmouseout triggers when you move your mouse out from that element. Try the following
example.
<html>
<head>
<script type="text/javascript">
<!--
function over() {
function out() {
//-->
</script>
</head>
<body>
</div>
</body>
</html>