INTRODUCTION TO JAVASCRIPT


Introduction


 

A scripting language developed by Netscape to enable Webauthors to design interactive sites. Although it shares many of the features and structures of the full Java language, it was developed independently. Javascript can interact with HTML source code, enabling Web authors to spice up their sites with dynamic content. JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

JavaScript is used in Web site development to do such things as:

Automatically change a formatted date on a Web page

Cause a linked-to page to appear in a popup window

Cause text or a graphic image to change during a mouse rollover

 

WHAT DOES JAVASCRIPT DO?


 

JavaScript is a multipurpose programming language. There are many, many things that it can be used for. Generally speaking, it is used to allow Website developers to create web pages that have some intelligence built in to them. Instead of a webpage just being a plain page that has no interactivity, JavaScript can allow webpages adapt to what you do on the page, load new information, make decisions and respond to events.

 

For example, JavaScript might be used to validate a Mailing List Subscription form. So that when you try to submit a form the code runs and looks at each field on the form. If the code notices that you’ve forgotten to enter something in one of the fields (For example, your email address) it would pop up a warning and not let you submit the form until it is complete. Once that field is fixed then the form will be allowed to be submitted.

With JavaScript you can:

 

 – Put text in an HTML page on-the-fly.

 

Say you want to display a nice thank you message to a user who has just submitted a comment form on your website. Obviously, the message needs to be added after the user has submitted the form.

 

You could let the server do that. However, if your website is very busy and your server processes hundreds of forms a day, it might take a little while for your thank you message to appear to the user.

 

Here’s JavaScript to the rescue. Because JavaScript runs in the user’s browser, the thank you note can be added and displayed on the page almost instantaneously, making your website users happy.

 

 – Make your web pages responsive.

 

Web environments are dynamic, things happen all the time: the web page loads in the browser, the user clicks a button or moves the mouse over a link, etc. These are called events (which will be the topic of lesson 3).

 

With JavaScript you can make the page immediately react to these events the way you choose: for example, by showing or hiding specific page elements, by changing the background color, etc.

 

 – Detect visitors’ browsers.

 

You can use a JavaScript script to detect the visitor’s browser, or, even better, you can detect what features a certain browser does or does not support. Depending on the browser and its capabilities, you can choose to load a page specifically tailored to that kind of browser

 

 – Create cookies.

 

A JavaScript script is great if you want to create cookies so that your visitors can enjoy a personalized experience the next time they visit your website

 

Java vs javascript


  • Java has static typing; JavaScript’s typing is dynamic. In dynamic typing, a variable can hold an object of any type and cannot be restricted.
  • JavaScript is weakly typed while Java is strongly typed.
  • Java is loaded from compiled bytecode; JavaScript is loaded as human-readable source code.
  • Java’s objects are class-based; JavaScript’s are prototype-based.
  • JavaScript has many functional programming features based on the Scheme language.
  • Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser only.
  • Java code needs to be compiled while JavaScript code are all in text.
  • They require different plug-ins.
  • Java can stand on its own while JavaScript must be placed inside an HTML document to function.
  • Java is larger and a more complicated language. While, JavaScript is easier and more robust than Java.
  • Java must be compiled into what is known as a “machine language” before it can be run on the Web.
  • JavaScript is geared to web pages. Java is geared toward where it is needed most at the time.
  • Java constructors are special functions that can only be called at object creation; JavaScript “constructors” are just standard functions.
  • Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the ends of certain lines.
  • Java uses block-based scoping; JavaScript uses function-based scoping.
  • Java has an implicit this scope for non-static methods, and implicit class scope; JavaScript has implicit global scope.
  • JavaScript supports closures; Java can simulate sort-of “closures” using anonymous classes.
  • All JavaScript functions are variadic; Java functions are only variadic if explicitly marked.
  • JavaScript prototypes can be redefined at runtime, and has immediate effect for all referring objects. Java classes cannot be redefined in a way that affects any existing object instances.
  • JavaScript allows methods in an object to be redefined independently of its prototype; methods in a Java object are tied to its class, and cannot be redefined at runtime.

 

  • JavaScript has many functional programming features based on the Scheme language.
  • Java is an OOP programming language while Java Script is an OOP scripting language.
  • JavaScript, does not create applets or stand-alone applications unlike Java.

 

<script > tag

While JavaScript is the default scripting language of the web, browsers can support any number of additional languages. For example, Internet Explorer also supports a scripting language derived from Visual Basic named VBScript. In order to specify the scripting language of choice, the <script> tag’s “type” attribute is used. Technically, “type” specifies the MIME type of the script. The following example uses “type” to specify JavaScript’s MIME type, “text/javascript”.

 

