Unit 2 Notes-2
Unit 2 Notes-2
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.
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Code Output
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part
of web pages, whose implementations allow client-side script to interact with the user and make dynamic
pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of
the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with
the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.
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.
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
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.
• Once again, JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
2.1.3 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.
<script ...>
JavaScript code
</script>
2.1.4 Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as named
containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var
keyword as follows.
You can also declare multiple variables with the same var keyword as follows −
While naming your variables in JavaScript, keep the following rules in mind.
• You should not use any of the JavaScript reserved keywords as a variable name. These keywords are
mentioned in the next section. For example, break or boolean variable names are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an
underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
• JavaScript variable names are case-sensitive. For example, Name and name are two different variables.
To be able to operate on variables, it is important to know something about the type. Without data types, a
computer cannot safely solve this:
let x = 16 + “Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?
JavaScript will treat the example above as:
Code:
<!DOCTYPE html>
<html>
<body>
<p>JavaScript has dynamic types. This means that the same variable can be used
to hold different data types:</p>
<p id="demo"></p>
<script>
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Output:
John
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
2.1.6 Statements
JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments. This
statement tells the browser to write "Hello Dolly." inside an HTML element with id=“demo":
Code
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
Output
JavaScript Statements
JavaScript statements are separated by semicolons.
11
2.1.7 Operators
Arithmetic operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y
Operator Description
`== equal to
`=== equal value and equal type
!= not equal
Operato Description
&& logical and
|| logical or
! logical not
Operator Description
typeof Returns the type of a variable
2.1.8 Literals
JavaScript Literals are the fixed value that cannot be changed, you do not need to specify any type of keyword
to write literals. Literals are often used to initialize variables in programming, names of variables are string
literals.
• String Literal
• Array Literal
• Regular Expression Literal
• Object Literal
2.1.9 Functions
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: {}
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking
statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
12
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
2.1.10 Objects
In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is called a property.
The key of a property can be a string. And the value of a property can be any value, e.g., a string, a number,
an array, and even a function.
JavaScript provides you with many ways to create an object. The most commonly used one is to use the
object literal notation.
The following example creates an empty object using the object literal notation:
let empty = {};
To create an object with properties, you use the key:value within the curly braces. For example, the following
creates a new person object:
let person = {
firstName: 'John',
lastName: 'Doe'
};
The person object has two properties firstName and lastName with the corresponding values 'John' and 'Doe'.
When an object has multiple properties, you use a comma (,) to separate them like the above example.
Accessing properties
To access a property of an object, you use one of two notations: the dot notation and array-like notation.
1) The dot notation (.)
The following illustrates how to use the dot notation to access a property of an object:
objectName.propertyName
For example, to access the firstName property of the person object, you use the following expression:
person.firstName
This example creates a person object and shows the first name and last name to the console:
let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person.firstName);
console.log(person.lastName);
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Code
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
</body>
</html>
Output:
JavaScript Objects
John is 50 years old.
2.1.11 Arrays
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like
this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but
300?
The solution is an array!
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
An array can hold many values under a single name, and you can access the values by referring to an index
number.
Code:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Output:
JavaScript Arrays
Saab,Volvo,BMW
• Built-in objects are not related to any Window or DOM object model.
• These objects are used for simple data processing in the JavaScript.
1. Math Object
• Math object is a built-in static object.
• It is used for performing complex math operations.
Math Properties
PI Returns Π value.
Math Methods
Methods Description
2. Date Object
Syntax:
var variable_name = new Date();
Example:
var current_date = new Date();
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Date Methods
Methods Description
getTime() Returns the number of milliseconds since January 1, 1970 at 12:00 AM.
getTimezoneOffset( Returns the timezone offset in minutes for the current locale.
)
3. String Object
Syntax:
var variable_name = new String(string);
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Example:
var s = new String(string);
String Properties
Properties Description
constructor It returns the reference to the String function that created the object.
String Methods
Methods Description
charCodeAt It returns the ASCII code of the character at the specified position.
()
concat() It combines the text of two strings and returns a new string.
split() It splits a string object into an array of strings by separating the string into the
substrings.
2.1.12 Debuggers
Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.
Built-in debuggers can be turned on and off, forcing errors to be reported to the user.
With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine
variables while the code is executing.
Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your browser with
the F12 key, and select "Console" in the debugger menu.
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Code:
<!DOCTYPE html>
<html>
<body>
<p>Activate debugging in your browser (Chrome, IE, Firefox) with F12, and select
"Console" in the debugger menu.</p>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Output:
When a web page is loaded, the browser creates a Document Object Model of the page.
DOM TREE :
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
markup, for better readability and allows you to add event listeners even when you do not control the HTML
markup.
You can easily remove an event listener by using the removeEventListener() method.
Code :
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add many events on the
same button.</p>
<p id="demo"></p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>";
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>";
}
function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>
</body>
</html>
Output:
JavaScript addEventListener()
This example uses the addEventListener() method to add many events on the same button.
Try it
Moused over!
Moused out!
Moused over!
Moused out!
Moused over!
Moused out!
Code:
<!DOCTYPE html>
<html>
<body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Output:
My Heading 1
Click Me!
2.3 jQuery
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery is a lightweight, "write less, do more", JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on your website.
jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them
into methods that you can call with a single line of code.
jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
The jQuery library contains the following features:
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities
There are lots of other JavaScript libraries out there, but jQuery is probably the most popular, and also the
most extendable.
Many of the biggest companies on the Web use jQuery, such as:
• Google
• Microsoft
• IBM
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
• Netflix
There are several ways to start using jQuery on your web site. You can:
• Download the jQuery library from jQuery.com
• Include jQuery from a CDN, like Google
Downloading jQuery
There are two versions of jQuery available for downloading:
• Production version - this is for your live website because it has been minified and compressed
• Development version - this is for testing and development (uncompressed and readable code)
Both versions can be downloaded from jQuery.com.
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice
<head>
<script src="jquery-3.5.1.min.js"></script>
</head>
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/
jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
<button>Click me</button>
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
</body>
</html>
Output:
This is a heading
Click me
2.4 Angular JS
AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It
extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is
open source, completely free, and used by thousands of developers around the world. It is licensed und er the
Apache license version 2.0.
AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
AngularJS provides developers an options to write client side applications using JavaScript in a clean Model
View Controller (MVC) way.
Applications written in AngularJS are cross-browser compliant. AngularJS automatically handles JavaScript
code suitable for each browser.
AngularJS is open source, completely free, and used by thousands of developers around the world. It is
licensed under the Apache license version 2.0.
Dr. D. Y. Patil Institute of Technology Unit 2 Notes Web Technology
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain web
applications.
Code:
<html>
<head>
<title>AngularJS First Application</title>
</head>
<body>
<h1>Sample Application</h1>
</body>
</html>
Output: