0% found this document useful (0 votes)
16 views98 pages

Module 2

JavaScript is a high-level, object-oriented programming language primarily used for creating dynamic and interactive websites, developed by Brendan Eich in the mid-1990s. It can be executed on both client-side (in web browsers) and server-side (using Node.js), allowing for features like DOM manipulation and dynamic content generation. Key concepts include variables, functions, object-oriented programming principles, and automatic memory management through garbage collection.

Uploaded by

Aditya Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views98 pages

Module 2

JavaScript is a high-level, object-oriented programming language primarily used for creating dynamic and interactive websites, developed by Brendan Eich in the mid-1990s. It can be executed on both client-side (in web browsers) and server-side (using Node.js), allowing for features like DOM manipulation and dynamic content generation. Key concepts include variables, functions, object-oriented programming principles, and automatic memory management through garbage collection.

Uploaded by

Aditya Sinha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

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.

• Developers primarily use JavaScript for client-side scripting.

• 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 an object-based scripting language which is lightweight and cross-platform.

• 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

• 3 Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

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.

• It focuses on the concept of objects, which represent real-world


entities with their own attributes (data) and behaviours (methods).
• The four pillars of OOP
• a) Encapsulation
• b) Inheritance
• c) Polymorphism
• d) Abstraction
• OOP allows developers to write modular, maintainable, and scalable
code by promoting code reusability and encapsulation.

• OOP Concepts in JavaScript can be defined as the concepts that


promote Object-Oriented Programming in JavaScript
• Objects and classes in JavaScript
• Before we delve into the main OOPS Concepts in JavaScript with
examples, we will first explore what objects and classes are.
• Objects in JavaScript
• In JavaScript, objects are crucial for creating complex data structures
and modelling real-world concepts. They are collections of key-value
pairs, where the keys are known as properties and the values can be of
any data type, including other objects or functions.
• Creating objects:

• JavaScript offers multiple ways to create objects.


• One common method is using object literals, which allow you to
define an object and its properties in a concise manner.
• For example:
“const person = {
name: "John",
age: 25,
profession: "Engineer"
};”

In this example, person is an object with properties such as name, age, and profession. Each property
has a corresponding value.
Classes in JavaScript

• Now that we know what an object is, we will define a class.

• In JavaScript, a class is a blueprint for creating objects with shared


properties and methods.

• It provides a structured way to define and create multiple instances of


similar objects
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}

getAge() {
const currentYear = new Date().getFullYear();
return currentYear - this.year;
}

static isOld(car) {
return car.getAge() >= 10;
}
}

const myCar = new Car("Toyota", "Camry", 2018);


console.log(myCar.getAge()); // Output: 5
console.log(Car.isOld(myCar)); // Output: false
• In this example, the Car class has a constructor that takes the make,
model, and year as parameters and initialises the respective properties.

• It also has a getAge() method that calculates the age of the car based
on the current year.

• The isOld() method is a static method that determines if a car instance


is considered old.
• Encapsulation
• Encapsulation is defined as the process of bundling data and methods
together within a single unit, known as an object.

• It allows for the organisation of related data and operations, promoting


code modularity and reusability
• . Encapsulation provides two key benefits: data hiding and access
control.
• By encapsulating data, an object's internal state is hidden from external
entities.
• This ensures that the data can only be accessed and modified through
defined methods, preventing direct manipulation and maintaining data
integrity.

• Access control mechanisms, such as private and public modifiers, allow


developers to control the visibility and accessibility of object members.

• Encapsulation in JavaScript can be achieved using techniques like closures,


