Module 4 - Introduction To JavaScript
Module 4 - Introduction To JavaScript
Module 3
Introduction to JavaScript
Overview
JavaScript is a lightweight, interpreted programming language. It is designed for creating network-
centric applications. It is complimentary to and integrated with Java. JavaScript is very easy to implement
because it is integrated with HTML. It is open and cross-platform.
Objectives
What is JavaScript?
The programs in this language are called scripts. They can be written right in a web page’s
HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.
In this aspect, JavaScript is very different from another language called Java.
JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set
of language elements such as operators, control structures, and statements. Core JavaScript
can be extended for a variety of purposes by supplementing it with additional objects; for example:
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at
that time, so it was decided that positioning a new language as a “younger brother” of Java would help.
But as it evolved, JavaScript became a fully independent language with its own specification called
ECMAScript, and now it has no relation to Java at all.
Javascript is a MUST for students and working professionals to become a great Software Engineer
specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning Javascript:
Javascript is the most popular programming language in the world and that makes it a
programmer’s great choice. Once you learnt Javascript, it helps you developing great front-end as
well as back-end softwares using different Javascript based frameworks like jQuery, Node.JS etc.
Javascript is everywhere, it comes installed on every modern web browser and so to learn
Javascript you really do not need any special environment setup. For example Chrome, Mozilla
Firefox , Safari and every browser you know as of today, supports Javascript.
Javascript helps you create really beautiful and crazy fast websites. You can develop your website
with a console like look and feel and give your users the best Graphical User Experience.
JavaScript usage has now extended to mobile app development, desktop app development, and
game development. This opens many opportunities for you as Javascript Programmer.
Due to high demand, there is tons of job growth and high pay for those who know JavaScript. You
can navigate over to different job sites to see what having JavaScript skills looks like in the job
market.
Great thing about Javascript is that you will find tons of frameworks and Libraries already
developed which can be used directly in your software development to reduce your time to market.
JavaScript’s capabilities greatly depend on the environment it’s running in. For instance, Node.js
supports functions that allow JavaScript to read/write arbitrary files, perform network requests, etc.
In-browser JavaScript can do everything related to webpage manipulation, interaction with the
user, and the webserver.
Add new HTML to the page, change the existing content, modify styles.
React to user actions, run on mouse clicks, pointer movements, key presses.
Send requests over the network to remote servers, download and upload files (so-called AJAX and
COMET technologies).
Get and set cookies, ask questions to the visitor, show messages.
Remember the data on the client-side (“local storage”).
Client side validation - This is really important to verify any user input before submitting it to the
server and JavaScript plays an important role in validating those inputs at front-end itself.
Manipulating HTML Pages - JavaScript helps in manipulating HTML page on the fly. This helps
in adding and deleting any HTML tag very easily using JavaScript and modify your HTML to change
its look and feel based on different devices and requirements.
User Notifications - You can use JavaScript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
Back-end Data Loading - JavaScript provides Ajax library which helps in loading back-end data
while you are doing some other processing. This really gives an amazing experience to your
website visitors.
Presentations - JavaScript also provides the facility of creating presentations which gives website
look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-based slide
presentations.
Server Applications - Node JS is built on Chrome's Javascript runtime for building fast and
scalable network applications. This is an event based library which helps in developing very
sophisticated server applications including Web Servers.
It means that a web page need not be a static HTML, but can include programs that interact with
the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail
address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
Less server interaction − You can validate user input before sending the page off to the server.
This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they
have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over them
with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components
and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following important
features:
Client-side JavaScript does not allow the reading or writing of files. This has been kept for security
reason.
JavaScript cannot be used for networking applications because there is no such support available.
1. Sublime Text 3.
2. Visual Studio Code 1.30
3. Brackets 1.13
4. Atom 1.33.
5. Komodo Edit 11.1.
6. Notepad++ 7.6.
7. BBEdit 12.
8. TextMate 2.0
9. Emacs
10. Vim (and variants)
JavaScript Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but
it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.
Language − This attribute specifies what scripting language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this
attribute.
Type − This attribute is what is now recommended to indicate the scripting language in use and its value
should be set to "text/javascript".
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
JavaScript Literals
The two most important syntax rules for fixed values are:
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed. The var keyword tells the browser
to create variables:
JavaScript Identifiers
Identifiers are names. In JavaScript, identifiers are used to name variables (and keywords, and
functions, and labels). The rules for legal names are much the same in most programming languages. In
JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($). Subsequent
characters may be letters, digits, underscores, or dollar signs.
Note: Numbers are not allowed as the first character. This way JavaScript can easily distinguish identifiers
from numbers.
1. Hyphens:
first-name, last-name, master-card, inter-city.
Note: Hyphens are not allowed in JavaScript. They are reserved for subtractions.
2. Underscore:
first_name, last_name, master_card, inter_city.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus:
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 treated as a comment. This may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a
single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it should be written
as //-->.
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button under
Active scripting.
JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox:
If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it gets enabled
upon clicking toggle.
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome:
1. Click the Chrome menu at the top right hand corner of your browser.
2. Select Settings.
3. Click Show advanced settings at the end of the page.
4. Under the Privacy section, click the Content settings button.
5. In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all sites to run
JavaScript (recommended)".
JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera:
To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
Here is an example to show how you can include an external JavaScript file in your HTML code using
script tag and its src attribute.
To use JavaScript from an external file source, you need to write all your JavaScript source code in a
simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can use sayHello
function in your HTML file after including the filename.js file.
The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or
after the </body> close tag, depending on when you want the JavaScript to load.
Generally, JavaScript code can go inside of the document <head> section in order to keep
them contained and out of the main content of your HTML document.
Let’s consider the following blank HTML document with a browser title of Today's Date:
Right now, this file only contains HTML markup. Let’s say we would like to add the following JavaScript
code to the document:
This will enable the webpage to display an alert with the current date regardless of when the user loads
the site.
In order to achieve this, we will add a <script> tag along with some JavaScript code into the HTML
file.
To begin with, we’ll add the JavaScript code between the <head> tags, signaling the browser to run
the JavaScript script before loading in the rest of the page. We can add the JavaScript below the <title>
tags, for instance, as shown below:
You can also experiment with putting the script either inside or outside the <body> tags and reload
the page. As this is not a robust HTML document, you likely will not notice any difference in the loading of
the page.
If we were modifying what is shown in the body of the HTML, we would need to implement that after the
<head> section so that it displays on the page, as in the example below:
To demonstrate how to connect a JavaScript document to an HTML document, let’s create a small web
project. It will consist of script.js in the js/ directory, style.css in the css/ directory, and a main
index.html in the root of the project.
We can start with our previous HTML template from the given first example:
We can add a reference to this script to or below the <body> section, with the following line of code:
The <script> tag is pointing to the script.js file in the js/ directory of our web project.
Let’s look at this line in the context of our HTML file, in this case, below the <body> section:
We can reference that CSS file within the <head> section of our HTML document:
Now, with the JavaScript and CSS in place we can load the index.html page into the web browser of our
choice. We should see a page that looks similar to the following:
JavaScript Functions
A function is a group of reusable code which can be called anywhere in your program. This eliminates
the need of writing the same code again and again. It helps programmers in writing modular codes.
Functions allow a programmer to divide a big program into a number of small and manageable
functions.
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is
executed when "something" invokes it (calls it).
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 parameters are listed inside the parentheses () in the function definition.
Function arguments are the 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:
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.
Activity
Using the previous Slam Note activity, enhance the webpage by applying basic JavaScript Syntax.
Use only HMTL, CSS tags, elements and JavaScript Syntax.