<script type=”text/javascript”>

// JavaScript code here

</script>

In older versions of HTML it was necessary to specify a value for “type”. However, starting in HTML5, “type” defaults to “text/javascript”. This decision was made because the W3C realized that JavaScript is the only universally supported scripting language. Therefore, HTML5 <script> tags can be shortened in the following fashion.

 

<script>

// JavaScript code here

</script>

The “language” Attribute

 

There is a second attribute, “language”, which can be used to specify the scripting language. Unlike “type”, the possible values for “language” were never standardized. This attribute has been deprecated for a long time now, but some people still use it. It should not be used under any circumstances.

 

Inline and External Scripts

 

The <script> tag allows code to either be embedded directly into HTML, or included from external script files. Inline scripts are created by placing code between <script> and </script> tags in an HTML file. The following code shows an example inline <script>.

 

<script>

// Inline JavaScript code here

</script>

Inline scripts are a quick and easy way to add code to web pages. However, large scripts can also lead to cluttered HTML files. The alternative approach is to include code in external script files. The external files are referenced via a URL specified by the “src” attribute. The following example shows how external script files are included. In this example, the external script file is named external.js, and is located in the same directory as the HTML file. Also, note that the closing </script> tag is still required.

 

<script src=”external.js”></script>

XHTML Compatibility

 

XHTML rules are much stricter than those of HTML. When special XML characters (such as & and <) are used in scripts in XHTML files, they cause errors. The simplest workaround is to use external script files. However, if you simply must write inline scripts, then you will need to include CDATA (character data) sections in your file. Within CDATA sections the special XML characters can be used freely. The following example uses a CDATA section that is compatible with both XHTML and HTML syntax. Note that XHTML also requires the use of the “type” attribute.

 

<script type=”text/javascript”>

//<![CDATA[

alert((1 < 2) && (3 > 2));

//]]>

</script>

Dynamic Script Tag Injection

 

Dynamic script tag injection is a technique in which new <script> elements are created at runtime. When the new <script> is added to the page, its “src” URL is automatically downloaded and executed. The following code shows an example dynamic script tag injection. In the example, a new <script> element is created using the document.createElement() function. Next, the “src” attribute is set to the URL of the script file. Finally, the new element is added to the document’s head, causing the script to be downloaded and executed.

 

var script = document.createElement(“script”);

 

script.setAttribute(“src”, url);

document.head.appendChild(script);

Application

 

The <script> tag is not subject to the same origin policy. Web pages can exploit this freedom to request cross-site data. JSONP, a technique for making cross-site AJAX-like requests, makes extensive use of dynamic script tag injection. Under the JSONP model, each AJAX request is replaced by a script tag injection.

 

The “async” Attribute

 

When a <script> tag is encountered, the browser stops what it is doing and begins downloading/executing the script. This default behavior is known as synchronous blocking. During this period of blocking, the page may seem unresponsive or slow to the user. To mitigate this problem, HTML5 introduced the “async” attribute for <script> tags. “async” is a Boolean attribute which, when specified, indicates that a script should unblock the rest of the page, and execute asynchronously. According to the specification, “async” should only be used with external script files. Unfortunately, “async” is not yet supported in Opera.  The following example shows how the “async” attribute is used.

 

<script src=”file.js” async=”async”></script>

Normally, “async” defaults to false. However, when dealing with dynamically injected scripts, the default value becomes true. This can lead to problems if scripts with interdependencies are inserted at the same time. For example, assume that a page injects a third-party library originating from a slow server. At (almost) the same time, the page also injects a script that makes calls to the library. Since the scripts are asynchronous, the second file could potentially get downloaded and executed before the library is available. The solution is to preserve the program order by setting “async” to false for both scripts. This concept is illustrated in the following example. In the example, the page will wait for the first script to load before moving on to the second script.

 

var library = document.createElement(“script”);

var local = document.createElement(“script”);

 

library.async = false;

local.async = false;

library.setAttribute(“src”, “remote-library-code.js”);

local.setAttribute(“src”, “local-file.js”);

document.head.appendChild(library);

document.head.appendChild(local);

// use the library code

The “defer” Attribute

 