IIFE (Immediately Invoked Function Expressions), and modules.
• // Encapsulation example
• class person {
• constructor(name, id) {
• this.name = name;
• this.id = id;
• }
• add_Address(add) {
• this.add = add;
• }
• getDetails() {
• console.log(`Name is ${this.name},
• Address is: ${this.add}`);
• }
• }
• let person1 = new person('Mukul', 21);
• person1.add_Address('Delhi');
• person1.getDetails();
• inheritance
• Inheritance is a mechanism that allows objects to acquire properties
and methods from a parent object, known as a superclass or base class.
It promotes code reuse and hierarchical relationships between objects.
• In JavaScript, inheritance is implemented through prototypal inheritance.
• Each object has an associated prototype object, and properties and methods not
found in the object itself are inherited from the prototype.
• This enables objects to share common functionality while maintaining the ability
to add or override specific behaviours.
• By leveraging inheritance, developers can reduce code duplication, enhance code
organisation, and establish relationships between objects based on their
similarities and hierarchies.
// Inheritance example
class person {
constructor(name) {
this.name = name;
}
// method to return the string
toString() {
return (`Name of person: ${this.name}`);
}
}
class student extends person {
constructor(name, id) {
// super keyword for calling the above
// class constructor
super(name);
• Polymorphism
• Polymorphism enables objects of different types to be treated as
interchangeable entities.

• It allows for flexibility in code design and promotes code


extensibility.
• In JavaScript, polymorphism is inherent due to the language's dynamic
typing nature.

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

• It involves defining essential characteristics and behaviours while


hiding unnecessary implementation details.
• In JavaScript, abstraction can be achieved through abstract classes and
interfaces.

• Abstract classes provide a blueprint for creating derived classes, defining


common methods and properties that must be implemented by subclasses.

• Interfaces, although not natively supported in JavaScript, can be emulated


using object literals or documentation to define expected properties and
methods.
// Abstraction example
function person(fname, lname)
{
let firstname = fname;
let lastname = lname;
let getDetails_noaccess = function ()
{
return (`First name is: ${firstname} Last
name is: ${lastname}`);
}

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

• By changing the way we define a function we can restrict its scope.


What is memory management?

• The practice of managing and coordinating memory in your


software is known as memory management.

• It makes sure that memory blocks are correctly managed and


distributed so that the application and other processes that are
currently running have the memory they require to complete
their tasks.
• Memory management in JavaScript is handled automatically by the
runtime environment, typically the JavaScript engine in web browsers
or Node.js.

• JavaScript uses a garbage collector to manage memory and ensure that


developers do not need to manually allocate or deallocate memory.
• When a user visits a website or an application, two things
matter to the user:
1. How long it will take the application to open.
2. The amount of memory space that will be consumed by the
program.
• Every user who visits an application deserves a rich and
interactive experience.
• They want an application to multitask with other applications
that are open on its system simultaneously. This can be done
by proper memory management in your program.
• Memory Life Cycle
• Irrespective of the programming language, the memory life cycle follows
the following stages:
1. Allocates the memory we need: JavaScript allocates memory to the object
created.
2. Use the allocated memory.
3. Release the memory when not in use: Once the allocated memory is
released, it is used for other purposes. It is handled by a JavaScript engine.
• The second stage is the same for all the languages. However, the first and
last stages are implicit in high-level languages like JavaScript.
• JavaScript engines have two places to store data
• Stack: It is a data structure used to store static data.

• Static data refers to data whose size is known by the engine during compile
time.

• In JavaScript, static data includes primitive values like strings, numbers,


boolean, null, and undefined.

• References that point to objects and functions are also included.

• A fixed amount of memory is allocated for static data. This process is


known as static memory allocation.
• Heap: It is used to store objects and functions in JavaScript.

• The engine doesn’t allocate a fixed amount of memory.

• Instead, it allocates more space as required.


• References in JavaScript memory management
• All variables start by pointing to the stack.
• A reference to the item in the heap is stored in the stack if the
value is not primitive.
• We need to maintain a reference to the heap in the stack since
the memory of the JavaScript heap is not organized in any
specific way.
• The objects in the heap can be compared to residences, with
references serving as the references' addresses.
JavaScript allocates memory for objects within the heap, but we must have a reference to that memory location to access the
value. The reference to the memory location resides in the stack memory.
• const employee = {
• name: 'Rajesh',
• age: 30,
• };

• 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

• const newEmployee = employee;


AJAX
• Asynchronous JavaScript and XML (Ajax) refer to a group of technologies that are
used to develop web applications.

• 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>

<h1>The XMLHttpRequest Object</h1>

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<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

• While Ajax is a web application development technique that is


designed to make web pages more responsive and interactive with a
user, Ajax has some limitations to consider before you develop an
Ajax-based application.
• The following limitations are some of the more prominent disadvantages:

• Browser support - Not all browsers support JavaScript or XMLHttpRequest object.


• Even among browsers that do have support for JavaScript and XMLHttpRequest, these
objects can be treated differently. Each browser's implementation of Ajax must be
considered.
• Security and user privacy - Not all concerns are addressed. Issues surrounding security
and user privacy need to be considered when developing an Ajax application.
• Accessibility - Because not all browsers have JavaScript or XMLHttpRequest object
support, you must ensure that you provide a way to make the web application accessible
to all users.
• Prerequisites:
There are no such pre-requisites required to understand the latter portion of the article. Only the
basic knowledge of HTML, CSS, and Javascript are good to go.
• How does it work?
First, let us understand what does asynchronous actually mean. There are two types of requests
synchronous as well as asynchronous.
• Synchronous requests are the one which follows sequentially i.e if one process is going on and in
the same time another process wants to be executed, it will not be allowed that means the only one
process at a time will be executed.
• This is not good because in this type most of the time CPU remains
idle such as during I/O operation in the process which are the order of
magnitude slower than the CPU processing the instructions.
• Thus to make the full utilization of the CPU and other resources use
asynchronous calls.
• Actually, the requests are made through the use of javascript functions.
• Now the term XML which is used to create XMLHttpRequest
object.
• summary of the above explanation is that Ajax allows web pages to be updated
asynchronously by exchanging small amounts of data with the server behind the
scenes.
.

• For implementing Ajax, only be aware of XMLHttpRequest object. Now, what


actually it is.
• It is an object used to exchange data with the server behind the scenes.
• Try to remember the paradigm of OOP which says that object communicates
through calling methods (or in general sense message passing).

• The same case applied here as well.

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

• req.open("GET", "abc.php", true);


• req.send();
• The above two lines described the two methods. req stands for the
request, it is basically a reference variable.

• The GET parameter is as usual one of two types of methods to send


the request.

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

• It is by default true which means that requests are asynchronous.

• 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

• jQuery is a fast, small, cross-platform and feature-rich JavaScript


library. It is designed to simplify the client-side scripting of HTML.

• It makes things like HTML document traversal and manipulation,


animation, event handling, and AJAX very simple with an easy-to-use
API that works on a lot of different type of browsers.

• The main purpose of jQuery is to provide an easy way to use


JavaScript on your website to make it more interactive and attractive.
It is also used to add animation.
• Why jQuery is required
• Sometimes, a question can arise that what is the need of jQuery or what
difference it makes on bringing jQuery instead of AJAX/ JavaScript? If
jQuery is the replacement of AJAX and JavaScript? For all these questions,
you can state the following answers.
• It is very fast and extensible.
• It facilitates the users to write UI related function codes in minimum
possible lines.
• It improves the performance of an application.
• Browser's compatible web applications can be developed.
• It uses mostly new features of new browsers.
• JQuery events are the actions that can be detected by your web
application.
• They are used to create dynamic web pages.
• An event shows the exact moment when something happens
• In jQuery, most DOM events have an equivalent jQuery
method.
• To assign a click event to all paragraphs on a page, you
can do this:

• $("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.

You might also like