0% found this document useful (0 votes)
129 views19 pages

Module 4 - Introduction To JavaScript

JavaScript is a lightweight programming language used to make web pages interactive. It was initially created to manipulate HTML pages but has now evolved into a fully independent language. JavaScript can be used for both client-side scripting within web browsers and server-side scripting using Node.js. It allows for dynamic interactions, validation of form inputs before submission, and asynchronous loading of data to provide a rich user experience. While powerful, JavaScript has limitations as a client-side only language without access to low-level system functions or multi-threading capabilities.

Uploaded by

Mr. Epiphany
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
129 views19 pages

Module 4 - Introduction To JavaScript

JavaScript is a lightweight programming language used to make web pages interactive. It was initially created to manipulate HTML pages but has now evolved into a fully independent language. JavaScript can be used for both client-side scripting within web browsers and server-side scripting using Node.js. It allows for dynamic interactions, validation of form inputs before submission, and asynchronous loading of data to provide a rich user experience. While powerful, JavaScript has limitations as a client-side only language without access to low-level system functions or multi-threading capabilities.

Uploaded by

Mr. Epiphany
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Republic of the Philippines

CAVITE STATE UNIVERSITY


Silang Campus
Biga I, Silang, Cavite
 046 513-5706  046 513-3965
✉ cvsusilang@cvsu.edu.ph

DEPARTMENT OF INFORMATION TECHNOLGY

ITEC50 – Web System Technologies

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

After working on this module, you will be able to:


1. Knowledgeable in JavaScript and be able to apply in Web Development;
2. Apply basic syntax and statements

What is JavaScript?

 JavaScript was initially created to “make web pages alive”.

 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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


 Client-side JavaScript extends the core language by supplying objects to control a
browser and its Document Object Model (DOM). For example, client-side extensions allow
an application to place elements on an HTML form and respond to user events such as mouse
clicks, form input, and page navigation.
 Server-side JavaScript extends the core language by supplying objects relevant to
running JavaScript on a server. For example, server-side extensions allow an application to
communicate with a database, provide continuity of information from one invocation to another
of the application, or perform file manipulations on a server.

Why is it called JavaScript?

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.

Why to Learn JavaScript

 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.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


What can in-browser JavaScript do?
 Modern JavaScript is a “safe” programming language. It does not provide low-level access
to memory or CPU, because it was initially created for browsers which do not require it.

 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.

For instance, in-browser JavaScript is able to:

 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”).

Applications of JavaScript Programming


As mentioned before, JavaScript is one of the most widely used programming languages (Front-end as
well as Back-end). It has it's presence in almost every area of software development. I'm going to list few
of them here:

 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.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.

 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.

 JavaScript doesn't have any multi-threading or multiprocessor capabilities.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


The 10 best JavaScript editors

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.

The script tag takes two important attributes:

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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


JavaScript Values
The JavaScript syntax defines two types of values:

 Fixed values - Fixed values are called Literals.


 Variable values – Variable values are called Variables.

JavaScript Literals
The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

2. Strings are text, written within double or single quotes:

JavaScript Variables
In a programming language, variables are used to store data values.

 JavaScript uses the var keyword to declare variables.


 An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:

JavaScript uses an assignment operator ( = ) to assign values to variables:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value. The
computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

Expressions can also contain variable values:

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe"

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.

JavaScript is Case Sensitive


All JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different
variables:

JavaScript does not interpret VAR or Var as the keyword var.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


JavaScript and Camel Case
Historically, programmers have used different ways of joining multiple words into one variable name:

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.

3. Upper Camel Case (Pascal Case)


FirstName, LastName, MasterCard, InterCity.

4. Lower Camel Case


firstName, lastName, masterCard, interCity.
JavaScript programmers tend to use camel case that starts with a lowercase letter:

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 //-->.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


Enabling JavaScript in Browsers
All the modern browsers come with built-in support for JavaScript. Frequently, you may need to enable or
disable this support manually. This chapter explains the procedure of enabling and disabling JavaScript
support in your browsers: Internet Explorer, Firefox, chrome, and Opera.

JavaScript in Internet Explorer


Here are simple steps to turn on or turn off JavaScript in your Internet Explorer:

1. Follow Tools → Internet Options from the menu.


2. Select Security tab from the dialog box.
3. Click the Custom Level button.
4. Scroll down till you find Scripting option.
5. Select Enable radio button under Active scripting.
6. Finally click OK and come out

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:

1. Open a new tab → type about: config in the address bar.


2. Then you will find the warning dialog. Select I’ll be careful, I promise!
3. Then you will find the list of configure options in the browser.
4. In the search bar, type javascript.enabled.
5. There you will find the option to enable or disable javascript by right-clicking on the value of that
option → select toggle.

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:

1. Follow Tools → Preferences from the menu.


2. Select Advanced option from the dialog box.
3. Select Content from the listed items.
4. Select Enable JavaScript checkbox.
5. Finally click OK and come out.

To disable JavaScript support in your Opera, you should not select the Enable JavaScript checkbox.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


JavaScript - Placement in HTML File
There is a flexibility given to include JavaScript code anywhere in an HTML document. However, the most
preferred ways to include JavaScript in an HTML file are as follows:

 Script in <head>...</head> section.

 Script in <body>...</body> section.

 Script in <body>...</body> and <head>...</head> sections.

 Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can place JavaScript in an HTML file in different ways.

JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere, then you will
place that script in the head as follows:

This code will produce the following results:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in the page, then the
script goes in the <body> portion of the document. In this case, you would not have any function defined
using JavaScript. Take a look at the following code.

JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that there are cases where
you are reusing identical JavaScript code on multiple pages of a site. You are not restricted to be
maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to
store JavaScript in an external file and then include it into your HTML files.

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.

Adding JavaScript into an HTML Document


You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script>
that wraps around JavaScript code.

 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.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


 However, if your script needs to run at a certain point within a page’s layout — like when using
document.write to generate content — you should put it at the point where it should be called,
usually within the <body> section.

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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


Once you load the page, you will receive an alert that will look similar to this:

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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


The output for the above HTML document loaded through a web browser would look similar to the
following:

Working with a Separate JavaScript File


In order to accommodate larger scripts or scripts that will be used across several pages, JavaScript code
generally lives in one or more js files that are referenced within HTML documents, similarly to how
external assets like CSS are referenced.

The benefits of using a separate JavaScript file include:


 Separating the HTML markup and JavaScript code to make both more straightforward
 Separate files make maintenance easier
 When JavaScript files are cached, pages load more quickly

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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


Now, let’s move our JavaScript code that will show the date as an <h1> header to the script.js file:

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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


Finally, let’s also edit the style.css file by adding a background color and style to the <h1> header:

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:

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


Now that we’ve placed the JavaScript in a file, we can call it in the same way from additional web pages
and update them all in a single location

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).

JavaScript Function Syntax


 A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

 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,
...)

 The code to be executed, by the function, is placed inside curly brackets: {}

 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:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self-invoked)

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.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021


(Once the button clicked)

Activity

Using the previous Slam Note activity, enhance the webpage by applying basic JavaScript Syntax.
Use only HMTL, CSS tags, elements and JavaScript Syntax.

ITEC 50 WEB SYSTEMS TECHNOLOGIES P. MAGNO SECOND SEMESTER AY 2020-2021

You might also like