<script> tags cause the browser to block the rest of the page while the script is processed. This can lead to problems if the script references DOM elements which haven’t finished loading yet. In this scenario, the DOM-related code is typically placed in an event handler such as window load or DOMContentLoaded. Another option is to postpone execution until the document has been parsed using the “defer” attribute. Like “async”, “defer” is a Boolean attribute that should only be used with external script files. The following example shows how “defer” works. This example requires an HTML file and a separate JavaScript file named defer.js. The HTML source is shown below.

 

<!DOCTYPE html>

<html lang=”en”>

<head>

<title>defer Example</title>

<meta charset=”UTF-8″ />

<script src=”defer.js” defer=”defer”></script>

</head>

<body>

<span id=”message”></span>

</body>

</html>

The code for defer.js is shown below. If the “defer” attribute were not present, this code would fail because the DOM is not ready when the <span> element is accessed.

 

var span = document.getElementById(“message”);

 

span.textContent = “The DOM is ready for scripting!”;

It is possible to specify both “async” and “defer” on the same <script> element. This is possible so that browsers that do not support “async” can fall back on the “defer” behavior instead of synchronous blocking. According to the specification, “defer” is overridden by “async”. Unfortunately, “defer” is also unsupported in Opera.

 

Performance Considerations

 

All of the examples on this page have shown <script> tags placed in the document’s head. This can actually degrade performance because the rest of the page is blocked while the scripts are processed. Obviously, the “defer” and “async” attributes offer one solution. Unfortunately, they are not supported everywhere yet. A second option is to move <script> tags to the bottom of the <body> tag whenever possible ― this is usually fine as long as the script does not call document.write().

 

Using external script files instead of inline scripts is another technique that often improves performance. This leads to smaller HTML files, at the expense of creating additional HTTP requests. However, script files are often shared among multiple HTML pages, and can be cached by the browser. The overall result is a smaller HTML download without the additional server requests. Also remember that scripts can be downloaded dynamically after the page is loaded.

document.write

 

The document.write method provides a way of incorporating strings into the HTML content of the page. There are better ways to do that, such as .innerHTML and .createElement or HTML cloning patterns. Use of document.write should be avoided.

 

document.write is recklessly dependent on timing. If document.write is called before the onload event, it appends or inserts text into the page. If it is called after onload, it completely replaces the page, destroying what came before.

 

document.write encourages bad structure, in which script and markup are intermingled. A cleaner structure has minimal interaction between markup and script.

 

 

Things to Remember

 

The <script> tag always requires a matching </script> tag.

The scripting language is specified by the “type” attribute. Do not use the “language” attribute. HTML5 defaults to “text/javascript”.

XHTML files should use external script files or CDATA sections to allow special characters.

Dynamic script tag injections allow cross-site resource requests.

The “async” attribute causes a script to execute asynchronously from the rest of the page. It can also preserve order for dynamically inserted scripts.

The “defer” attribute can postpone script execution until the document is ready.

Move <script> tags to the end of the <body> when possible.

Use external script files which can be cached and shared among pages.

 

Program to demonstrate script tag

<html>

<head>

<title>Javascript – How to include a script area in HTML</title>

<script language=javascript type=”text/javascript”>

document.writeln(“<h1>Hello World</h1>”)

</script>

</head>

<body>

 

ggg

Comments in java script

When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include some comments in the code that will explain what is going on. Not only will this help you remember it later on, but if you someone else views your code, they will also be able to understand the code (hopefully)!

 

Another great thing about comments is the ability for comments to remove bits of code from execution when you are debugging your scripts. This lesson will teach you how to create two types of comments in JavaScript:

Single or one line comments and

 multi-line comments.

  1. One-line comments of C++ style. These comments begin with // and continue up to the next line break:

// This is a one-line comment

 

  1. Multiple-line C-style comments. Everything between /* and */ is a comment, for example:

/* This is a comment */

/* C-style comments can span

as many lines as you like,

as shown in this example */

 

 

for example:

<html>

<head>

<title>Javascript – How to include a comments in HTML with javascript</title>

<script type=”text/javascript”>

 

// This is a single line JavaScript comment

 

document.write(“I have comments in my JavaScript code!”);

//document.write(“You can’t see this!”);

 

</script>

</head>

<body>

 

Programming concept:

Javascript is similar to many other programming languages. Javascript supports creating variables, constants, function etc. it is always a good practice to implement coding in <HEAD>…</HEAD>

So that these are defined before being used. Javascript is case sensitive

. therefore, watch your letter when you create are called variables, statements, objects and functions.

 

1 variables in JavaScript

A variable is a name, or identifier, that represents some data that you set. The name wraps up the data so you can move it around a lot easier, but the name is not the data! A variable’s value can change during the script. You can refer to a variable by name to see its value or to change its value.

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.

 

Rules:

1 can negin by any alphabet a-z, A-Z

2 digits 0-9

3 special character underscore(_), dollar sign ($)

4 variables name are case sensitive.

For example:

<html>

<body>

 

<h1>My Web Page</h1>

 

<p id=”abc1″></p>

<p id=”abc2″></p>

 

<script>

a = 1;

b = 6;

c = a + b;

document.getElementById(“abc1”).innerHTML = c;

x = 7;

y = 2;

z = x + y;

document.getElementById(“abc2”).innerHTML = z;

</script>

 

</body>

</html>

Result:

 

 

 

Data types


Primitive Data Types:
The primitive data types are (JsFiddle):

  • String
  • Number
  • Boolean

Reference Data Types
Other than above three primitive data types everything in JavaScript is object like function, Regexp etc. The reference data types are (JsFiddle):

  • Object
  • Array
  • Function

 

Special Data Types:

There are two others special data types, which includes (JsFiddle):

  • null
  • undefined

 

 

String Data Type

String data type is use to represent text in JavaScript. A string is value with zero or more characters which may include letters, punctuation marks and digits. There is no separate data type for character (char) in JavaScript. You may use single or double quote for assigning value to string.

These are some examples of valid string data types in JavaScript:

var str1 = “Hi, How are you?”;

var str2 = “He said: ‘Hi'”;

var str3 = ‘He said:”Hi” ‘;

var str4 = “25”;

var str5 = “”;

var str6 = ‘C’;

 

 

Number Data Type

For any numeric values float, decimal or integer JavaScript has only one data type that is Number.

 

Integers

In JavaScript, you can express integers in 3 different Bases:

  • base 10,
  • base 8 (octal), and
  • base 16 (hexadecimal).

Base 8 numbers can have digits only up to 7, so a decimal value of 18 would be an octal value of 22.

Similarly, hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F is 15. So, a decimal value of 18 would be 12 in hexadecimal notation.

Floating Point Values

Floating point values can include a fractional component. A floating-point literal includes a decimal integer plus either a decimal point and a fraction expressed as another decimal number or an expression indicator and a type suffix

  • 7.2945
  • -34.2
  • 2e3 means 2 x 10=> 2000
  • 2E-3 means 2 x 10-3 => .002

Floating point literals must, at a minimum, include a decimal integer and either the decimal point or the exponent indicator (“e” or “E”). As with integers, floating point values can be positive or negative

Boolean Data Type

Boolean data type can only have two values, literals true and false. Comparison of two variables will outcome a Boolean value. Boolean are used for condition testing.

Here is example :
var num1=54; var result = (num1 === 2000); //will return falsevar result1 = (num1 === 54); //will return true

 

Functions

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.

Defining functions

A function definition (also called a function declaration) consists of the function keyword, followed by:

  • The name of the function.
  • A list of arguments to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly brackets, { }.

For example, the following code defines a simple function named square:

function square(number) {

return number * number;

}

 

 

In this “square” function, the parenthesized variable “number” is called a parameter. It represents the input, or the value to be squared. The output of square is the value of the expression following the return statement — in this case, the contents of the result variable, which is equal to number squared. This function fulfills its role by multiplying the input value by itself and returning the result.

The above function definition, by itself, accomplishes nothing. In order for it to be useful, it must be put to work. The following example shows how to use our new square function:

x = 5;

y = square (x);

The first command assigns a value of 5 to the variable x. The second command uses x’s value, still 5, as a parameter to the square function. The value returned by the function, 25, is then assigned to the variable y.

 

 

For example:

<html>

<body>

 

<p>This example calls a function which performs a calculation, and returns the result:</p>

 

<p id=”mul”></p>

 

<script>

function myFunction(a, b) {

return a * b;

}

document.getElementById(“mul”).innerHTML = myFunction(8, 8);

</script>

 

</body>

</html>

 

 

 

What is an object?

Objects are the core component of JavaScript. Simply stated, an object is an aggregation (i.e., collection) of variables and functions. Ideally, the components of an object are put together in such a way that the object represents both the attributes and behavior of some “thing” being modeled in the program.

An object used to represent a stopwatch, for example, might contain a variable to represent hours, another to represent minutes, and another to represent seconds. The stopwatch object might also contain functions that manipulate those values, such as “start ()” and “stop ()”. In object oriented languages, object variables are called “properties” and object functions are called “methods.”

When a web page is loaded, the browser’s JavaScript interpreter automatically creates objects for most of the components contained in the document. This includes — but is not limited to — objects for the document’s forms, images, and hyperlinks. JavaScript programmers can take advantage of the properties and methods of these objects to accomplish a wide variety of tasks.

You cannot fully appreciate what an object is until you have learned more about properties and methods. Please read on.

 

What is a property?

 

It is impossible to explain what an object is without explaining what a property is also. Simply put, the variables that makes up an object are called the object’s properties. In other words, properties are variables that belongs to an object; thus they are sometimes called member variables. Other than the fact that properties belong to objects, there is little behavioral difference between variables and properties.

Properties have names just like variables do, and in fact follow the same naming rules. However, a property’s name alone is insufficient to identify an object’s property. This is because properties belong to objects, and the object to which the property belongs must also be specified. In JavaScript, properties are identified by concatenating the object and property names together, with the object name first and the two names separated by a dot (period).

 

Examples:

 

time . hours

time . minutes

current_window . width

user . password

user . name . first *

Consider a variable, called “watch,” whose value is an object that represents a stopwatch. If the properties of watch are hours and minutes, then the program fragment below demonstrates how watch’s properties can be manipulated so that the object represents a time which is 5 minutes later:

/* Increase minutes by 5: */

watch . minutes += 5;

 

/* If minutes now exceed 59, then subtract 60 and bump the hours by one: */

if (watch . minutes > 59)

{

watch . minutes -= 60;

watch . hours += 1;

}

As you can see, properties are treated just like normal variables. From this point of view, properties are like variables with long, dotted names. On the other hand, you shouldn’t forget that properties are components of their objects, and that the objects themselves are also variables.

 

What is a method?

Although the code shown above accomplishes what it is supposed to do, it has a serious limitation: it works only on a stopwatch object named “watch”. If we were using multiple stopwatch objects to represent the times of several participants in a race (such as “watch1” and “watch2”), we would have to duplicate the code once for each object, changing the object name “watch” to the name of the new object in each replication.

This is more work than most programmers are willing to do. The object-oriented answer to this problem is a special kind of function call a method. Methods are functions that belong to objects, and for that reason they are sometimes called “member functions.” Member functions are designed to operate directly on the properties of the object to which they belong.

 

Let’s rewrite the previous sample code as a member function. Creating member functions requires two steps. First, we define a generalized function that does not apply to any object in particular:

 

// Step 1:

function update_by_5 ()

{

this . minutes += 5;

if (this . minutes > 59)

{

this . minutes -= 60;

this . hours += 1;

}

}

The JavaScript interpreter recognizes the word “this” as a synonym for “the object to which I belong.” Since at this point the update_by_5 function doesn’t actually belong to an object, the concept of “this” doesn’t have much meaning. Step 2 provides the cure for this problem:

 

// Step 2:

watch . update = update_by_5;

This assignment statement tells the interpreter to let update be a member function of the watch object. It says that update’s behavior should be the same as specified for update_by_5.

 

Now that watch has an update () method, we can invoke it with the following statement:

 

watch . update ();

This statement tells the JavaScript interpreter to run the update_by_5 function with the word “this” replaced by “watch”. As a result, watch’s member variables, hours and minutes, will be replaced with values that represent a time that is 5 minutes later.

 

 

Null:

Null Data Type

The value for null data type can only be null. keyword null is use to assign null to any variable. It can be use to emptied content of any variable without deleting the variable. A variable with null data type contains no valid other data types.
Like Array in JavaScript typeof operator with null returns the object which is confusing behavior.

Here is example (JsFiddle):

var type = null;var obj = null;
Undefined Data Type

The undefined value is default for a variable which is declared but never assigned a value.

Here is example (JsFiddle):

var myVar;if((typeof var) === “undefined”){  alert(“variable is undefined”);

 

literals in javascript

An object literal is a comma-separated list of name-value pairs wrapped in curly braces. Object literals encapsulate data, enclosing it in a tidy package.

 

Object literals are defined using the following syntax rules:

 

A colon separates property name[1] from value.

A comma separates each name-value pair from the next.

There should be no comma after the last name-value pair

 

 

Special characters

It is also possible to include special characters in a string. It is also called escape sequences.

For example:

‘nikhil \n arora’

 

The following table lists the special characters that you can use in javascript:

characters Description
\’ single quote
\” double quote
\? question mark
\\ backslash
\a audible bell
\b backspace
\f form feed – new page
\n line feed – new line
\r carriage return
\t horizontal tab
\v vertical tab