Module 2
Module 2
JAVASCRIPT
2
• JavaScript is a high-level, object-oriented programming language that creates dynamic and interactive
websites. Brendan Eich developed it in the mid-1990s, and it has since become an essential tool for web
development.
• It runs in the user’s web browser and can manipulate a web page’s Document Object Model (DOM) to
provide interactive behavior.
• One can also use it on the server side through Node.js, a JavaScript runtime built on Chrome’s V8 JavaScript
engine.
• JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator (embedded in
the browser) is responsible for translating the JavaScript code for the web browser.
3
• What is JavaScript
• JavaScript (js) is a light-weight object-oriented programming language
which is used by several websites for scripting the webpages.
• It is an interpreted, full-fledged programming language that enables
dynamic interactivity on websites when applied to an HTML document.
• It was introduced in the year 1995 for adding programs to the webpages in
the Netscape Navigator browser. Since then, it has been adopted by all other
graphical web browsers.
• With JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional website uses
js to provide several forms of interactivity and simplicity.
4
• Although, JavaScript has no connectivity with Java programming language. The name was suggested and
provided in the times when Java was gaining popularity in the market. In addition to web browsers, databases
such as CouchDB and MongoDB uses JavaScript as their scripting and query language
• Features of JavaScript
• There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming
language.
3. JavaScript is an object-oriented programming language that uses prototypes rather than using classes for
inheritance.
4. It is a light-weighted and interpreted language.
5. It is a case-sensitive language.
6. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
7. It provides good control to the users over the web browsers.
5
• Application of JavaScript
• JavaScript is used to create interactive websites. It is mainly used for
• client-side validation,
• Dynamic drop-down menus,
• Displaying date and time,
• Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
• Displaying clocks etc.
1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>
6
• The script tag specifies that we are using JavaScript.
• The text/javascript is the content type that provides information to the
browser about the data.
• The document.write() function is used to display dynamic content through
JavaScript. We will learn about document object in detail late
7
• JavaScript: Client side Vs. Server side
• Client side programming includes any coding or computation or effects or animation or any
sort of interaction your website performs with the user via browser . But server side
programming is that which performs all the task in the server only .
• So the user is unaware of that. Few years ago JavaScript compilers were available only on
the client machine (browsers). So java script was called as a client side scripting language.
On the client side JavaScript is run by v8 engine (Google chrome).
• But now in the server side also JavaScript is used. The v8 engine (with some modifications
to provide the server functionality) is also used in the servers to run js codes. So, in both
cases the language is the same, only the environment is different.
8
• Client-side JavaScript
• Client-side JavaScript refers to JavaScript code that is executed on the
user's web browser. It's used to enhance the functionality
and interactivity of web pages without requiring communication
with the server. Common uses of client-side JavaScript include form
validation, dynamic content updates, and user interface enhancements.
In this example, when the "Click me"
button is clicked, the client-side JavaScript
code prompts the user for their name and
displays a greeting using an alert box, all
within the user's browser.
9
• Server-side JavaScript
• Server-side JavaScript refers to JavaScript code that is executed on the
server, usually in response to HTTP requests. It's used to generate
dynamic content, handle data processing, and interact with databases.
Server-side JavaScript is often used in conjunction with server-side
frameworks and technologies like Node.js to build web applications
and APIs.
10
11
• Client side Vs. Server side
• Location of Execution
1. Client-side JavaScript runs in the user's web browser.
2. Server-side JavaScript runs on the web server.
• Purpose
1. Client-side JavaScript enhances user interactivity and experience
within the browser.
2. Server-side JavaScript is used to generate dynamic content, process
data, and handle server-side tasks.
12
• Access to Resources
1. Client-side JavaScript has access to the browser's Document Object Model (DOM) and can
manipulate webpage content.
2. Server-side JavaScript can access databases, file systems, and other server resources.
• Communication
1. Client-side JavaScript communicates with the server via AJAX requests or by loading new
pages.
2. Server-side JavaScript processes client requests and sends responses back to the client.
• Conclusion
• Client-side JavaScript focuses on enhancing the user experience within the browser,
while server-side JavaScript is used to manage server-related tasks and generate dynamic
content on the server before sending it to the client.
13
14
• JavaScript Variable
1. JavaScript variable
2. JavaScript Local variable
3. JavaScript Global variable
• A JavaScript variable is simply a name of storage location. There are two types
of variables in JavaScript : local variable and global variable.
• There are some rules while declaring a JavaScript variable (also known as
identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variable
15
1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
16
• JavaScript Functions
• JavaScript functions are used to perform operations. We can call
JavaScript function many times to reuse the code.
• Advantage of JavaScript function
• There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save
coding.
2. Less coding: It makes our program compact. We don’t need to write
many lines of code each time to perform a common task.
17
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
18
• Object-Oriented Programming (OOP) is essentially a programming
paradigm that organises code into reusable, self-contained objects.
In this example, person is an object with properties such as name, age, and profession. Each property
has a corresponding value.
Classes in JavaScript
getAge() {
const currentYear = new Date().getFullYear();
return currentYear - this.year;
}
static isOld(car) {
return car.getAge() >= 10;
}
}
• It also has a getAge() method that calculates the age of the car based
on the current year.
• This means that the same function or method can be used with different
object types, as long as they support the required interface or share a
common set of methods.
• This flexibility enables code to work with objects of multiple types without
explicitly checking their specific types. Polymorphism can enhance code
readability, simplify code maintenance, and enable the creation of more
generic and reusable functions
• Abstraction
• Abstraction focuses on simplifying complex systems by breaking them
down into smaller, more manageable modules.
this.getDetails_access = function () {
return (`First name is: ${firstname}, Last
name is: ${lastname}`);
}
}
let person1 = new person('Mukul', 'Latiyan');
console.log(person1.firstname);
console.log(person1.getDetails_noaccess);
console.log(person1.getDetails_access());
• In this example, we try to access some property(person1.firstname)
and functions(person1.getDetails_noaccess) but it returns undefined
while there is a method that we can access from the person
object(person1.getDetails_access()).
• Static data refers to data whose size is known by the engine during compile
time.
• const name="Ram"
• // Allocates memory for object in heap.Values
• // in object are primitive,which is why they are stored in stack.
• function getname(name) {
• return name;
•}
• // The function return value is given to stack after
• // being evaluated in the heap
• By combining these technologies, web pages appear more responsive since small
packets of data are exchanged with the server and web pages are not reloaded each
time that a user makes an input change.
• Ajax enables a web application user to interact with a web page without the
interruption of constant web page reloading.
• Website interaction happens quickly with only portions of the page reloading and
refreshing.
• Ajax is made up of the following technologies :XHTML and CSS for
presenting information.
• Document Object Model (DOM) for dynamically interacting with
and displaying the presented information.
• XMLHttpRequest object to manipulate data asynchronously with
the web server.
• XML, HTML, and XSLT for data interchange and manipulation.
• JavaScript for binding data requests and information display.
<!DOCTYPE html>
<html>
<body>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
Ajax limitations
• Usually, create this object and use it to call the methods which result in effective
communication. All modern browsers support the XMLHttpRequest object.
• Basic Syntax: The syntax of creating the object is given below
•
req = new XMLHttpRequest();
• There are two types of methods open() and send().
• Uses of these methods explained below.
• Use POST as well depending upon whether send the data through
POST or GET method.
• The second parameter being the name of the file which actually handles the
requests and processes them.
• The third parameter is true, it tells that whether the requests are processed
asynchronously or synchronously.
• The open() method prepares the request before sending it to the server. The
send method is used to send the request to the server.
jQuery
• $("p").click();
• The next step is to define what should happen when the event fires.
You must pass a function to the event:
•
$("p").click(function(){
// action goes here!!
});
click()
The click() method attaches an event handler function to an
HTML element.
The function is executed when the user clicks on the HTML
element.
The following example says: When a click event fires on
a <p> element; hide the current <p> element:
• $("p").click(function(){
$(this).hide();
});
dblclick()
The dblclick() method attaches an event
handler function to an HTML element.
The function is executed when the user
double-clicks on the HTML element:
• $("p").dblclick(function(){
$(this).hide();
});
mouseenter()
The mouseenter() method attaches an event handler function
to an HTML element.
The function is executed when the mouse pointer enters the
HTML element:
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
• JSON stands for JavaScript Object Notation
• JSON is a text format for storing and transporting data
• JSON is "self-describing" and easy to understand
• This example is a JSON string:
• '{"name":"John", "age":30, "car":null}'
• It defines an object with 3 properties:
• name
• age
• car
• Each property has a value.
• If you parse the JSON string with a JavaScript program,
you can access the data as an object:
• let personName = obj.name;
let personAge = obj.age;
• What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent *
• Storing Data
• When storing data, the data has to be a certain format,
and regardless of where you choose to store it, text is
always one of the legal formats.
• JSON makes it possible to store JavaScript objects as
text.
Why Use JSON?
The JSON format is syntactically similar to the code for creating
JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into
JavaScript objects.
Since the format is text only, JSON data can easily be sent between
computers, and used by any programming language.
JavaScript has a built in function for converting JSON strings into
JavaScript objects:
JSON.parse()
JavaScript also has a built in function for converting an object into a
JSON string:
JSON.stringify()
• JSON format has a syntax nearly identical to the code for
JavaScript objects.
• This similarity makes it very easy for programs written in
JavaScript to be converted to a JSON data format.
• Even though JSON is derived from JavaScript object notation
syntax, JSON is a text-only subset of JavaScript syntax.
• In JSON, data is represented in name/value pairs separated by a
comma.
• The curly bracket contains the object and is separated from the
name by a colon.
• Square brackets hold arrays, and a comma separates the array
from values.
•
Here is an example:
• “movie”: [
• {
• “season”: “01”,
• “language”: “english”,
• “episode”: “second”,
• “director”: “Robert Anderson”
• }
•]
• JSON is built on two structures which are
• An ordered list of values, which translates to arrays, vectors,
lists, or sequences.
• A collection of name/value pairs; can be an object, record, hash
table, etc.
• Uses of JSON
• JSON is widely used all over the world, and this reflects how
important it has become in today’s world. It gained so much
popularity because of its ease of use and simplicity. The JSON
data format replaced XML, which was formally in use but was
very heavy and difficult to learn due to several modifications.
On the other hand, JSON makes data transfer a walk in the park.
The syntax is straightforward to learn, lightweight, and
compatible with human and machine languages.
• The most common uses of JSON include:
• It is used in writing JavaScript-based applications that have
websites and browser extensions as part of their features.
• It is essential in the transfer of structured data across network
connections.
• It is used to draw up data from a server by web applications.
• Types of JSON Data
• JavaScript Object Notation is currently a widely used data format for
any data exchange on the World Wide Web. This data format is easy
to understand, with seven different data types. They are;
1. Number
2. String
3. Boolean
4. Array
5. Object
6. Whitespace
7. Null
• User Interface (UI) Components
• Overview
• User interface (UI) components make up the visual aspect of your
app. Combine, style and customize Thunkable UI components to give
your app personality and style that best suits your brand.
• Properties Panel
• Each UI component you add to your app has an associated properties
panel unique to that component. Using the various settings in the
properties panel, you can style and customize your Thunkable UI
components to give your app personality and style that best suits
your brand.
• A label's properties panel is displayed on the right in the example
below. Note its unique properties, such as the label's text, font, color,
etc.