JavaScript Notes
JavaScript Notes
Definition
JavaScript is a lightweight, interpreted programming language. It is commonly
used to create dynamic and interactive elements in web applications. JavaScript is
very easy to implement because it is integrated with HTML. It is open and cross-
platform.
• 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 is in all over the world, and companies like Google, Meta,
Microsoft, PayPal, LinkedIn, etc. also use JavaScript.
• Furthermore, JavaScript has more than 1.5 lakh libraries. It is also growing.
• 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 presentation.
• 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.
• Machine learning − Developers can use the ML5.js library to complete the
task related to machine learning.
• Game Developments − JavaScript contains multiple libraries and NPM
packages to design graphics for the game. We can use HTML, CSS, and
JavaScript with libraries to develop the games.
• Mobile applications − We can use frameworks like React Native to build
feature-rich mobile applications.
• Internet of Things (IoT) − JavaScript is used to add functionality to
devices like smartwatches, earbuds, etc.
• Data visualization − JavaScript contains the libraries like D3.js to visualize
the data efficiently. The D3.js is also used to prepare high-quality charts to
visualize the data.
• Cloud computing − We can use JavaScript in serverless computing
platforms like Cloudflare and AWS lambda to write and deploy functions on
the cloud.
This list goes on, there are various areas where millions of software developers are
happily using JavaScript to develop great websites and other software.
Advantages of JavaScript
The merits of using JavaScript are −
• 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 reasons.
• JavaScript cannot be used for networking applications because no such
support is available.
• JavaScript doesn't have any multi-threading capabilities.
Once again, JavaScript is a lightweight, interpreted programming language
that allows you to build interactivity into otherwise static HTML pages.
Here are various free tools which can be helpful while developing applications
with JavaScript.
• Visual Studio Code (VS Code) − The VS Code is a code editor used by
most developers to write JavaScript code. It is feature rich and contains
various extensions that can increase the productivity of any developer.
• Chrome dev tools − Programmers may use the Chrome dev tools to debug
the JavaScript code. However, they can use the debugging tool of any
browser as most browser comes with it.
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 a weakly typed language, where certain types are implicitly
cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses
prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
Client-side scripting :
Web browsers execute client-side scripting. It is used when browsers have all
code. Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without
going to the user. It cannot be basically used to connect to databases on a web
server. These scripts cannot access the file system that resides in the web
browser. Pages are altered on basis of the user’s choice. It can also be used to
create “cookies” that store data on the user’s computer.
Client-side scripting simply means running scripts, such as JavaScript, on the
client device, usually within a browser. All kinds of scripts can run on the client
side if they are written in JavaScript, because JavaScript is universally
supported. Other scripting languages can only be used if the user's browser
supports them.
Server-side scripting :
Web servers are used to execute server-side scripting. They are basically used
to create dynamic pages. It can also access the file system residing at the
webserver. A server-side environment that runs on a scripting language is a
web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is
used to require to download plugins. In this load times are generally faster
than client-side scripting. When you need to store and retrieve information a
database will be used to contain data. It can use huge resources of the server. It
reduces client-side computation overhead. The server sends pages to the
request of the user/client.
It does not provide security for data. It provides more security for data.
HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
JavaScript Variables
JavaScript variables are used to store data that can be changed later on. The
ariables 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. In
JavaScript, you can declare the variables in 4 ways −
JavaScript Variables
Variable means anything that can vary. In JavaScript, a variable stores
data that can be changed later on.
Declare a Variable
In JavaScript, a variable can be declared using var, let, const keywords.
• var keyword is used to declare variables since JavaScript was created. It is
confusing and error-prone when using variables declared using var.
• let keyword removes the confusion and error of var. It is the new and
recommended way of declaring variables in JavaScript.
• const keyword is used to declare a constant variable that cannot be changed
once assigned a value.
In the above example, var msg; is a variable declaration. It does not have
any value yet. The default value of variables that do not have any value
is undefined.
You can assign a value to a variable using the = operator when you
declare it or after the declaration and before accessing it.
Example: Variable Initialization
let msg;
msg = "Hello JavaScript!"; // assigning a string value
In the above example, the msg variable is declared first and then assigned
a string value in the next line.
You can declare a variable and assign a value to it in the same line.
Values can be of any datatype such as string, numeric, boolean, etc.
You can copy the value of one variable to another variable, as shown
below.
JavaScript allows multiple white spaces and line breaks when you
declare a variables.
Dynamic Typing
JavaScript is a loosely typed language. It means that you don't need to
specify what data type a variable will contain. You can update the value
of any type after initialization. It is also called dynamic typing.
The value of a constant variable cannot be changed but the content of the
value can be changed. For example, if an object is assigned to a const
variable then the underlying value of an object can be changed.
Variable Scope
In JavaScript, a variable can be declared either in the global scope or the
local scope.
Global Variables
Variables declared out of any function are called global variables. They
can be accessed anywhere in the JavaScript code, even inside any
function.
Local Variables
Variables declared inside the function are called local variables of that
function. They can only be accessed in the function where they are
declared but not outside.
myfunction();
The variables declared without the var keyword become global variables,
irrespective of where they are declared. It is recommended to declare
variable using the let keyword.
myfunction();
alert(msg); // msg becomes global variable so can be accessed here
What is an Operator?
In JavaScript, an operator is a symbol that performs an operation on one or more
operands, such as variables or values, and returns a result. Let us take a simple
expression 4 + 5 is equal to 9. Here 4 and 5 are called operands, and ‘+’ is called
the operator.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Bitwise Operators
• Assignment Operators
• Miscellaneous Operators
Lets have a look on all operators one by one.
z=x+y
will
= (Simple
Assigns values from the right side operand to the left side operand assign the
Assignment)
value of x
+ y into z
z += x is
+= (Add
It adds the right operand to the left operand and assigns the result to the equivalent
and
left operand. to z = z +
Assignment)
x
z -= x is
−= (Subtract
It subtracts the right operand from the left operand and assigns the equivalent
and
result to the left operand. to z = z -
Assignment)
x
z *= x is
*=(Multiply
It multiplies the right operand with the left operand and assigns the equivalent
and
result to the left operand. to z = z *
Assignment)
x
z /= x is
/= (Divide
It divides the left operand with the right operand and assigns the result equivalent
and
to the left operand. to z = z /
Assignment)
x
%= z %= x is
(Modules It takes modulus using two operands and assigns the result to the left equivalent
and operand. to z = z %
Assignment) x
Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=.
JavaScript Miscellaneous Operators
There are few other operators supported by JavaScript. These operators
are conditional operator (? :), typeof operator, delete operator, etc.
In the below table, we have given the JavaScript miscellaneous operators with its
explanation.
Operator Description
Here, we have given a table containing the mathematical operators and explaining
the functionality of each operator.
• If one operand is string, the addition operator converts the other operand to
string and concatenate it with first operand.
• If both the operands are string, it just concatenates the second operand to the
first operand.
• If both operands are numeric values, it will return the numeric value.
• The subtraction operator uses numeric operands but can also be used for
non-numeric operands such as strings.
• If both operands are numbers, then resultant is number.
• If any or both operands are strings (containing only numbers), it first
converts the strings to number and then performs subtraction operations.
• If string contains non numeric value, it will return NaN.
• If any operand is NaN or Infinity, the result will be NaN or Infinity
respectively.
If any or both operands are string, it converts the string to number and then returns
their product.
The prefix increment operator increments the value of the variable before its
current value is used.
The postfix increment operator increments the value of the variable after its current
value is used.
The prefix decrement operator decrements the value of the variable before its
current value is used.
The postfix decrement operator decrements the value of the variable after its
current value is used.
Syntax:
if ( condition ) {
// If the condition is met,
//code will get executed.
}
if (num % 2 === 0) {
console.log("Given number is even number.");
}
if (num % 2 !== 0) {
console.log("Given number is odd number.");
};
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Syntax:
if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// ode for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// ode that will execute if all
// above conditions are false
}
if (num > 0) {
console.log("Given number is positive.");
} else if (num < 0) {
console.log("Given number is negative.");
} else {
console.log("Given number is zero.");
};
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
. . .
case valueN:
statementN;
break;
default:
statementDefault;
};
let Branch;
switch (true) {
case marks >= 90:
Branch = "Computer science engineering";
break;
case marks >= 80:
Branch = "Mechanical engineering";
break;
case marks >= 70:
Branch = "Chemical engineering";
break;
case marks >= 60:
Branch = "Electronics and communication";
break;
case marks >= 50:
Branch = "Civil engineering";
break;
default:
Branch = "Bio technology";
break;
}
Syntax:
condition ? value if true : value if false
Example: In this example, we use the ternary operator to check if the user’s
age is 18 or older. It prints eligibility for voting based on the condition.
let age = 21;
const result =
(age >= 18) ? "You are eligible to vote."
: "You are not eligible to vote.";
console.log(result);
• Alert Box
• Prompt Box
• Confirm Box
Alert Box
It is used when a warning message is needed to be produced. When the alert
box is displayed to the user, the user needs to press ok and proceed.
Syntax:
alert("your Alert here");
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Alert Box</h3>
<button onclick="geekAlert()">
Click here for alert box
</button>
Prompt Box
It is a type of pop up box which is used to get the user input for further use.
After entering the required details user have to click ok to proceed next stage
else by pressing the cancel button user returns the null value.
Syntax:
prompt("your Prompt here");
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Prompt Box</h3>
Syntax:
confirm("your query here");
<head>
<title>
Pop-up Box type | Confirm Box
</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Confirm Box</h3>
<button onclick="geekConfirm()">
Click here for Confirm box
</button>
<p id="geek"></p>
</html>
JavaScript Events
JavaScript Events are actions or occurrences that happen in the browser.
They can be triggered by various user interactions or by the browser itself.
Common events include mouse clicks, keyboard presses, page loads, and form
submissions. Event handlers are JavaScript functions that respond to these
events, allowing developers to create interactive web applications.
Syntax:
<HTML-element Event-Type = "Action to be performed">
<!doctype html>
<html>
<head>
<script>
function hiThere() {
alert('Hi there!');
}
</script>
</head>
<body>
<button type="button"
onclick="hiThere()"
style="margin-left: 50%;">
Click me event
</button>
</body>
</html>
Example 2: Here, we will change the color by pressing UP arrow key using
onkeyup() event. This code defines a JavaScript function
`changeBackground()` that changes the background color of an input box
when the up arrow key is pressed. RGB color values are incremented with
each key press, cycling through colors.
<!doctype html>
<html>
<head>
<script>
let a=0;
let b=0;
let c=0;
function changeBackground() {
let x=document.getElementById('bg');
x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
a+=100;
b+=a+50;
c+=b+70;
if(a>255) a=a-b;
if(b>255) b=a;
if(c>255) c=b;
}
</script>
</head>
<body>
<h4>The input box will change color when UP arrow key is
pressed</h4>
<input id="bg" onkeyup="changeBackground()" placeholder="write
something" style="color:#fff">
</body>
</html>
<script>
// JavaScript function to handle the click event
function myFunction() {
alert("Button clicked!");
}
</script>
</body>
</html>
Syntax:
// To assign event
const startEvent = new Event("start");
// To trigger the event Listener
document.addEventListener("start", () => {
console.log("The start event was triggered")
});
// To trigger the Event
document.dispatchEvent(startEvent);
document.addEventListener('start', ()=>{
console.log("Start event triggered")
});
if(x == 5){
document.dispatchEvent(event);
}
</script>
</body>
</html>
Syntax:
// To assign event
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});
// To trigger the event Listener
document.addEventListener('start', (e)=>{
console.log(
`start event triggered on platform :
${e.detail.platform}`
);
});
// To trigger the Event
document.dispatchEvent(event);
Example: In this example, we are creating a custom event that triggers when
the value of x is 5.
<html>
<body>
<script>
let x = 5;
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});
if (x == 5) {
document.dispatchEvent(event);
}
</script>
</body>
</html>
JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.
• Basic Validation − First of all, the form must be checked to make sure all
the mandatory fields are filled in. It would require just a loop through each
field in the form and check for data.
• Data Format Validation − Secondly, the data that is entered must be
checked for correct form and value. Your code must include appropriate
logic to test correctness of data.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>Form Validation</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>REGISTRATION FORM</h1>
<form
name="RegForm"
onsubmit="return validateForm()"
>
<p>
<label for="name">Name:</label>
<input
type="text"
id="name"
name="Name"
placeholder="Enter your full name"
/>
<span
id="name-error"
class="error-message"
></span>
</p>
<p>
<label for="address"
>Address:</label
>
<input
type="text"
id="address"
name="Address"
placeholder="Enter your address"
/>
<span
id="address-error"
class="error-message"
></span>
</p>
<p>
<label for="email"
>E-mail Address:</label
>
<input
type="text"
id="email"
name="EMail"
placeholder="Enter your email"
/>
<span
id="email-error"
class="error-message"
></span>
</p>
<p>
<label for="password"
>Password:</label
>
<input
type="password"
id="password"
name="Password"
/>
<span
id="password-error"
class="error-message"
></span>
</p>
<p>
<label for="subject"
>Select Your Course: </label
>
<select
id="subject"
name="Subject"
>
<option value="">
Select Course
</option>
<option value="BTECH">
BTECH
</option>
<option value="BBA">
BBA
</option>
<option value="BCA">
BCA
</option>
<option value="B.COM">
B.COM
</option>
</select>
<span
id="subject-error"
class="error-message"
></span>
</p>
<p>
<label for="comment"
>College Name:</label
>
<textarea
id="comment"
name="Comment"
></textarea>
</p>
<p>
<input
type="checkbox"
id="agree"
name="Agree"
/>
<label for="agree"
>I agree to the above
information</label
>
<span
id="agree-error"
class="error-message"
></span>
</p>
<p>
<input
type="submit"
value="Send"
name="Submit"
/>
<input
type="reset"
value="Reset"
name="Reset"
/>
</p>
</form>
<script src="script.js"></script>
</body>
</html>
AngularJS - Overview
AngularJS is a structural framework for dynamic web applications. It lets you use
HTML as your template language and lets you extend HTML's syntax to express
your application components clearly and succinctly. Its data binding and
dependency injection eliminate much of the code you currently have to write. And
it all happens within the browser, making it an ideal partner with any server
technology.
General Features
The general features of AngularJS are as follows −
Advantages of AngularJS
The advantages of AngularJS are −
On the top of everything, AngularJS applications can run on all major browsers
and smart phones, including Android and iOS based phones/tablets.
Disadvantages of AngularJS
Though AngularJS comes with a lot of merits, here are some points of concern −
AngularJS Directives
The AngularJS framework can be divided into three major parts −
AngularJS Expressions
In this article, we will see the Expressions in AngularJS, along with
understanding their implementation through the examples.
Expressions in AngularJS are used to bind application data to HTML. The
expressions are resolved by AngularJS and the result is returned back to where
the expression is written. The expressions in AngularJS are written in double
braces: {{ expression }}. They behave similar to ng-bind directives: ng-
bind=”expression”.
Syntax:
{{ expression }}
AngularJS Modules
The AngularJS module defines the functionality of the application which is
applied on the entire HTML page. It helps to link many components. So it is
just a group of related components. It is a container that consists of different
parts like controllers, services, and directives.
Note: These modules should be made in normal HTML files like index.html
and no need to create a new project in VisualStudio for this section.
AngularJS Directive
AngularJS is a Javascript open-source front-end framework that is mainly used
to develop single-page web applications(SPAs). It has the ability to change
static HTML to dynamic HTML. Its features like dynamic binding and
dependency injection eliminate the need for code that we have to write
otherwise.
Directives are markers on the DOM element which tell AngularJS to attach a
specified behavior to that DOM element or even transform the DOM element
with its children. Simple AngularJS allows extending HTML with new
attributes called Directives. AngularJS has a set of built-in directives which
offers functionality to the applications. It also defines its own directives. A
directive can be defined using some functions which are: Element name,
Attribute, Class, and Comment.