Section A Part 2 JS
Section A Part 2 JS
A function in JavaScript is a reusable block of code that performs a specific task.
You define it once, and then you can run (or “call”) it whenever you need that task
done in your program.
A JavaScript function runs when it is “called” by some part of your code.
Syntax: The basic syntax to create a function in JavaScript is shown below.
function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function,
separated by the name of the function and parameters within parenthesis. The part
of the function inside the curly braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for assignments,
or calculations.
Why Functions?
Functions can be used multiple times, reducing redundancy.
Break down complex problems into manageable pieces.
Manage complexity by hiding implementation details.
Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
Triggered by an event (e.g., a button click by a user).
When explicitly called from JavaScript code.
Automatically executed, such as in self-invoking functions.
Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can
use the above syntax to create a function in JavaScript.
A function definition is sometimes also termed a function declaration or function
statement. Below are the rules for creating a function in JavaScript:
Every function should begin with the keyword function followed by,
A user-defined function name that should be unique,
A list of parameters enclosed within parentheses and separated by commas,
A list of statements composing the body of the function enclosed within curly
braces {}.
Example: This example shows a basic declaration of a function in javascript.
JavaScript
function calcAddition(number1, number2) {
return number1 + number2;
}
1
console.log(calcAddition(6,9));
Objects in Javascript
Last Updated : 14 Aug, 2024
Objects in JavaScript are the most important data type and form the building blocks
for modern JavaScript. Unlike primitive data types (Number, String, Boolean, null,
undefined, and symbol), which hold a single value, objects can hold multiple values
as properties. This makes objects incredibly useful for grouping related data and
operations, leading to more organized and maintainable code.
What Are Objects in JavaScript?
In JavaScript, an object is a collection of related data and functions, known as
properties and methods, respectively. Properties are “key: value” pairs that store
data, while methods are functions associated with the object that can manipulate its
properties.
Syntax
new Object(value)
Object(value)
let object_name = {
key_name : value,
...
}
Note:- Object() can be called with or without new. Both create a new object.
Example: Below is an example of Objects in JavaScript.
JavaScript
const o = new Object();
o.foo = 42;
console.log(o);
// { foo: 42 }
Output
{ foo: 42 }
Example: In this example “name”, “location”, and “established” are
all “keys” and “Vivekananda School”, “Delhi” and 1971 are values of these keys
respectively. Each of these keys is referred to as properties of the object. An object
in JavaScript may also have a function as a member, in which case it will be known
as a method of that object. Here “displayinfo” is a method of the school object that
is being used to work with the object’s data, stored in its properties.
javascript
2
// JavaScript code demonstrating a simple object
let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
displayInfo: function () {
console.log(`${school.name} was established
in ${school.established} at ${school.location}`);
}
}
school.displayInfo();
Output
Vivekananda School was established
in 1971 at Delhi
Objects are more complex and each object may contain any combination of
these primitive data-types as well as reference data-types.
An object is a reference data type. Variables that are assigned a reference value
are given a reference or a pointer to that value. That reference or pointer points
to the location in memory where the object is stored. The variables don’t
actually store the value.
Loosely speaking, objects in JavaScript may be defined as an unordered
collection of related data, of primitive or reference types, in the form of
“key: value” pairs. These keys can be variables or functions and are called
properties and methods, respectively, in the context of an object.
An object can be created with figure brackets {…} with an optional list of properties.
A property is a “key: value” pair, where a key is a string or a symbol (also called a
“property name”), and the value can be anything including numbers, strings,
booleans, functions, arrays, or even other objects.
How to Manipulate DOM Elements in
JavaScript ?
Last Updated : 26 Mar, 2024
In web development, one of the main features to enable interactivity is DOM
Manipulation. DOM manipulation allows developers to interact and modify the
structure, style, and content of web pages dynamically.
The below list contains different methods to manipulate DOM.
Table of Content
DOM Element Selectors
DOM content manipulators
DOM element creators
DOM CSS manipulators
3
DOM Element Selectors
There are multiple methods available in DOM to select the HTML elements and
manipulate them as listed below:
querySelector() method: The querySelector( ) method is used to select the
first element that matches the specified selector provided as an argument.
querySelectorAll() method: The querySelectorAll() method returns a
NodeList which contains all elements that match the selector within the
document.
getElementById( ) method: The getElementId() method is used to select a
single element using its Id.
getElementByClassName( ): The getElementsByClassName()
method in JavaScript is used to select elements in the HTML document that
have a specific class name.
getElementByTagName()
method: The getElementsByTagName() method is used to select elements
using the specified tag name.
getElementByName() method: The getElementsByName() method is used to
select elements that have a specific name attribute. This method returns a
NodeList of elements with the specified name.
Example: The below code explain the use of the above listed DOM selectors.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
GeeksForGeeks
</title>
</head>
4
document.querySelector(".example");
const gebi =
document.getElementById("target");
const gebcn =
document.getElementsByClassName('example');
const gebtn =
document.getElementsByTagName('p');
const gebn =
document.getElementsByName('username');
const querySAll =
document.querySelectorAll("p");
console.log(queryS);
console.log(gebi);
console.log(gebcn);
console.log(gebn);
console.log(gebtn);
console.log(querySAll);
</script>
</body>
</html>
Output:
5
DOM content manipulators
The below DOM properties can be used to change the HTML and the text content
of the HTML elements.
textContent: The textContent property is used to set and get the text content
and it’s descendants.
innerHTML: The innerHTML property is used to get and set the text
and HTML inside an HTML element.
innerText: The innerText property represents the rendered text content of a
node and its descendants. It is aware of the elements which will be rendered and
ignores the hidden elements.
Example: The below code will explain the use of the above listed DOM
manipulators.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
DOM Manipulation Techniques
</title>
</head>
</html>
6
JavaScript libraries and frameworks make the life of a programmer easier by
providing a plethora of built-in functions and methods. These tools enhance web
development by saving time, making code more readable, and offering project
structure and data flow organization, resulting in faster and more reliable
applications.
JavaScript Libraries
A JavaScript library is a collection of classes, methods, and pre-written functions
that developers can use in their web development projects. Libraries make code
reusable and simplify the development process. They are also favored for their cross-
browser compatibility, saving developers time and effort. Some popular JavaScript
libraries include:
JavaScript
Libraries Versions Description Applications
Creates
simple views
An open-source for each state
JavaScript library used to in the
create user interfaces in a application
declarative and efficient and
Introduced: May 29, 2013
way. efficiently
Current: 18.2.0
Component-based front- updates and
end library is responsible renders just
only for the view layer of the right
an MVC architecture. component as
your data
ReactJS changes.
JavaScript Frameworks
JavaScript frameworks are essential tools for creating web applications. They
provide built-in components that help in developing robust and interactive web
applications. Frameworks simplify the structure of projects by offering blueprints
and streamline the development process with powerful and efficient methods for
handling events, two-way data binding, and more. Some popular JavaScript
frameworks include:
7
Js
Frameworks Versions Description Applications
Creates
A powerful application
JavaScript based on
framework that MVC
Introduced: October 20,
helps in architechture
2010
building that leads to
Current: 17.0.3
dynamic and cleaner and
interactive web more
applications. organized
Angular js code.
A progressive
JavaScript
framework for
building user Helps in
interface or UI creating a
Introduced: February 2014 components. fast and
Current: 3.3.0 Can adapt routing
incremently and based web
it has a library applications.
which basically
focuses on the
Vue.js view layer only.
Provides an
An open-source event-
and cross- driven, non-
platform blocking I/O
runtime and cross-
environment platform
built on runtime
Introduced: May 27, 2009
Chrome’s V8 environment
Current: 21.1.0
JavaScript for building
engine for highly
executing scalable
JavaScript code server-side
outside of a applications
browser. using
Node.js JavaScript.
8
jQuery Tutorial
Last Updated : 25 Jul, 2024
jQuery is a lightweight JavaScript library that simplifies the HTML DOM
manipulating, event handling, and creating dynamic web experiences. The main
purpose of jQuery is to simplify the usage of JavaScript on websites. jQuery achieves
this by providing concise, single-line methods for complex JavaScript tasks, making
your code more readable and maintainable. By learning jQuery, you can
significantly enhance the interactivity and responsiveness of your web pages. In this
jQuery tutorial, you will learn all the basic to advanced concepts of jQuery such as
DOM manipulation and event handling, AJAX, animations, plugins, etc.
Table of Content
What is jQuery?
Features of jQuery
Getting Started with jQuery
jQuery Basic Example
Steps to Learn jQuery
jQuery Projects
jQuery Interview Questions and Answers (2024)
Advantages of jQuery
jQuery Cheat Sheet
jQuery Tutorial – FAQs
What is jQuery?
jQuery is a lightweight, “write less, do more” JavaScript library that simplifies
web development. It provides an easy-to-use API for common tasks, making it much
easier to work with JavaScript on your website. It streamlines web development by
providing a concise syntax and powerful utilities for creating interactive and
dynamic web pages.
Features of jQuery
Here are some key points about jQuery:
DOM Manipulation: jQuery simplifies HTML DOM tree traversal and
manipulation. You can easily select and modify elements on your web page.
Event Handling: Handling user interactions (such as clicks or mouse events)
becomes straightforward with jQuery.
CSS Animations: You can create smooth animations and effects using jQuery.
AJAX (Asynchronous JavaScript and XML): jQuery simplifies making
asynchronous requests to the server and handling responses.
Cross-Browser Compatibility: jQuery abstracts browser-specific
inconsistencies, ensuring your code works consistently across different
browsers.
9
Community Support: A large community of developers actively contributes to
jQuery, ensuring continuous updates and improvements.
Plugins: jQuery has a wide range of plugins available for various tasks.
Getting Started with jQuery
1. Download the jQuery Liberary
You can download the jQuery library from the official website jquery.com and
include it in your project by linking to it using a <script> tag, and host it on your
server or local filesystem.
2. Include the jQuery CDN in Code
Using jQuery Library Content Delivery Network (CDN) in your HTML project.
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.j
s"></script>
Once the library is included, you can write jQuery code within <script> tags.
jQuery code typically follows a specific syntax:
<script> $(document).ready(function() { // Your jQuery code here
});</script>
The $(document).ready(function() { ... }) function ensures your code
executes only after the document is fully loaded, preventing errors.
jQuery Basic Example
In this example, we are using hover() and css() methods to change the style of
heading content on mouse move over.
html
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("h1").hover(
function () {
$(this).css(
"color",
"green"
);
},
function () {
$(this).css(
"color",
"aliceblue"
);
}
);
10
});
</script>
</head>
<body>
<h1>GeeksforGeeks</h1>
</body>
</html>
Output:
React Tutorial
Last Updated : 09 Sep, 2024
React is a JavaScript Library for front-end development. It is used to build
user interfaces and UI components. It is developed by Facebook.
React is known for its component-based architecture which allows you to create
reusable UI components, making complex web applications easier to manage and
maintain. React is used to build single-page applications.
In this React tutorial, you’ll learn all the basic to advanced concepts of React such
as React components React props, React state, Functional components in
React, React hooks, etc.
React Tutorial Prerequisites:
Before learning React you must have the knowledge of the following.
HTML
CSS
JavaScript
Also Check: Recent Articles on ReactJS
Table of Content
Getting Started with React: Installation and Environment Setup
Why Learn React JS?
Features of React
Core React Concepts
React Advantages
Getting Started with React: Installation and Environment
Setup
11
Before embarking on your React journey, ensure you have a suitable development
environment set up. Here’s a roadmap to get you started:
1. Node.js and npm: Download and install Node.js
(https://nodejs.org/en/download/package-manager/current) as it provides the
runtime environment for JavaScript code execution. npm (Node Package
Manager) is bundled with Node.js and is used to manage project dependencies.
2. Create React App (CRA): Using Create React App (CRA) to establish a new
React project with minimal configuration. Run npx create-react-app my-
react-app in your terminal, replacing my-react-app with your desired project
name.
Basic Example of React:
ReactJS
// Import statements
import React from 'react';
import ReactDOM from 'react-dom/client';
This code defines a functional component named App that returns JSX
code displaying the text “Hello GeeksforGeeks”. Save the file and run your
development server using npm start. Navigate to http://localhost:3000/ in
your browser to view your webpage.
Why Learn React JS?
React, the popular JavaScript library, offers several exciting reasons for developers
to learn it.
First, React is flexible – once you learn its concepts, you can use it across various
platforms to build quality user interfaces. Unlike a framework, React’s library
approach allows it to evolve into a remarkable tool.
Second, React has a great developer experience, making it easier to understand and
write code. Third, it benefits from Facebook’s support and resources, ensuring
regular bug fixes, enhancements, and documentation updates. Additionally, React’s
broader community support, excellent performance, and ease of testing make it an
ideal choice for web development.
Features of React
1. JSX (JavaScript Syntax Extension):
12
JSX combines HTML and JavaScript, allowing you to embed JavaScript
objects within HTML elements.
It enhances code readability and simplifies UI development.
Example:
const name = "GeekforGeeks";
const ele = <h1>Welcome to {name}</h1>;
2. Virtual DOM (Document Object Model):
React uses a virtual DOM, which is an exact copy of the real DOM.
When there are modifications in the web application, React updates the virtual
DOM first and then computes the differences between the real DOM and the
virtual DOM.
This approach minimizes unnecessary re-rendering and improves performance.
4. Performance:
React’s virtual DOM and component-based architecture contribute to better
performance.
Separate components allow efficient rendering and faster execution.
5. Extension:
React has a rich ecosystem and supports various extensions.
Explore tools like Flux, Redux, and React Native for mobile app development
and server-side rendering.
6. Conditional Statements in JSX:
JSX allows writing conditional statements directly.
Display data in the browser based on provided conditions.
Example:
const age = 12;
13
if (age >= 10) {
return <p>Greater than {age}</p>;
} else {
return <p>{age}</p>;
}
7. Components:
React divides web pages into reusable and immutable components.
Component-based development simplifies code organization and maintenance.
AngularJS Tutorial
Last Updated : 01 Jul, 2024
AngularJS is a free and open-source JavaScript framework that helps developers
build modern web applications. It extends HTML with new attributes and it is perfect
for single-page applications (SPAs).
AngularJS, developed by Google, has been important in web development since its
inception in 2009. AngularJS excels at building SPAs. These are applications that
load in the browser once and update content without needing to refresh the entire
page, providing a smoother user experience.
This AngularJS tutorial is designed to learn AngularJS quickly and efficiently.
You will start by learning the fundamentals of AngularJS, including directives,
expressions, filters, modules, and controllers. After that, you will learn about a
variety of other aspects of AngularJS, such as events, DOM, forms, input,
validation, HTTP, and more.
Additionally, we also provide AngularJS interview questions to help you deepen
your understanding of the framework and prepare for potential job opportunities.
Table of Content
AngularJS Prerequisites
What is AngularJS?
Why Learn AngularJS?
Basic Example of AngularJS Application
Create Your First AngularJS Application
Key Concepts in AngularJS
Advantages of AngularJS
Additional Aspects to Explore
More Related to AngularJS
Complete References
Interview Questions
Frequently Asked Questions on AngularJS Tutorial
AngularJS Prerequisites
HTML
CSS
14
JavaScript
What is AngularJS?
AngularJS revolutionized front-end development by introducing a Model-View-
Controller (MVC) architecture. This separation of concerns keeps your code clean,
maintainable, and easier to test. Here’s a breakdown:
Model: Represents your application’s data and business logic.
View: Handles the user interface and presentation layer.
Controller: Acts as the glue, binding the model and view together and handling
user interactions.
Why Learn AngularJS?
AngularJS is an open-source web application framework, was initially developed in
2009 by Misko Hevery and Adam Abrons. It is now maintained by Google, and
its latest version is 1.2.21.
Established Framework: AngularJS is a widely used framework with a
successful developer community and large learning resources.
Single Page Applications (SPAs): AngularJS excels at building SPAs, where
content updates occur seamlessly on the same page. If you aim to create
dynamic and interactive web applications, AngularJS is your partner.
Structure and Maintainability: By attaching to the Model-View-Controller
(MVC) architecture, AngularJS promotes clean separation of concerns. This
architectural pattern leads to more maintainable and scalable code, especially
beneficial for complex applications.
Large Development Community: With its extensive history, AngularJS boasts
a vast community of developers. Access forums, tutorials, and other resources
to deepen your understanding and troubleshoot effectively.
Basic Example of AngularJS Application
AngularJS is a JavaScript framework written in JavaScript.
AngularJS is distributed as a JavaScript file, and can be added to a web page with a
script tag:
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.m
in.js">
</script>
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
15
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text"
ng-model="name"
placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
Output:
16
ADVANCED JAVASCRIPT CONCEPTS
Prototype in JavaScript
Last Updated : 06 Jun, 2024
JavaScript is a prototype-based, automatically adds a prototype property to
functions upon creation. This prototype object allows attaching methods and
properties, facilitating inheritance for all objects created from the function.
Example : There are different ways to create an object, one of the ways is to create
an object using a function constructor.
javascript
// function constructor
function Person(name, job, yearOfBirth){
this.name= name;
this.job= job;
this.yearOfBirth= yearOfBirth;
}
// this will show Person's prototype property.
console.log(Person.prototype);
Output:-
In above image, you can see Person has a prototype property and that prototype
property has a constructor object which again points to the Person constructor
function.
We can understand this by an Image:
When we create an object using the above function constructor, JavaScript Engine
will add dunder proto or __proto__ in the object which will point to the prototype’s
constructor object.
17
Now, we will add a method calculateAge() to the Prototype property in a Person
function constructor which will inherit by the different objects. Below is the code
for this:-
javascript
// function constructor
function Person(name, job, yearOfBirth) {
this.name = name;
this.job = job;
this.yearOfBirth = yearOfBirth;
}
Person.prototype.calculateAge = function () {
console.log('The current age is: ' + (2019 - this.yearOfBirth));
}
console.log(Person.prototype);
Output:-
In above image, we can see calculateAge() method gets added to the Prototype
property. Now, we will create 2 different objects which will inherit calculateAge()
method and remember, When a certain method(or property) is called, it first
checks inside the object but when it doesn’t find, then search moves on
Object’s prototype.
javascript
// function constructor
function Person(name, job, yearOfBirth) {
this.name = name;
this.job = job;
this.yearOfBirth = yearOfBirth;
}
// adding calculateAge() method to the Prototype property
Person.prototype.calculateAge = function () {
console.log('The current age is: ' + (2019 - this.yearOfBirth));
}
console.log(Person.prototype);
18
// creating Object Person1
let Person1 = new Person('Jenni', 'clerk', 1986);
console.log(Person1)
let Person2 = new Person('Madhu', 'Developer', 1997);
console.log(Person2)
Person1.calculateAge();
Person2.calculateAge();
Output:-
Here, we created two Objects Person1 and Person2 using constructor function
Person, when we called Person1.calculateAge() and Person2.calculateAge(), First
it will check whether it is present inside Person1 and Person2 object, if it is not
present, it will move Person’s Prototype object and prints the current age,
which shows Prototype property enables other objects to inherit all the
properties and methods of function constructor.
Closure in JavaScript
Last Updated : 09 Sep, 2024
Closures in JavaScript are functions that retain access to variables from their
containing scope even after the parent function has finished executing. They’re
useful for maintaining private data, creating modular code, and implementing
callback functions with persistent state.
What is a Closure?
A closure is the combination of a function bundled together (enclosed) with
references to its surrounding state (the lexical environment). When you create a
closure, you gain access to an outer function’s scope from an inner function.
Closures are automatically created every time a function is defined in JavaScript.
Lexical Scoping
Lexical scoping refers to how a parser resolves variable names when functions are
nested. The location where a variable is declared within the source code determines
where that variable is available. Nested functions have access to variables declared
in their outer scope. Consider the following example:
Example: This example shows the basic use of closure.
JavaScript
function foo() {
19
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();
console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
Output
1
1
1
Output: We can access the variable b which is defined in the function
foo() through function inner() as the later preserves the scope chain of the
enclosing function at the time of execution of the enclosing function i.e. the inner
function knows the value of b through its scope chain.
This is closure in action that is inner function can have access to the outer function
variables as well as all the global variables.
Closure in JavaScript
20
function inner(inner_arg) {
return outer_arg + inner_arg;
}
return inner;
}
let get_func_inner = foo(5);
console.log(get_func_inner(4));
console.log(get_func_inner(3));
Output
9
8
In the above example we used a parameter function rather than a default one. Not
even when we are done with the execution of foo(5) we can access
the outer_arg variable from the inner function. And on the execution of the inner
function produce the summation of outer_arg and inner_arg as desired.
Now let’s see an example of closure within a loop.
In this example, we would store an anonymous function at every index of an array.
Example 2:
JavaScript
// Outer function
function outer() {
let arr = [];
let i;
for (i = 0; i < 4; i++) {
// storing anonymous function
arr[i] = function () { return i; }
}
console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());
Output
4
4
4
21
4
Did you guess the right answer? In the above code, we have created four closures
that point to the variable i which is the local variable to the function outer. Closure
doesn’t remember the value of the variable it only points to the variable or stores
the reference of the variable and hence, returns the current value. In the above
code when we try to update the value it gets reflected all because the closure stores
the reference.
Let’s see the correct way to write the above code so as to get different values of i at
different indexes.
Example 3:
JavaScript
// Outer function
function outer() {
function create_Closure(val) {
return function () {
return val;
}
}
let arr = [];
let i;
for (i = 0; i < 4; i++) {
arr[i] = create_Closure(i);
}
return arr;
}
let get_arr = outer();
console.log(get_arr[0]());
console.log(get_arr[1]());
console.log(get_arr[2]());
console.log(get_arr[3]());
Output
0
1
2
3
In the above code we are updating the argument of the function create_Closure
with every call. Hence, we get different values of i at different indexes.
22
Async and Await in JavaScript is used to simplify handling asynchronous
operations using promises. By enabling asynchronous code to appear synchronous,
they enhance code readability and make it easier to manage complex asynchronous
flows.
Async Function
The async function allows us to write promise-based code as if it were synchronous.
This ensures that the execution thread is not blocked.
Promise Handling: Async functions always return a promise. If a value is
returned that is not a promise, JavaScript automatically wraps it in a resolved
promise.
Async Syntax
async function myFunction() {
return "Hello";
}
Example: Here, we will see the basic use of async in JavaScript.
javascript
const getData = async () => {
let data = "Hello World";
return data;
}
Output
Hello World
Await Keyword
The await keyword is used to wait for a promise to resolve. It can only be used
within an async block.
Execution Pause: Await makes the code wait until the promise returns a result,
allowing for cleaner and more manageable asynchronous code.
Syntax
let value = await promise;
Example : This example shows the basic use of the await keyword in JavaScript.
javascript
const getData = async () => {
let y = await "Hello World";
console.log(y);
}
console.log(1);
getData();
console.log(2);
Output
23
1
2
Hello World
The async keyword transforms a regular JavaScript function into an asynchronous
function, causing it to return a Promise.
The await keyword is used inside an async function to pause its execution and wait
for a Promise to resolve before continuing.
Async/Await Example
Here, we will be implementing several promises in a method, and then that method
we will use for displaying our result. You can check the JS async/await syntax in
the example.
JavaScript
function asynchronous_operational_method() {
let first_promise =
new Promise((resolve, reject) => resolve("Hello"));
let second_promise =
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(" GeeksforGeeks..");
}, 1000);
});
let combined_promise =
Promise.all([first_promise, second_promise]);
return combined_promise;
}
display();
Output:
[ 'Hello', ' GeeksforGeeks..' ]
Explanation:
1. Promise Creation:
Two promises are created: one resolve immediately with “Hello”, and the
other resolves after 1 second with ” GeeksforGeeks..”.
2. Combining Promises:
The Promise.all() method combines both promises into a single promise,
combined_promise.
3. Asynchronous Function:
The display() function is declared as async, indicating it contains
asynchronous operations.
4. Awaiting Promise Resolution:
24
The await keyword pauses execution until combined_promise is resolved.
5. Logging Result:
The resolved array from combined_promise is logged to the console.
Note
To resolve and reject are predefined arguments by JavaScript.
resolve function is used when an asynchronous task is completed and returns
the result.
reject function is used when an asynchronous task fails and returns reasons for
failure.
Error Handling in Async/Await
JavaScript provides predefined arguments for handling promises: resolve and
reject.
resolve: Used when an asynchronous task is completed successfully.
reject: Used when an asynchronous task fails, providing the reason for failure.
Example:
JavaScript
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
Advantages of Async and Await
1. Improved Readability: Async and Await allow asynchronous code to be
written in a synchronous style, making it easier to read and understand.
2. Error Handling: Using try/catch blocks with async/await simplifies error
handling.
3. Avoids Callback Hell: Async and Await prevent nested callbacks and complex
promise chains, making the code more linear and readable.
4. Better Debugging: Debugging async/await code is more intuitive since it
behaves similarly to synchronous code.
25
How to Manipulate DOM Elements in
JavaScript ?
Last Updated : 26 Mar, 2024
In web development, one of the main features to enable interactivity is DOM
Manipulation. DOM manipulation allows developers to interact and modify the
structure, style, and content of web pages dynamically.
The below list contains different methods to manipulate DOM.
Table of Content
DOM Element Selectors
DOM content manipulators
DOM element creators
DOM CSS manipulators
DOM Element Selectors
There are multiple methods available in DOM to select the HTML elements and
manipulate them as listed below:
querySelector() method: The querySelector( ) method is used to select the
first element that matches the specified selector provided as an argument.
querySelectorAll() method: The querySelectorAll() method returns a
NodeList which contains all elements that match the selector within the
document.
getElementById( ) method: The getElementId() method is used to select a
single element using its Id.
getElementByClassName( ): The getElementsByClassName()
method in JavaScript is used to select elements in the HTML document that
have a specific class name.
getElementByTagName()
method: The getElementsByTagName() method is used to select elements
using the specified tag name.
getElementByName() method: The getElementsByName() method is used to
select elements that have a specific name attribute. This method returns a
NodeList of elements with the specified name.
Example: The below code explain the use of the above listed DOM selectors.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
GeeksForGeeks
</title>
</head>
26
<body style="text-align: center;">
<div id="target">
<h1>Hello Geeks</h1>
<h2 class="example">
This is a sample sub heading
</h2>
<p>
This is sample paragraph1
</p>
<p>
This is sample paragraph2
</p>
<input type="text" name="username"
id="userName">
</div>
<script>
const queryS =
document.querySelector(".example");
const gebi =
document.getElementById("target");
const gebcn =
document.getElementsByClassName('example');
const gebtn =
document.getElementsByTagName('p');
const gebn =
document.getElementsByName('username');
const querySAll =
document.querySelectorAll("p");
console.log(queryS);
console.log(gebi);
console.log(gebcn);
console.log(gebn);
console.log(gebtn);
console.log(querySAll);
</script>
</body>
</html>
Output:
27
DOM content manipulators
The below DOM properties can be used to change the HTML and the text content
of the HTML elements.
textContent: The textContent property is used to set and get the text content
and it’s descendants.
innerHTML: The innerHTML property is used to get and set the text
and HTML inside an HTML element.
innerText: The innerText property represents the rendered text content of a
node and its descendants. It is aware of the elements which will be rendered and
ignores the hidden elements.
Example: The below code will explain the use of the above listed DOM
manipulators.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
DOM Manipulation Techniques
28
</title>
</head>
</html>
A Single Page Application (SPA) is a type of web application that loads
and updates content dynamically without refreshing the entire page.
Unlike traditional websites, SPAs use modern technologies to enhance
the user experience by minimizing interruptions and providing a smoother
interface. Users can interact with the application seamlessly, similar to
using desktop software. The main advantage is the elimination of full-page
reloads, resulting in a more responsive and engaging web experience.
This is achieved by ensuring that the browser obtains all
essential HTML, JavaScript, and CSS codes in one request or updates
the necessary content based on user actions.
When you click on something in a SPA, it only sends the necessary
information to your browser and the browser renders it. This is different
from a traditional page load, where the server sends a full page to your
browser with every click you make.
29
When to use SPA?
Dynamic Interactions: Choose SPAs for applications requiring
frequent user interactions without full page reloads.
Real-Time Updates: Opt for SPAs when real-time responsiveness is
crucial for a seamless user experience.
Mobile-Friendly: Use SPAs for mobile-friendly apps, providing an app-
like feel with smooth transitions.
Rich User Interfaces: Consider SPAs for interactive interfaces with
features like animations and dynamic content.
Minimized Server Load: Utilize SPAs when reducing server load and
bandwidth usage is a priority.
Single-Page Content: Prefer SPAs for content logically presented on
a single page, avoiding the need for multiple pages.
Cross-Platform Consistency: Choose SPAs for maintaining a
consistent user experience across various devices and platforms.
SPA Architecture and How Does it Work?
Imagine a Single Page Application (SPA) to be like a magical book. In a
traditional book, you flip pages to move to different chapters. However, in
the magical SPA book, every chapter appears instantly with a wave of
your hand, without having to flip pages. You get fully absorbed in the story
without any interruptions. Similarly, SPAs function on the web by smoothly
loading and updating content, allowing users to explore the digital world
without any delays that come with traditional websites.It includes three
renderings :
Client-side rendering
First browser requests HTML from the server.
Then server swiftly responds with a basic HTML file and linked
styles/scripts.
Now user sees a blank page or loader while JavaScript executes.
App fetches data, creates views, and injects them into the DOM.
Client-Side Rendering (CSR) can be slower for basic websites because it
uses a lot of device resources. Yet, it’s good for busy websites, making
things faster for users. Just remember, if you want different social sharing
options, you might need Server-Side Rendering (SSR) or Static Site
Generation (SSG) instead.
Server-side rendering (SSR)
The browser first asks the server for an HTML file.
Now server gathers necessary data, builds the SPA, and creates an
HTML file instantly.
Now user sees the content ready to go.
Single-page app structure adds events, makes a virtual DOM, and gets
things ready.
Now, the application is set for use.
30
HUSPI opts for server-side rendering to achieve a swift application
experience, balancing the speed of single-page applications without
burdening the user’s browser, ensuring optimal app performance.
Static site generator (SSG)
Browsers ask for HTML, SSGs quickly provide pre-made static pages.
The server shows users the static page for fast loading.
SPAs in the page fetch data and make dynamic changes to the page.
SPA is ready for smooth user interaction after data is added.
SSGs are great for fast static pages but may not be ideal for highly
dynamic websites.
While static site generators offer a quick and efficient solution, it’s crucial
to note that they might not be the perfect fit for websites with dynamic
content. Their strength lies in static pages, aligning with their name.
31
Improved Performance: By minimizing server requests and only
updating the required components, SPAs significantly reduce the load
on servers, resulting in faster load times and better overall
performance.
Reduced Bandwidth Usage: Since SPAs only fetch the data needed
for specific interactions, they minimize the amount of data transferred
between the client and server, reducing bandwidth usage and
improving efficiency.
Enhanced Responsiveness: It enable dynamic content updates
without requiring full page reloads.
Seamless User Navigation: SPAs use client-side routing, enabling
seamless navigation between sections of the application without the
need for full page reloads.
Cross-Platform Compatibility: SPAs are inherently compatible with
various devices and platforms, promoting a consistent user experience
across desktops, tablets, and mobile devices.
Scalability: SPAs support the scalability of web applications by
efficiently managing client-server interactions.
Disadvantages of SPAs
Slower Initial Load: Can be slower initially, affecting users with slower
internet.
SEO Challenges: SEO can be tricky due to heavy reliance on
JavaScript.
Limited Browser Support: Advanced features may not work well on
older browsers.
Security Risks: Vulnerable to security issues like Cross-Site Scripting
(XSS).
Client-Side Resource Intensity: Places a heavy load on the client
side, impacting older devices.
Dependency on JavaScript: Essential functionality may break if users
disable JavaScript.
Browser History Management: Handling navigation dynamically
poses challenges with browser history.
Complex Development: Developing SPAs is more complex, requiring
a learning curve.
32
Vue.js Tutorial
Last Updated : 18 Jun, 2024
Vue.js is a progressive JavaScript framework used for building user interfaces.
As a progressive framework, UI built-in Vue updates automatically when data
changes. Unlike other frameworks, Vue is designed from the ground up to be
incrementally adaptable.
Vue.js enables developers to build modern and interactive web applications with
ease, efficiency, and scalability. It uses standard HTML, CSS, and JavaScript and
provides a declarative, component-based programming model to develop user
interfaces efficiently. Its core library focuses on the view layer only, making it easy
to pick up and integrate with other libraries or existing projects. Vue.js is also
perfectly capable of powering sophisticated single-page applications when used in
combination with modern tooling and supporting libraries.
In this Vue.js Tutorial, you’ll learn all the basic to advanced concepts of
Vue.js such as Directives, Transition, Routing, etc.
Prerequisite to Learn Vue.js:
HTML
CSS
JavaScript
What is Vue.js?
Vue.js is a progressive JavaScript framework used for building user interfaces. It
stands out for its simplicity, seamless integration with other libraries, and reactive
data binding.
Here are some reasons why you should consider learning Vue.js:
1. Adaptability: Vue.js offers a hassle-free migration process and provides a
straightforward and efficient structure for developers.
2. Component-Based Architecture: Vue.js allows you to create custom elements
(components) that can be reused across your HTML templates. This
modularity enhances code maintainability and scalability.
3. Transitions: Vue.js provides various methodologies for applying smooth
transitions to HTML components when they are added or removed from the
DOM.
4. Detailed Documentation: Vue.js comes with comprehensive documentation,
making it easy for beginners to learn and explore its features.
Why Choose Vue.js?
Easy to Learn: Vue.js is known for its gentle learning curve. Its syntax is
straightforward and easy to understand for developers with a basic knowledge
of HTML, CSS, and JavaScript.
Flexible and Versatile: Vue.js can be used for building both single-page
applications (SPAs) and more complex applications. It integrates well with
other libraries and projects, providing flexibility to developers.
33
Reactive Data Binding: One of the core features of Vue.js is its reactivity
system, which allows for efficient and effective updates to the DOM when data
changes.
Complete Documentation: Vue.js boasts some of the best documentation in
the JavaScript ecosystem. This extensive resource makes it easier for
developers to understand and implement the framework effectively.
Performance: Vue.js is known for its efficient virtual DOM implementation,
leading to smooth performance and fast rendering of your web applications.
Table of Content
Applications of Vue.js
Vue.js Tutorial
o Vue.js Basics
o Vue.js Directives
o Vue.js Transition
o Vue.js Routing
o Miscellaneous
Advantages of Vue.js
Core Concepts of Vue.js
Applications of Vue.js
1. Single-Page Applications (SPAs): Vue.js is an excellent choice for building
dynamic and interactive SPAs. Its lightweight nature and reactivity make it
ideal for handling complex UIs.
2. User Interfaces (UIs): Vue.js is widely used for creating engaging and
responsive UIs. Its component-based approach simplifies UI development.
3. Real-Time Updates: Vue.js facilitates real-time data updates, making it
suitable for applications that require live data synchronization.
4. Prototyping: Due to its simplicity and flexibility, Vue.js is perfect for rapid
prototyping of web applications.
5. Cross-Platform Development: Whether you’re building web, mobile, or
desktop applications, Vue.js can adapt to different platforms seamlessly.
Vue.js Tutorial
Vue.js Basics
Introduction & Installation
Instances
Event Modifiers
DOM tree
How to write and use for loop in Vue js ?
Two Way Binding Model
Reusing Components
Rendering
List Rendering Mutation Methods
v-cloak Directive
Passing Data to Child Components with Props
34
Form Input Binding with Select option
Dynamic Components
Form Input Value Binding
Form Input Binding number Modifier
List Rendering v-for with v-if
List Rendering v-for with a Range
Form Input Binding with Checkbox option
Form Input Binding with Multiline text
Form Input Binding trim Modifier
Form Input Binding with Radio Option
List Rendering v-for with an Object
Render Function with h() Arguments
Form Input Binding with Radio Option
List Rendering v-for with an Object
Composition API with Templates
Event Handling
Event Modifiers
Declarative Rendering
Create a Hover effect in Vue.js
Types of data binding with template in Vue.js
Click Event
Dynamic Components
Pass data between components using Vue.js Event Bus
Passing Data to Child Components with Props
Render Functions Component VNodes creation
List Entering & Leaving Transitions
Composition API using Provide
Watchers
Methods
Vue.js Directives
v-on:keyup Directive
v-bind Directive in Vue.js
v-for Directive in Vue.js
List Rendering v-for with a Range
v-else-if Directive in Vue.js
Custom Directives with Components
Form Input Binding number Modifier
Conditional Rendering
List Rendering v-for with a Component
List Rendering v-for on a <template>
v-if directive
v-text directive
v-show directive
v-html directive
35
v-on:click directive
v-once Directive
v-on:click.ctrl Directive
v-on:click.right Directive
v-on:click.shift Directive
v-on:click.left Directive
v-on:click.middle Directive in Vue.js
v-pre Directive
Vue.js Transition
List Move Transitions
Transitioning between the Components
REST API Call to Get Location Details
Vue.js Routing
Routing
How to use routing in Vue.js ?
– Advance
Consuming a Rest API with Axios in Vue.js
– Differences
Node.js vs Vue.js
What is the difference between ShadowDOM and VirtualDOM ?
What is the difference between created and mounted event in VueJS?
Comparative study of Svelte vs React vs Angular vs Vue
What is the difference between one-way data flow and two-way data binding in
vue.js?
Miscellaneous
How to replace all occurrences of a string using Vue.js filters ?
How to set a click event once a page or view is loaded in vue.js?
How to check an image is loaded or not in VueJS ?
How to loop through a list of elements and display it in VueJS ?
How to Make localStorage Reactive in Vue.js ?
How to implement DateTime localization in vue.js ?
Select different values on two select tags in Vue.js
How to convert a normal string to a uppercase string using filter in VueJS ?
How to dynamically add or remove items from a list in Vue.js ?
How to binding inline styles in Vue.js ?
How to change text into lower case string using filters in Vue.js ?
How to Add Custom Fonts in VueJS ?
How to Trigger Watchers on Initialization in Vue.js ?
How to replace jQuery with Vue.js ?
How to catch props data on component change in Vue.js ?
How to create a reporting app with Vue 3 and Composition API ?
How to delete all occurrences of a particular string using Vue.js ?
How to Toggle a Class in Vue.js ?
How to Check Response Data Length in VueJS ?
36
Why the component data must be a function in vue.js ?
Advantages of Vue.js
1. Easy to Learn: Vue.js has a gentle learning curve, making it accessible to
beginners. Its straightforward syntax and clear documentation contribute to its
popularity.
2. Versatility: Vue.js can be integrated into existing projects and used for various
types of applications. Whether you’re building a small widget or a complex
SPA, Vue.js fits the bill.
3. Lightweight: Vue.js is lightweight, ensuring fast performance and an enhanced
user experience.
4. Reactivity: Vue.js offers seamless reactivity, automatically updating the UI in
response to data changes.
5. Component Reusability: The component-based architecture encourages
modular development, allowing developers to reuse components efficiently.
Core Concepts of Vue.js
Now that you have a basic understanding of setting up Vue.js, let’s explore some
fundamental concepts that are essential for building interactive web applications:
1. Templates: Vue.js uses HTML-like templates to define the structure of your
application’s UI. These templates can include dynamic expressions that get
evaluated based on your data.
2. Data: The data in your Vue.js application is typically an object containing
properties that represent the state of your application. Changes to this data will
automatically trigger updates to the UI.
3. Reactivity: Vue.js employs a reactive system that tracks changes to your data.
Whenever a data property is modified, Vue.js efficiently updates the
corresponding parts of the UI, ensuring a consistent and responsive user
experience.
4. Computed Properties: Computed properties are derived values based on your
data. They are ideal for calculations or transformations that you don’t want to
perform within the template itself.
5. Methods: Methods are functions that you can define within your Vue.js
component to handle user interactions or perform specific tasks. They are
reusable pieces of logic that can be invoked throughout your application.
6. Components: Components are reusable building blocks that encapsulate a
specific part of your UI and its functionalities. This promotes code
organization, maintainability, and reusability.
Learning Vue.js through this tutorial equips you with the skills to build dynamic and
reactive web applications efficiently. With Vue.js, you’ll create captivating user
interfaces and deliver seamless user experiences, enhancing your development
prowess.
37
Getting Started with Redux
Last Updated : 04 Mar, 2024
Redux is a popular state management library for JavaScript applications. It provides
a way to centralize the state of an application in a single store, making it easier to
debug, test, and reason about the state changes in the application. It helps to manage
complex application states, making it easier to handle data flow and interactions.
In this article, we’ll go over the basics of Redux and explore how it simplifies state
management.
The following fundamental concepts are discussed in this article:
Table of Content
Redux
Steps to simplify State Management using Redux
Store Creation
Action Creation
Dispatching Actions
Reducer Functions
Combining Reducers
Connecting to React Component
What is Redux?
Redux is a state managing library used in JavaScript apps. It simply manages the
state of your application or in other words, it is used to manage the data of the
application. It is used with a library like React.
Setting Up Redux in a React App
1. Store Creation
2. Action Creation
3. Dispatching Actions
4. Reducer Functions
5. Combining Reducers
6. Connecting to React Component
1. Store Creation in Redux
To build a Redux store, developers use the redux library’s createStore function and
send in a root reducer as an argument. A root reducer is a collection of reducers
that describe how the state in an application changes. Here’s an illustration of a
store built in Redux:
Javascript
38
import rootReducer from './reducers';
// an action object.
return {
type: 'ADD_TODO',
text
};
39
};
store.dispatch(addTodo('Learn Redux'));
// next state
switch (action.type) {
40
// For the ADD_TODO action type
case 'ADD_TODO':
return [
// existing todos
...state,
text: action.text,
// to false
completed: false
];
return state;
};
41
5. Combining Reducers in Redux
If an application has multiple reducers, developers can use the redux library’s
combineReducers function to combine them into a single root reducer. Here’s an
example of how to combine reducers in Redux
Javascript
todos: todoReducer,
visibilityFilter: visibilityFilterReducer
});
42
// Define functional components that accepts
// todos as a prop
<ul>
each todo */
<li key={index}>{todo.text}</li>
))}
</ul>
);
return {
// be mapped to props
todos: state.todos
};
};
Output:
43
Output
VueJS is a JavaScript framework for creating user interfaces. Vue.js, often simply
referred to as Vue, is known for its simplicity and flexibility. Vue has gained
widespread popularity among developers for its ease of integration. Vuejs is also
used for single-page web applications, the same as ReactJS.
Table of Content
What is VueJs?
How to set up VueJS and create a VueJS project?
Important concepts of VueJS
Creating a simple notes app using VueJS
VueJS FAQs
What is VueJs?
It’s a JavaScript framework that makes it easy to build web interfaces. With
VueJS, you can create dynamic and interactive elements on your website without
hard work. It’s user-friendly and flexible, making it a great choice for both
beginners and experienced developers. This can be used in many different ways:
44
Creating dynamic HTML
Single page application
Server-side rendering
Used for mobile, desktop or terminal
How to set up VueJS and create a VueJS project?
You can follow the below steps to setup and create a VueJS project:
Step 1: Install nodejs from nodejs.org
Step 2: Install dependencies using the below npm command.
npm install -g @vue/cli
Step 3: Create and visit your VueJS project
vue create your_project_name
cd your-project-name
Step 4: Run the node server to run the code
npm run serve
Important concepts of VueJS
Data Binding
It will make sure that your data whenever changes, will make visible to user
interface. Whenever anyone type anything in the input box it will refleceted on the
screen and visible to the user.
JavaScript
<template>
<div>
<h1 style="color: green">
GeeksforGeeks
</h1>
<input v-model="userInput"
placeholder="Type your message" />
<p>{{ userInput }}</p>
</div>
</template>
<script>
export default {
data() {
return {
userInput: '',
};
},
};
</script>
Component and props
Your web page is created using many different components. It is piece of code,
which can be used multiple time and not have to define again and again.
JavaScriptJavaScript
<!-- ParentComponent.vue -->
<template>
45
<div>
<h1>
{{ parentMessage }}
</h1>
<ChildComponent :childProp="parentMessage" />
</div>
</template>
<script>
import ChildComponent from
'./ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
parentMessage:
'Hello from Parent!',
};
},
};
</script>
Directives
These are like commands for VueJS. It start from ‘v-‘ and tell VueJS to do
something. Example v-if decides whether to show or hide an element.
JavaScript
<template>
<div>
<p v-if="showMessage">
This message is visible if showMessage is true.
</p>
<ul>
<li v-for="item in items">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
showMessage: true,
items: ['Item 1', 'Item 2', 'Item 3'],
};
},
};
</script>
46
Computed Properties
Computed properties in Vue.js enable the creation of reactive properties based on
other data properties.
JavaScript
<template>
<div>
<input v-model="inputText"
placeholder="Type your message" />
<p>
Message length:
{{ messageLength }}
</p>
</div>
</template>
<script>
export default {
data() {
return {
inputText: '',
};
},
computed: {
messageLength() {
return this.
inputText.length;
},
},
};
</script>
Vue Routes
Vue Router facilitates navigation and the creation of Single Page
Applications (SPAs). Also run a command to install the vue-router.
npm install vue-router
JavaScriptJavaScriptJavaScriptJavaScript
// main.js file
47
},
{
path: '/about',
component: AboutPage
}
]
});
createApp(App).use(router).mount('#app');
Creating a simple notes app using VueJS
It is a simple notes taking or ToDo application which allows you to add as well as
delete the items. You can create an task you have to do in future and delete it once
you have complete it.
Example: The below VueJS code will help you in creating the simple notes taking
app.
JavaScriptJavaScript
<!-- App.vue -->
<template>
<div id="app">
<h2 style="text-align: center;">
A Simple Notes App using VueJS
</h2>
<div class="input-container">
<input v-model="newNote"
placeholder="Type your note" />
<button @click="addNote">
Add Note
</button>
</div>
<NoteTaking v-for="note in notes" :key="note.id"
:note="note" @delete="deleteNote" />
</div>
</template>
<script>
import NoteTaking from './NoteTaking.vue';
export default {
components: {
NoteTaking,
},
data() {
return {
newNote: '',
notes: [],
nextNoteId: 1,
};
},
methods: {
addNote() {
if (this.newNote.trim() === '') return;
48
this.notes.push({
id: this.nextNoteId++,
text: this.newNote
});
this.newNote = '';
},
deleteNote(noteId) {
this.notes = this.notes.
filter((note) => note.id !== noteId);
},
},
};
</script>
<style>
#app {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.input-container {
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.input-container input {
flex-grow: 1;
padding: 10px;
margin-right: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
.input-container button {
background-color: #3498db;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 3px;
cursor: pointer;
}
.input-container button:hover {
background-color: #2980b9;
}
</style>
49