Master Frontend Ebook
Master Frontend Ebook
to Hero
1. Matser Frontend Development: Zero to Hero
HTML Topic
Quick Learning
1. Task: Create Your Personal Web Page
Deep Knowledge
1. HTML Page Structure
2. HTML Head
4. HTML Attributes
5. HTML Headings
6. HTML Paragraphs
7. HTML Styles
8. HTML Formatting
CSS Topic
1. What do you need before learning CSS?
2. CSS SELECTOR
3. EXAMPLE
5. CSS Comments
6. CSS Colors
JavaScript Topic
1. Web Development Tools
3. JavaScript Syntax
4. JavaScript Variables
6. JavaScript Numbers
9. ES6
24. JavaScript if
2. getElementsByName
3. getElementsByTagName
4. getElementsByClassName
5. querySelector
7. parentNode
9. JavaScript Siblings
10. CreateElement
11. appendChild
Bootstrap Topic
3. Getting Started
4. Bootstrap Containers
6. Bootstrap Typography
7. Bootstrap Tables
8. Bootstrap Lists
9. bootstrap 5 4
Bonus Gift
Free Hand Written>>
HTML
CSS
JavaScript
Free Guide On >>
How to get into freelancing after this e-book
Action Steps to Polish Your Front-End Development Skills
Building a Great Portfolio: What to Include and What to Avoid
Determining Your Pricing Structure as a Freelance Front-End Developer
Leveraging Freelance Platforms
Utilizing LinkedIn for Freelance Opportunities
Defining Your Services and Target Audience
Most Asked Interview Questions>>
HTML
CSS
JavsScript
Bootstrap
Frontend Projects>>
150 HTML-CSS Projects
150 JavaScript Project
50 Bootstrap Project
25 Complete Website Project
HTML is the foundation of any web page and is an essential skill for anyone interested
in web development. By learning HTML, you will be able to create and design your own
web pages and have a better understanding of how the internet works.
In conclusion, HTML is a powerful and versatile tool for web development and is an
essential skill for anyone interested in building web applications. By mastering the
basics of HTML, you will be able to create web pages that are both functional.
HTML 1
HTML is constantly evolving, and new versions of HTML continue to be developed to
improve the functionality and capabilities of the language. The most recent version of
HTML is HTML5, which introduced new features such as video and audio elements,
semantic tags, and improved support for mobile devices.
One of the strengths of HTML is its ability to work in conjunction with other web
development languages, such as CSS and JavaScript. CSS is used to style and format
the content of a web page, while JavaScript is used to add interactivity and dynamic
functionality to the page.
When creating a web page, it's important to consider factors such as accessibility,
search engine optimization, and usability. By using proper HTML markup and adhering
to web standards, you can ensure that your web pages are accessible to a wide range
of users and are optimized for search engines.
Overall, HTML is a foundational skill for anyone interested in web development and is
an essential tool for creating high-quality, interactive web pages. With its flexibility and
versatility, HTML allows you to create web pages that are both functional and visually
appealing and is a key component of modern web development.
HTML 2
Getting Started with HTML
Welcome to the world of HTML! In this chapter, we will learn the basics of HTML and get
started with creating our first web pages. HTML stands for Hypertext Markup Language,
and it is the foundation of every web page on the Internet. With HTML, you can create
and structure the content of your web pages, and add text, images, links, and more.
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My First Web Page!</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
<!DOCTYPE html> : This is the doctype declaration that tells the browser we are using
HTML5.
<head> : The <head> element contains metadata about the document, such as the
title.
<title>: The <title> element sets the title of the web page displayed in the
browser's title bar or tab.
<body> : The <body> element represents the content of the web page.
<h1> : The <h1> element represents the main heading or title of the page.
<body>
<h1>Welcome to My First Web Page!</h1>
<p>This is a paragraph of text.</p>
<h2>About Me</h2>
<p>Hi, my name is John. I love playing video games and learning about new technologie
s.</p>
<h3>My Hobbies</h3>
<ol>
<li>Playing soccer</li>
<li>Drawing</li>
<li>Reading books</li>
</ol>
</body>
Save the changes and refresh your web page in the browser. You will now see
additional headings, paragraphs, and lists on your web page.
Explanation:
<li> : The <li> element represents a list item within <ul> or <ol> .
<body>
<h1>Welcome to My First Web Page!</h1>
<p>This is a <strong>paragraph</strong> of <em>text
</em>.</p>
<h2>About Me</h2>
<p>Hi, my name is <u>John</u>. I love playing video games and learning about new techn
ologies.</p>
Save the changes and refresh your web page. You will see the text formatted with bold,
italic, and underlined styles.
Explanation:
<body>
<h1>Welcome to My First Web Page!</h1>
<p>This is a paragraph of text. Click the link below to visit my favorite website:</p>
Save the changes and refresh your web page. You will now see a link that says "My
Favorite Website." When clicked, it will take you to the specified URL (in this case,
"https://www.example.com").
Explanation:
href="..." : The attribute specifies the URL or destination of the link. Replace
href
You can also create links to other pages within your website. Let's say you have another
HTML file called "about.html" in the same directory as your current page. You can
create a link to that page using a relative URL:
Congratulations! You have learned the basics of creating an HTML document, adding
content, formatting text, and Creating Links. In the next chapter, we will explore more
exciting features of HTML.
2. Set up the basic structure of the HTML document with the doctype declaration,
<html> , <head> , and <body> tags.
3. Inside the <body> tag, create a heading using <h1> to introduce yourself (e.g., "Meet
[Your Name]"). Add a paragraph below the heading to provide a brief description of
yourself.
4. Add an image of yourself using the <img> tag. You can use an image of your choice
or even create your own simple drawing to represent yourself.
5. Create a section titled "My Interests" using an appropriate heading tag. Within this
section, create an unordered list <ul> or an ordered list <ol> with at least three
items that represent your interests (e.g., sports, art, music, etc.). Feel free to add
images or icons next to each list item to make it visually appealing.
6. Include a section titled "My Favorite Quote" using an appropriate heading tag.
Inside this section, add a blockquote <blockquote> with your favorite quote and cite
its source using the <cite> tag.
8. Save your changes and open the HTML file in a web browser to see your personal
web page in action. Make adjustments as needed and continue experimenting with
different tags and styles to customize your page further.
9. Bonus: Challenge yourself by exploring more HTML tags and features. Try adding
links to your favorite websites, embedding videos or music, or creating a form for
visitors to leave comments or feedback.
Remember to have fun and let your creativity shine while building your personal web
page. Experiment, modify, and make it uniquely yours!
By completing this task, you will gain practical experience in creating web pages,
understanding HTML tags, and exploring different ways to express yourself online.
NOTE:
Don't worry if you feel overwhelmed or if you're not ready to complete this task right
away. It can be challenging to create a web page immediately after learning a few tags.
Remember, we are here to guide you through each step of your learning journey.
In the upcoming chapters, we will explain each HTML tag in detail, providing examples
and further explanations to help you understand its purpose and usage. We believe in
building a strong foundation of knowledge, and that takes time and practice.
So, if you're not ready to complete this task yet, that's absolutely fine! Take your time to
absorb the information, experiment with the examples provided, and gradually build
your understanding. Learning HTML is a process, and we will be there to support you
every step of the way.
Feel free to revisit this task once you have familiarized yourself with more HTML
tags and concepts.
Remember, practice makes perfect, and the more you experiment and create, the
better you will become at designing and building your own web pages.
Keep up the enthusiasm and curiosity. The next chapter will dive deeper into HTML,
expanding your knowledge and empowering you to tackle exciting challenges.
Enjoy your learning journey, and remember, we are here to help you succeed!
<body>
<h1>Welcome to My Web Page!</h1>
<p>This is a paragraph of text. Check out the image below:</p>
Save the changes and make sure you have an image file named "image.jpg" in the
same directory as your HTML file. Refresh the web page, and you will see the image
displayed on the page.
Explanation:
src attribute: The src attribute specifies the source (URL or file path) of the image.
alt attribute: The alt attribute provides alternative text for the image, which is
displayed if the image cannot be loaded or for accessibility purposes.
Save the changes and refresh the page. The image will now be displayed with a width
of 300 pixels and a height of 200 pixels. Adjust the values according to your preference.
Always strive to provide meaningful alt text that accurately describes the image's
content or purpose.
JPEG (JPG): Ideal for photographs and complex images with many colors.
PNG: Suitable for images with transparency or sharp lines, such as logos.
When creating or choosing images for your web page, ensure you optimize them for
web use to reduce file size and improve page loading speed.
Experiment with adding different images and adjusting their size and alt text. Images
can greatly enhance the visual appeal of a website and convey information effectively.
In the next chapter, we will learn about structuring content with lists.
<body>
<h1>Welcome to My Web Page!</h1>
<h2>My Favorite Fruits</h2>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
</body>
<li>: The <li> tag represents a list item within the <ul> or <ol> element.
<body>
<h1>Welcome to My Web Page!</h1>
<h2>Steps to Make a Sandwich</h2>
<ol>
<li>Spread butter on bread slices.</li>
<li>Add cheese, lettuce, and tomato.</li>
<li>Place another bread slice on top.</li>
</ol>
</body>
Save the changes and refresh the web page. You will now see a numbered list
representing the steps to make a sandwich.
<li>: The <li> tag represents a list item within the <ol> or <ul> element.
<body>
<h1>Welcome to My Web Page!</h1>
<h2>My Favorite Foods</h2>
<ul>
<li>Pizza</li>
<li>Burger
<ul>
<li>Cheeseburger</li>
<li>Chicken Burger</li>
<li>Veggie Burger</li>
</ul>
</li>
<li>Ice Cream</li>
</ul>
</body>
Save the changes and refresh the web page. You will see a list of favorite foods, with
"Burger" having a nested list of different burger types.
Explanation:
Experiment with creating different types of lists and nesting them to create a structured
content hierarchy. Lists are versatile and can be used in various contexts to organize
information effectively.
In the next chapter, we will explore tables and how they can be used to represent data.
<body>
<h1>Welcome to My Web Page!</h1>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
Save the changes and refresh the web page. You will see a table with three columns
(Name, Age, and City) and two rows of data.
Explanation:
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>25</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
Save the changes and refresh the web page. The first row will now be rendered as table
headers, visually distinguishing them from the data rows.
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th colspan="2">Address</th>
</tr>
<tr>
<td>John Doe</td>
<td>25</td>
<td rowspan="2">123 Main St</td>
<td rowspan="2">New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>30</td>
</tr>
</table>
colspan: The colspan attribute specifies the number of columns a cell should span.
rowspan: The rowspan attribute specifies the number of rows a cell should span.
<body>
<h1>Welcome to My Web Page!</h1>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
Save the changes and refresh the web page. You will see a form with three input fields
(Name, Email, and Message) and a Submit button.
Explanation:
<form>: The <form> tag represents a form element that contains input fields.
<label>: The <label> tag provides a label or description for an input field.
<input>: The <input> tag creates different types of input fields, such as text, email,
password, and more.
required attribute: The required attribute ensures that the field must be filled in
before submitting the form.
In this example, the form data will be sent to a file named "submit.php" on the server
using the HTTP POST method.
Explore these input field types and experiment with their usage within the form.
Forms are a powerful tool for collecting user input and enabling interactions on web
pages. With HTML forms, you can create a wide range of user experiences and gather
data for further processing.
<!DOCTYPE html>: This is the Document Type Declaration that informs the web
browser about the type and version of HTML used on a web page.
<head> : It includes the page title, scripts, styles & meta-information about website
<!DOCTYPE html>
<html>
<head>
<title>This is a sample page title</title>
</head>
<body>
<h1>This is a heading.</h1>
<p>This is a sample paragraph content.</p>
</body>
</html>
Title: HTML Head element contains the title of the page that is displayed in the
browser title bar.
Scripts: All client-side scripts such as JavaScript often included in this Head
section
Styles: Internal & External Style rules also included inside the Head element
Meta: A few meta tags such as descriptions & keywords about HTML pages are
included inside the head section. These are useful for Search Engines.
The above data in the head is never directly visible in the main browser window. Some
of the head metadata is helpful for search engines like Google for better document
understanding. At the same time, styles are used to extend page formatting. Scripts are
internally used to enhance HTML web page functionality & event handling.
<!DOCTYPE html>
<html>
<head>
<title> HTML Head Tutorial - xyz.com </title>
<meta charset="UTF-8">
<meta name="description" content=" This website provides free online tutorials">
<meta name="keywords" content="HTML, CSS, PHP, SEO">
<meta name="author" content="xyz.com">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
alert("Simple JavaScript Alert");
</script>
</head>
HTML Head 1
<body>
This is sample content.
</body>
</html>
You can see following example, where different kinds of meta-information are included
in the Head element.
When you run the above example, you can see some titles in the Browser title bar as
defined in the title tag in the head. Search engines use meta keywords, descriptions &
author information.
You can read in detail about styles & scripts in later chapters.
HTML Head 2
HTML Elements and Tags
A Website page is made up of multiple HTML elements and an HTML element is made
of HTML tags.
HTML Tags
HTML tags are like labels or keywords to define a web page. These tags tell the
browser about the format or structure of the content.
Most of the tags come in pair. One is called the opening tag and the other is the closing
tag. Tags begin with a less-than sign “<" and end with a greater-than sign ">“ . For
example: <p></p> tags create paragraph content. While <h1></h1> tags are used to
create headings.
HTML Element
An element in HTML generally consists of an opening tag, content, and a closing tag.
We can see the HTML element as an individual web page component.
Start/Opening Tag
HTML elements start with opening tags. For example: <p><b><h1> etc.
End/Closing Tag
HTML elements end with closing tags. For example: </p></b></h1> etc.
Content
We place content between the opening and closing tags. For example: <p> This is
sample content. </p>
</body>
</html>
HTML5 does not require empty elements to be closed. But if you want strict validation,
or if you need to make your document readable by XML parser, you must close all
HTML elements properly.
HTML5 does not require empty elements to be closed. But if you want strict validation,
or if you need to make your document readable by XML parser, you must close all
HTML elements properly.
HTML5 standard does not require lowercase tags but W3C recommends to use
lowercase in HTML
HTML Attributes 1
<p align="left">This content is left aligned</p>
<p align="center">This content is aligned center</p>
<p align="right">This text is right aligned</p>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
HTML Attributes 2
You can read about more HTML attributes for various HTML Elements in each chapter.
For example, anchor tag use "href" attribute for links. Image tag use "alt" attribute for
alternate text.
HTML Attributes 3
HTML Headings
HTML specifies six levels of headings. All heading element has their own font size and
spacing before and after the heading.
Headings are defined with the <h1> to <h6> tags.
<h1>defines the most important (highest level) heading. <h6> defines the least
important heading.
Search engines (such as Google) also use your headings to understand the
important components of your website.
We should use HTML headings to define headings content only. It should not be
used just to make text big or bold.
HTML Headings 1
Complete HTML Example with Headings
<!DOCTYPE html>
<html>
<head>
<title>HTML Headings Example</title>
</head>
<body>
<h1>First Heading</h1>
This is a simple content
<h2>Second Heading</h2>
This is a simple content
</body>
</html>
HTML Headings 2
HTML Paragraphs
HTML paragraph tags are used to define the text paragraphs.
When we create any document, we divide text content into multiple paragraphs.
Similarly, HTML documents can be divided into HTML paragraphs.
HTML <p> The tag defines a paragraph. This Paragraph tag automatically adds some
margin (white space) before and after a paragraph.
Simple Example:
<html>
<head> </head>
<body>
<p>This is the first paragraph. You can add any kind of text here. </p>
<p>This is the second paragraph. This is some sample text. </p>
<p>This is another paragraph. You can add multiple lines of text in this paragraph. </p>
</body>
</html>
HTML Paragraphs 1
HTML Styles
HTML is primarily used to define the structure of the web page While Cascaded style
sheets (CSS) are a language that is used for the presentation of HTML Pages.
Using CSS in HTML, we can change colors, fonts, and other kinds of formatting on a
web page. There are many different ways to include CSS in an HTML page. We will see
a simple way to apply CSS Rules in the HTML Document.
Syntax
You can use style attributes to apply CSS to any HTML page.
style="property: value;"
<body style="background-color:lightblue;">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
HTML Styles 1
<h1 style="color:black;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
HTML Fonts
The font-family property is used to define the font types for an HTML element.
HTML Styles 2
The text-align property is used to set a horizontal text alignment for an HTML element.
HTML Styles 3
HTML Formatting
HTML Formatting tags are used to format the appearance of the text on your web page.
When you use MS Word processor, you format text as bold, italic, or underlined.
Similarly, HTML Formatting tags help you to format text in different ways.
Bold & Strong Tag <b> Sample Text </b> <strong> Sample Text </strong>
Marked (Highlighted)
<mark> Sample Text </mark>
Tag
Deleted (Removed)
<del> Sample Text </del>
Tag
Inserted (Added) Tag <ins> Sample Text </ins>
Next, we will cover these HTML Text formatting tags in detail below.
HTML Formatting 1
HTML Strong Tag: The HTML <strong> element defines strong text, with added
semantic “strong” importance.
HTML Emphasised Tag: The HTML <em> element defines the emphasized text, with
added semantic importance.
HTML Formatting 2
The HTML <small> element defines small text.
HTML Formatting 3
HTML Deleted Text Formatting
The HTML <del> element defines deleted (removed) text.
HTML Formatting 4
HTML Comments
HTML Comment tags are used to insert some useful comments in the HTML document.
Anything you write inside Comment tags will be ignored by the web browser and it will
not show any output to the user. Comments are very helpful for programmers. Using
HTML Comments, you can add some useful descriptions of some code. They help you
understand your code and increase code readability later.
Example of Comment tag: <!-- This is a sample comment -->
<!-- This comment will tell something about the following paragraph -->
<p>This is another paragraph for testing.</p>
<html>
<head>
<title>Multiline Comments Testing</title>
</head>
<body>
<!--
This is a multiline comment and you can
add some description about the following
code so that it will be helpful to others.
-->
<p>This is some sample text.</p>
</body>
</html>
HTML Comments 1
Conditional Comments
Conditional comments define HTML tags to be executed by Internet Explorer only.
<!--[if IE 8]>
.... some HTML or code here only for Internet Explorer...
<![endif]-->
HTML Comments 2
HTML Links
Links are used to connect multiple HTML pages.
A Website is a collection of web pages and these web pages are connected with each
other using HTML links. Users can visit one page to another HTML web page by
clicking on the links.
You can provide a link to any section of the same page, any other page within a
website or any external website as well.
The href attribute is used to specify the link address of the web page. The text between
the anchor tags “Tutorials Class” is visible to the user. Users can click on this and it will
take them to another page.
Example of HTML Link using anchor tag:
<html>
<body>
</body>
</html>
HTML Links 1
Type of Link URLs:
Absolute URLs: These are full addresses to the destination page/link.
Example of Absolute URL is: <a href="http://www.xyz.com/page1.html"> Page 1 Link </a>
Relative URLs: A relative URL links to a file in relation to the present directory.
For example, if you want to create a link from “page1.html” to “page2.html” and both
files are in the same folder, you can simply provide the file name in href. It is called the
relative URL.
Example of Relative URL: <a href="page2.html"> Page 2 Link </a>
It opens the linked page in the same window/tab in which we clicked on the
_self
link. (This is the default link target)
_parent It opens the linked page in the parent frame
_top It opens the linked page in the full body of the window
HTML Links 2
<html>
<body>
</body>
</html>
<html>
<body>
</body>
</html>
HTML Links 3
HTML Images
You can insert HTML images on a web page.
Images play an important part to make a web page attractive and beautiful. You can add
multiple images with a variety of sizes to the HTML page. Some of the most used image
formats and extensions are .jpg, .png, .jpeg & .gif.
Till now, we have used text along with different formatting options. Now we will see how
to add images, graphics, and even icons on our web page.
The source (src) attribute specifies the image URL (address). The <img> tag is an
empty tag, so it does not have any closing tag. However, you can optionally close it like
this: <img />
Example to simply include “photo.jpg”: <img src="photo.jpg">
<img src="myimage.jpg">
If an image is in any sub-folder, you can mention the folder name with the slash “/” and
then the image name. Suppose image “myphoto.jpg” is available in the “pictures” folder,
We can include it as given in the following example:
<img src="pictures/myphoto.jpg">
HTML Images 1
Absolute URL refers to the full Image URL/Path for the image location. You can include
images from external websites using absolute URLs in the source. See the example
below:
<img src="http://xyz.com/wp-content/uploads/2016/04/xyz-logo1.png">
HTML Images 2
<img src="www.xyz.com/photo.jpg" border="5px" >
<html>
<head>
<title>Example of Image Tag & Attribute - Tutorials Class</title>
</head>
<body>
<p>This is a test paragraph.</p>
<img src="sample-picture.jpg" alt="Sample Image Text" border="5" align="right" />
<p>This is sample text. We will add an image in html page.</p>
<img src="test-photo.jpg" height="300" width="400" title="Sample title" />
</body>
</html>
HTML Images 3
HTML Lists
HTML List Tags are used to specify information in the form of a list.
HTML Lists are very useful to group related information together. Often List items looks
well-structured and they are easy to read for users. A list can contain one or more list
elements.
Unordered List used to group a set of items without any order. <ul>,<li>
Unordered lists
Unordered lists are used to list a set of items when they have no special order or
sequence. It is also called a bulleted list.
An unordered list is created using HTML <ul> tag. Each item in the list starts with
the <li> tag
<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>
List Tags
<li> tag is used to display list elements and it is used in ordered and unordered lists.
HTML Lists 1
The above example will list items with bullets (small black circles) by default. There are
different list styles available such as a bullet, circle, etc.
disc Starts a list using discs type bullets (default) <ul type="disc">
<html>
<title> Unordered List Example Test - Tutorials Class </title>
<body>
HTML Lists 2
<li>Black</li>
<li>Green</li>
<li>Blue</li>
</ul>
</body>
</html>
List style type can be set using CSS as well, for example: <ul type="square">. You can
read about them in CSS List Style Tutorial.
Ordered lists
An ordered list is used to list related items in a numbered or other specific order. This is
useful when you want to show counts of items in some way.
The ordered list is created using HTML <ol> tag. Each item in the list starts with
the <li> tag
<ul>
<li>Red</li>
<li>Green</li>
HTML Lists 3
<li>Blue</li>
</ul>
The above example will list colored items with numbers by default. There are different
list styles available for an ordered list such as numbers, letters, etc.
<html>
<title> Ordered List Example - Tutorials Class </title>
<body>
HTML Lists 4
<ol type="a">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>
</body>
</html>
Definition Lists
A definition list is used to list items along with a description of each item.
HTML Lists 5
An ordered list is created using HTML <dl> tag. Between <dl> tag, we use <dt> to
define the terms and <dd> to describe that term.
<dl>
<dt>Computer</dt>
<dd>Computer is an electronic device that is designed to work with Information.</dd>
<dt>HTML</dt>
<dd>HyperText Markup Language (HTML) is the standard markup language for creating web
pages and web applications.</dd>
</dl>
<!DOCTYPE html>
<html>
<body>
<h2>Unordered List</h2>
<ul type="circle">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>
HTML Lists 6
<li>Bannana</li>
<li>Apple</li>
<li>Grapes</li>
</ol>
<h2>Definition List</h2>
<dl>
<dt>Computer</dt>
<dd>Computer is an electronic device that is designed to work with Information.</dd>
<dt>HTML</dt>
<dd>HyperText Markup Language (HTML) is the standard markup language for creating web
pages and web applications.</dd>
</dl>
</body>
</html>
HTML Lists 7
HTML Iframes
An HTML Iframe is used to include and display one web page within another web page.
The iframe is also called Inline Frame. Using HTML Iframes, you can embed one or
more external HTML documents or web pages into your web page.
Iframe Syntax
<iframe src="http://xyz.com/"></iframe>
HTML <iframe> tag is used to create Iframe in the webpage. The src attribute specifies
the webpage address which you want to display in a frame.
HTML Iframes 1
Iframe height and width attributes are used to specify the size of the iframe. By default,
the value of these attributes is specified in pixels, but you can specify in percentage as
well.
Complete the HTML Iframe program with Height and Width:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Iframe – Border
You can set border width using frameborder attribute. iframe always has a border by
default, but we can remove it by setting frameborder="0"
You can set and remove borders using CSS attributes as well. We can read about that
in the CSS border tutorial.
2. Create an HTML Link using the anchor tag and give the above Iframe name to this
link’s target attribute.
This way, when the user will click on the above link, its reference page will be opened in
the target Iframe.
<!DOCTYPE html>
<html>
HTML Iframes 2
<body>
<p> When the user will click on the above link, its reference page will be loaded in the t
arget Iframe.</p>
</body>
</html>
HTML Iframes 3
HTML Forms
HTML Forms are used to collect some data from users on a webpage.
Forms contain special control elements like input text box, checkboxes, radio-button
and submit buttons. Using form elements, you can take different types of data from
users. This data can be used for different purposes.
Example of HTML Forms:
You must have seen different kinds of forms on websites. For example, the User
Registration form is used to collect user data to store in a database. The simple Contact
form allows users to send messages or contact website owners. HTML works with
Server side programming languages (like PHP or ASP) to send this form into the
database or in email.
Form Element
HTML <form> tag is used to define an HTML form. All other form elements are defined
inside this tag. Different types of form elements include input text elements,
checkboxes, radio buttons, submit buttons, and many more.
Example of Simple Form Element
data.
specify the HTTP method to send form
method method="get"
data.
target specify the target window or frame target="_blank"
enctype="multipart/form-data"
enctype specify the encoding of form data (for
HTML Forms 1
media files)
Action Attribute
The action attributes specify the action to be performed after form submission. Mostly,
we pass a page URL into the action.
That action page is usually created with some server-side programming that can
perform some action on form data. Action can be related to inserting form data into a
database or sending that data into some email. For Example: <form action="page2.php">
Method Attribute
The method attribute tells which HTTP method to use for submitting form data. You can
use the GET & POST method.
The GET method sends data along with the page URL. For
Example: <form method="GET">
Target Attribute
The target attribute works in a similar way as in the anchor tag. After form submission,
action will be directed to another page. This action page can be opened in the same
window, a new window, or some frame. Example: <form target="_blank">
Enctype Attribute
The enctype attribute is used to specify how the browser encodes the form data after
submission. An example of an Enctype attribute using default values
is: <form enctype="application/x-www-form-urlencoded">
When you need to send/upload some media file such as pdf or image, set enctype as a
multipart. For example: <form enctype="multipart/form-data">
Example of Form with different attributes:
HTML Forms 2
<html>
<head>
</head>
<body>
<form action="page2.php" method="POST" enctype="multipart/form-data" target="_blank" >
<input type="text">
</form>
</body>
Attributes: You can use the following attributes with the text field:
type=” text” defines the text box/field where the user can enter some text.
HTML Forms 3
the name defines a unique name for every form element to get their data after
submission.
the value specifies the default or initial value in the text field. Users can change it.
<html>
<head> </head>
<body>
<form>
User Name: <input type="text" name="username" value="Enter your Name" ><br>
Mobile: <input type="text" name="mobile">
</form>
</body>
</html>
Radio Button
Radio Button defines a radio button where the user can select one option from multiple
choices in forms. Example: <input type="radio">
Attributes: You can use the following attributes with the text field:
name that defines a unique name for every radio button element to get their data
after submission.
The value that will be transferred as data after submission if the radio box is
value
selected.
<html>
<head> </head>
<body>
<form>
<input type="radio" name="nationality" value="India"> India
<br/>
<input type="radio" name="nationality" checked value="Australia"> Australia
</form>
</body>
</html>
Checkbox Input
HTML Forms 4
Check Boxes are used when you want to allow the selection of more than one option by
the user. Example: <input type="check">
Attributes: You can use the following attributes with checkboxes:
defines a unique name for every radio button element to get their data after
name
submission.
The value that will be transferred as data after submission if the radio box is
value
selected.
<html>
<head>
<title>Form Checkbox Example - xyz.com</title>
</head>
Select your hobbies:
<body>
<form>
<input type="checkbox" name="hobbies" value="singing"> Singing
<br/>
<input type="checkbox" name="hobbies" value="dancing"> Dancing
<br/>
<input type="checkbox" name="hobbies" value="book-reading" checked> Book Reading
<br/>
</form>
</body>
</html>
A simple button defines the regular button with no action. We can add some
specific actions later using JavaScript. Example: <input type="button">
Submit button defines the submit button. When the user clicks on submit button, it
will submit the form to transfer data. Example: <input type="submit">
HTML Forms 5
The reset button is used to create a reset button. When the user clicks on the reset
button, all form data will reset to default values. Example: <input type="reset">
Attributes
<form action="page2.html">
Name:<br>
<input type="text" name="username" value="Robin"><br>
<input type="button" value="Button">
<input type="reset" value="Reset Form">
<input type="submit" value="Submit">
</form
the name defines a unique name for every select menu to identify later get its list
data
multiple attributes allow users to select multiple items from the list at the same
time.
Option Attributes
the value specifies the value of the list item. After submission, this value will be
sent if the user selected an item.
the name defines a unique name for every button to identify later.
the selected attribute in any option set itself as a default selected item in the drop-
down list.
<html>
<body>
HTML Forms 6
<form>
<select name="dropdown">
<option value="" selected>Select your favorite city</option>
<option value="newdelhi" selected>New Delhi</option>
<option value="newyork">New York</option>
<option value="paris">Paris</option>
</select>
</form>
</body>
</html>
<html>
<head>
<title>HTML Forms Element Example - xyz.com </title>
</head>
<body>
<form action="page2.php" method="POST" enctype="multipart/form-data" target="_blank" >
User Name: <input type="text" name="username" value="Enter your Name" >
<br><br/>
Mobile: <input type="text" name="mobile">
<br/><br/>
Select Your Country:
<input type="radio" name="nationality" value="India"> India
<input type="radio" name="nationality" checked value="Australia"> Australia
<br/><br/>
Select Your Hobby:
<input type="checkbox" name="hobbies" value="singing"> Singing
<input type="checkbox" name="hobbies" value="dancing"> Dancing
<input type="checkbox" name="hobbies" value="book-reading" checked> Book Reading
<br/><br/>
Select Your City:
<select name="dropdown">
<option value="" selected>Select your favorite city</option>
<option value="New Delhi" selected>New Delhi</option>
<option value="NewYork">New York</option>
<option value="Paris">Paris</option>
</select>
<br/><br/><br/>
<input type="button" value="Button">
<input type="reset" value="Reset Form">
<input type="submit" value="Submit">
</form>
HTML Forms 7
</body>
</html>
This HTML program will create a Form with different elements. Users can fill in the
information using these form elements. After the user submits a form, all data can be
passed to another page. This form of data can be processed by some server-side
programming languages such as PHP, ASP, or JSP.
HTML Forms 8
HTML Tables
HTML Tables are used to organise information into rows and columns.
In HTML tables you can arrange data such as text, images, or links. Using Tables you
can get better formatting of data.
Used to define a table. All other table tags and data are
Table Tag <table></table>
placed within the Table tag.
Used to define table heading row. Mostly used for the first
Table Heading <th></th>
table row.
Table Row Used to define each table row. <tr></tr>
<html>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Subject</th>
</tr>
<tr>
<th>101</th>
<th>Robin</th>
<th>Maths</th>
</tr>
HTML Tables 1
<tr>
<th>102</th>
<th>John</th>
<th>English</th>
</tr>
</table>
</body>
</html>
Border used to specify borders around the table & cells border="2"
HTML Tables 2
Example using Table Attributes
Here is a simple example using various table attributes.
<!DOCTYPE html>
<html>
<head>
<title> Table Attributes - xyz.com </title>
</head>
<body>
HTML Tables 3
Most of the website layout has one common header area where we place the website
logo or tagline (and sometimes the menu as well). Then we have the main content
section divided into two or three columns.
The bottom of the webpage contains a common footer section, where we can place a
logo, copyright statement, menu, or some other content.
In two columns we have one left or right sidebar area and one content area. In three
columns page design, we have a left sidebar area, a main content area, and then one
right sidebar area.
<!DOCTYPE html>
<html>
<head>
<title>Basic HTML Layout using Tables</title>
</head>
<body>
<table width="90%" border="1" align="center">
<tr>
<td colspan="2" bgcolor="green">
<h1>Website Title or Tagline</h1>
</td>
</tr>
<tr valign="top">
<td bgcolor="lightblue" width="30%">
<b>Fruit Menu</b>
Orange<br />
Banana<br />
Apple<br />
Grapes
</td>
<td bgcolor="orange" width="60%" height="200">
This is the main content area.
</td>
</tr>
<tr>
<td colspan="2" bgcolor="sky blue" align="center">
Copyright © 2023 xyz.com
</td>
HTML Tables 4
</tr>
</table>
</body>
</html>
HTML Tables 5
HTML Frames
HTML Frames are used to divide a browser window into multiple rectangular sections or
frames, where each frame can load and display separate HTML documents.
Warning: Do not use body tags when using frames. Use <frameset> instead of <body> ,
not inside of <body> . Similarly, No other tags like paragraphs, etc can be used along
with frames except inside <noframes> tag.
bordercolor used to set the color of the border between frames bordercolor="blue"
<frame> Attribute
List
Syntax &
Attribute Description
Example
used to give the file or page URL that should be loaded
src src="page1.html"
in the frame.
Frame Set
All frames are defined under the frameset. To use frameset, use the <frameset> tag and
avoid the <body> tag. We can set the rows and columns attributes for this frameset to
HTML Frames 1
define the layout.
Example of Frameset: <frameset rows="70%,30%" border="3">
The above example will create two vertical sections. The first will take 70% of the
browser window and the second will take 30%.
Frame
Each frame section is defined using a frame tag along with the page or file source that
you want to load in that frame. You can set a name for each frame. It will help when you
want to load a page into a certain frame when click on some link.
Example of Frameset: <frame name="left-frame" src="left-section.html">
<!DOCTYPE html>
<html>
<frameset cols="25%,50%,25%">
<frame src="page1.htm">
<frame src="page2.htm">
<frame src="page3.htm">
</frameset>
</html>
No Frame
Some old browsers do not support frames. We can use <noframes> tag along with
frames. The browser will load <noframes> content if frames are not supported. Thus, we
can add body text and some messages if the frame is not loaded.
<HTML>
<HEAD>
<TITLE>A Complete HTML Frameset Example | xyz.com</TITLE>
</HEAD>
<frameset cols="30%, 70%" bordercolor="blue" noresize="noresize">
<frameset rows="100, 200" bordercolor="red">
<frame name="first-frame" src="page1.html">
<frame name="second-frame" src="page2.html">
</frameset>
<frame name="third-frame" src="page3.html">
<noframes>
<p> This document contains frame content. Your browser does not support it. </p>
</noframes>
HTML Frames 2
</frameset>
</HTML>
The above example will first create two frame sections, 30%, and 70%. Now the first
frame is again divided into two frames 50% and 50%. You can see each frame having a
source HTML page to load for example: page1.html, page2.html & page3.html.
HTML Frames 3
CSS
CSS (Cascading Style Sheets) is a styling language used for describing the
presentation of a document written in a markup language such as HTML.
It provides a way to separate the presentation from the content and structure of web
pages. By using CSS, web developers can control the layout, colors, fonts, and
other visual aspects of a web page.
In simple words, CSS is a language used to style web pages. It allows web developers
to create a consistent look and feel across multiple pages and websites. CSS can be
applied directly to HTML elements or through an external style sheet.
For example, let's say you want to change the color of the text on your website.
Without CSS, you would need to go through every page and manually change the color.
With CSS, you can create a style rule that applies to all the pages and changes the
color of the text in one go.
Here is an example of a CSS code snippet that changes the color of the text to red:
p {
color: red;
}
CSS 1
This code applies the color red to all paragraphs on a web page. CSS also allows
developers to target specific elements such as headings, links, and lists.
CSS is used extensively in modern web development, and it is a crucial skill for any web
developer to master. By using CSS, web developers can create visually appealing and
user-friendly websites that are consistent across multiple pages and devices.
One real-life example of how CSS is used is in the design of e-commerce websites.
When you visit an online store, you will see a consistent design and layout across all the
pages. This is achieved through the use of CSS.
The CSS code is written to define the colors, font styles, and layout of the website, and
it is applied to all the pages of the website.
For instance, the navigation menu on an e-commerce website is a critical element that
helps visitors find what they are looking for quickly. With CSS, web developers can
customize the navigation menu's design to make it easy to use and visually appealing.
They can change the menu's color, font size, and style to match the website's overall
look and feel.
Another example of how CSS is used in modern web development is in responsive
design. Responsive design is an approach to web design that ensures a website looks
great and functions well on any device, regardless of its size or orientation. CSS is used
to achieve this by creating a fluid layout that adjusts to the device's screen size.
In conclusion, CSS is a powerful tool that web developers use to create visually
appealing and user-friendly websites. It enables them to separate the presentation from
the content and structure of web pages, making it easier to maintain and update
websites. With CSS, web developers can create a consistent look and feel across
multiple pages and devices, making it easier for visitors to navigate and use websites.
body {
background-color: blue;
}
CSS 2
p {
font-family: "Times New Roman";
font-size: 22px;
}
Examples of Detail
Here, you can see Html tags like body and p. Then we have applied different CSS
formatting to those tags.
CSS 3
What do you need before
learning CSS?
Before learning CSS, you should have basic knowledge of HTML.
Since we are going to use CSS to style the HTML elements, having a basic knowledge
of HTML is a must before learning CSS.
Example
<table border="1">
<tr>
<td>Row1,Column1</td>
<td>Row1,Column2</td>
</tr>
<tr>
<td>Row2,Column1</td>
<td>Row2,Column2</td>
</tr>
</table>
The Style Sheet used to style the above table is given below for reference.
Don't worry if its hard to understand, this is just the start of the CSS tutorial, you will
learn it all in the following tutorials.
<style>
body{
background-color:#FFEBF0;
}
thead {
background-color:#ADDFE7;
}
There are 3 methods through which you can add CSS to the HTML document.
Inline Style.
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
Inline Style
It is not a good practice to use Inline Style Sheets as it requires adding styles directly to
the tags. Use it only if you feel very lazy to use the other two methods.
Inline Styles are added directly inside the tags as shown below.
1. Inline Styles.
CSS SYNTAX
The basic CSS syntax is shown below.
Syntax Explained
The above syntax is explained below using tables.
p {color:red;font-size:10px;}
Selector Declaration
color : blue
Property Value
<html>
<head>
<style>
p{
color: red;
font-size:20px;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
1. Id Selector
2. Class Selector
Id Selector
First of all, what is an Id?
Id is a property of HTML elements that you can specify like shown below.
You can use the specified Id to manipulate the corresponding HTML Element as shown
below.
#para1{
color: red;
font-size:20px;
}
Class Selector
Class is a property of HTML elements that you can specify like shown below.
CSS SELECTOR 1
<p>This is a Paragraph without class.</p>
<h4>This is a Heading without class.</h4>
The difference between class and id is that Class is used to apply styles to a group of
HTML elements while Id is used to apply styles for a single unique HTML element.
Styles are applied to classes as shown below.
.class1{
color: red;
font-size:20px;
}
The above style is applied to the HTML elements with class "class1".
"." symbol is used to specify class.
p{
color: red;
font-size:20px;
}
CSS SELECTOR 2
The above style is applied to the HTML element "Paragraph".
CSS SELECTOR 3
EXAMPLE
In this tutorial, you will learn how to use CSS to make HTML tables look better.
Since this is the beginner's section, only tables are used. Real-time examples are used
in the advanced section.
At the end of this tutorial, the table will look like this.
Samara Miller 20
Allen Scarlet 25
Samara Miller 20
Allen Scarlet 25
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Samara</td>
<td>Miller</td>
<td>20</td>
</tr>
<tr>
<td>Allen</td>
<td>Scarlet</td>
<td>25</td>
</tr>
<tr>
<td>Samara</td>
<td>Miller</td>
<td>20</td>
</tr>
<tr>
<td>Allen</td>
<td>Scarlet</td>
<td>25</td>
EXAMPLE 1
</tr>
</table>
table {
width: 100%;
}
tr:nth-of-type(odd) {
background: #eee;
}
th {
background: #332;
color: white;
}
td, th {
padding: 6px;
text-align: left;
}
Code Explanation
Selector Property Value Description
EXAMPLE 2
the text in every table cells
EXAMPLE 3
CSS BOX MODEL
The HTML document is considered a series of boxes that can be used to style the
layout.
A pictorial representation of the CSS Box Model is shown below.
Padding in CSS
The space around the content box. You can specify the size as required.
Border in CSS
The line that separates the padding and margin. You can create dashed line, normal
lines, and so on.
Margin in CSS
The space after the border till the end is shown in the image above. You can specify the
size as required.
Example
<div class="div1">
Content of div1.
In the above code, there are two div tags, each with a different box style.
The CSS applied to the above code is given below.
.div1 {
height:80px;
width:400px;
padding:30px;
border:2px solid #FF3F34;
margin:20px;
background-color:#C4334D;
}
.div2 {
height:40px;
width:500px;
padding:10px;
border:5px dashed #000123;
}
Example Usage:
Explanation:
In the given example, comments are used to provide additional information and
explanations for different sections of the CSS code.
The first comment /* Styles for the navigation menu */ helps identify the purpose of
the styles that follow and provides a clear context for the .navbar selector.
CSS Comments 1
Within the .navbar rule, a comment /* Adding padding for better spacing */ explains
the intention behind adding padding to the element.
Conclusion
CSS comments are an essential tool for documenting and annotating your code. They
allow you to add explanatory notes that can be helpful to yourself and other developers.
Properly placed comments can make your CSS code more understandable and
maintainable in the long run.
CSS Comments 2
CSS Colors
Colors play a vital role in web design, as they contribute to the overall aesthetics and
user experience of a website. CSS provides various ways to specify colors, allowing you
to create visually appealing styles. Let's explore the different methods to define colors in
CSS.
Color Names
CSS provides a set of predefined color names that you can use directly. Some common
color names include red , blue , green , yellow , black , and many more. Here's an
example:
h1 {
color: red;
}
Hexadecimal Notation
Hexadecimal notation represents colors using a combination of six hexadecimal digits.
Each pair of digits represents the intensity of red, green, and blue (RGB) respectively.
Hex values range from 00 to FF , where 00 represents no intensity (0) and FF
represents maximum intensity (255). Here's an example:
p {
color: #336699;
}
RGB Notation
RGB notation allows you to specify colors using the intensity of red, green, and blue as
decimal values ranging from 0 to 255. The format is rgb(red, green, blue) . For example:
a {
color: rgb(255, 0, 128);
}
CSS Colors 1
RGBA Notation
RGBA notation is similar to RGB, but it includes an additional value for the alpha
channel, which represents the opacity of the color. The alpha channel ranges from 0
(fully transparent) to 1 (fully opaque). Here's an example:
button {
background-color: rgba(0, 128, 0, 0.5);
}
div {
background-color: hsl(180, 50%, 50%);
}
Conclusion
CSS provides various ways to define colors, including color names, hexadecimal
notation, RGB and RGBA notations, and HSL and HSLA notations. Understanding
these methods allows you to unleash your creativity and effectively apply colors to your
web designs. Experiment with different color options to achieve the desired visual
effects on your web pages.
CSS Colors 2
CSS Background Color
The background color property in CSS allows you to set the color of an element's
background. It helps define the visual appearance and style of your web page. Let's
explore how to use the background-color property to set background colors.
Syntax
The background-color property is applied to an HTML element and takes a color value as
its parameter. Here's the basic syntax:
selector {
background-color: color;
}
The selector represents the HTML element(s) you want to target, and color specifies
the desired background color. The color value can be specified using color names,
hexadecimal notation, RGB or RGBA notation, or HSL or HSLA notation.
Examples
ody {
background-color: yellow;
}
button {
background-color: aqua;
}
h1 {
background-color: #336699;
}
p {
background-color: rgb(255, 0, 0);
}
span {
background-color: rgb(0, 128, 0);
}
.container {
background-color: rgba(0, 0, 255, 0.5);
}
.header {
background-color: rgba(255, 0, 0, 0.8);
}
.section {
background-color: hsl(120, 100%, 50%);
}
.footer {
background-color: hsl(240, 100%, 50%);
}
Conclusion
The background-color property in CSS enables you to define the background color of
HTML elements.
Syntax
The color property is applied to an HTML element and takes a color value as its
parameter. Here's the basic syntax:
selector {
color: color;
}
The selector represents the HTML element(s) you want to target, and color specifies
the desired text color. The color value can be specified using color names,
hexadecimal notation, RGB or RGBA notation, or HSL or HSLA notation.
Examples
h1 {
color: red;
}
p {
color: blue;
}
h2 {
color: #336699;
}
span {
a {
color: rgb(255, 0, 0);
}
li {
color: rgb(0, 128, 0);
}
.heading {
color: rgba(0, 0, 255, 0.5);
}
.paragraph {
color: rgba(255, 0, 0, 0.8);
}
.nav-link {
color: hsl(120, 100%, 50%);
}
.footer-link {
color: hsl(240, 100%, 50%);
}
Conclusion
The color property in CSS allows you to define the text color of HTML elements. By
using color names, hexadecimal notation, RGB or RGBA notation, or HSL or HSLA
notation, you can customize the text color and improve the readability and visual appeal
of your web pages. Experiment with different colors to achieve the desired effects and
create engaging designs that enhance the user experience.
Let's explore how to use the border-color property to set border colors.
Syntax
The border-color property is applied to an HTML element and takes a color value as its
parameter. Here's the basic syntax:
selector {
border-color: color;
}
The selector represents the HTML element(s) you want to target, and color specifies
the desired border color. The color value can be specified using color names,
hexadecimal notation, RGB or RGBA notation, or HSL or HSLA notation.
Examples
.button {
border-color: red;
}
.container {
border-color: blue;
}
.box {
border-color: #336699;
}
.card {
border-color: rgb(255, 0, 0);
}
.link {
border-color: rgb(0, 128, 0);
}
.header {
border-color: rgba(0, 0, 255, 0.5);
}
.footer {
border-color: rgba(255, 0, 0, 0.8);
}
.section {
border-color: hsl(120, 100%, 50%);
}
.sidebar {
border-color: hsl(240, 100%, 50%);
}
Conclusion
The border-color property in CSS allows you to define the color of an element's border.
By using color names, hexadecimal notation, RGB or RGBA notation, or HSL or HSLA
notation, you can customize the border color and enhance the visual appeal of your web
Background Color
Setting the background color is one of the simplest ways to style an element's
background. You can use color names, hexadecimal notation, RGB or RGBA notation,
or HSL or HSLA notation to define the background color. Here's an example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: lightblue;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
CSS Backgrounds 1
Background Image
CSS allows you to use images as backgrounds for HTML elements. You can specify the
path to the image using the url() function. Here's an example:
header {
background-image: url("path/to/image.jpg");
}
section {
background-image: url("path/to/another-image.png");
}
Background Repeat
The background-repeat property controls how background images are repeated within an
element. It can have values like repeat , repeat-x , repeat-y , or no-repeat . For example:
div {
background-image: url("path/to/image.jpg");
background-repeat: no-repeat;
}
Background Gradient
CSS gradients allow you to create smooth transitions between two or more colors. You
can define linear or radial gradients using the background-image property with the linear-
gradient() or radial-gradient() functions. Here's an example:
button {
background-image: linear-gradient(to right, red, yellow);
}
section {
background-image: radial-gradient(circle, blue, green);
}
Background Size
CSS Backgrounds 2
The background-size property controls the size of background images. It can have values
like cover , contain , or specific dimensions in pixels or percentages. Here's an example:
div {
background-image: url("path/to/image.jpg");
background-size: cover;
}
Conclusion
CSS provides versatile options for styling backgrounds, including background colors,
images, gradients, repeat patterns, and size adjustments. By leveraging these features,
you can create visually appealing web pages that enhance user experience and
effectively communicate your design intent. Experiment with different combinations and
techniques to achieve the desired effects and make your web designs visually
captivating.
CSS Backgrounds 3
CSS Borders
Borders in CSS allow you to add visual boundaries around HTML elements. They can
enhance the appearance of elements, separate content, and provide a polished look to
your web page. Let's explore various techniques to style borders using CSS.
Border Style
The border-style property specifies what kind of border to display.
The following values are allowed:
ridge - Which defines a 3D ridged border. The effect depends on the border-color
value
inset - Which defines a 3D inset border. The effect depends on the border-color
value
outset - Which defines a 3D outset border. The effect depends on the border-color
value
The border-style property can have from one to four values (for the top border, right
border, bottom border, and left border)
Here's an example:
CSS Borders 1
p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}
Border Width
The border-width property is used to control the width of the border. It can have values
like thin , medium , thick , or specific measurements in pixels. For example:
p {
border-width: 2px;
}
Border Color
CSS Borders 2
The border-color property is used to define the color of the border. You can specify the
color using color names, hexadecimal notation, RGB or RGBA notation, or HSL or
HSLA notation. Here's an example:
h1 {
border-color: red;
}
button {
border-color: #336699;
}
Border Radius
The border-radius property allows you to create rounded corners for borders. It can take
a value in pixels or percentages to specify the radius of the curve. Here's an example:
div {
border-radius: 10px;
}
Shorthand Property
CSS also provides a shorthand property called border that combines border-width ,
border-style , and border-color into a single declaration. Here's an example:
button {
border: 2px solid red;
}
CSS Borders 3
CSS Border Sides
From the examples on the previous pages, you have seen that it is possible to specify a
different border for each side.
In CSS, there are also properties for specifying each of the borders (top, right, bottom,
and left):
p {
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
p {
border-style: dotted solid;
}
CSS Borders 4
left border is dashed
border-style: dotted;
Example
/* Four values */
p {
border-style: dotted solid double dashed;
}
/* Three values */
p {
border-style: dotted solid double;
}
/* Two values */
p {
border-style: dotted solid;
}
CSS Borders 5
/* One value */
p {
border-style: dotted;
}
Conclusion
CSS borders offer a range of possibilities to style and customize the edges of HTML
elements. By utilizing properties such as border-style , border-width , border-color ,
border-radius , and the shorthand border property, you can create visually appealing
designs with distinct borders. Experiment with different combinations and techniques to
achieve the desired effects and enhance the overall aesthetics of your web page.
CSS Borders 6
CSS Margins
Margins in CSS allow you to control the space around HTML elements. They provide
spacing between elements, create visual separation, and help achieve proper layout
and alignment. Let's explore how to use CSS margins to control spacing.
Margin Property
The margin property is used to define the margin around an element. It can have values
in pixels ( px ), percentages ( % ), or other length units. You can set different margin
values for each side of an element (top, right, bottom, left), or use shorthand notation to
set them simultaneously.
Individual Margins:
div {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 15px;
margin-left: 30px;
}
CSS Margins 1
Shorthand Margin:
p {
margin: 5px 10px 5px 10px;
}
The shorthand notation follows the order: top , right , bottom , left . In the example
above, all sides have a margin of 5px except for the top and bottom, which have a
margin of 10px .
Margin Auto
Using the value auto for margins allows for automatic centering or alignment of
elements. This is especially useful when horizontally centering elements within a
container.
div {
margin-left: auto;
margin-right: auto;
}
Negative Margins
Negative margins can be used to pull elements closer together or overlap them. This
technique is helpful for achieving specific layout effects or adjusting the positioning of
elements.
h1 {
margin-top: -10px;
}
Margin Collapse
Margin collapse occurs when the margins of adjacent elements overlap, and the larger
of the two margins "wins." This behavior applies to vertical margins (top and bottom),
but not horizontal margins (left and right). Margin collapse can affect the spacing and
layout of elements, and it's important to be aware of this behavior when designing.
CSS Margins 2
Conclusion
CSS margins allow you to control the spacing around HTML elements. By using
individual margin properties or shorthand notation, you can adjust the margins to
achieve proper spacing and alignment. Additionally, features like margin auto and
negative margins offer flexibility in centering elements and creating specific layout
effects. Understanding margin collapse is also crucial to ensure consistent spacing and
layout in your web page designs.
CSS Margins 3
CSS Padding
Padding in CSS allows you to control the space between the content of an element and
its border. It provides internal spacing, helping to improve readability and create visually
appealing designs. Let's explore how to use CSS padding to control spacing within
elements.
Padding Property
The padding property is used to define the padding around an element. It can have
values in pixels ( px ), percentages ( % ), or other length units. You can set different
padding values for each side of an element (top, right, bottom, left), or use shorthand
notation to set them simultaneously.
Individual Padding:
div {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 15px;
padding-left: 30px;
}
CSS Padding 1
Shorthand Padding:
p {
padding: 5px 10px 5px 10px;
}
The shorthand notation follows the order: top , right , bottom , left . In the example
above, all sides have a padding of 5px except for the top and bottom, which have a
padding of 10px .
Conclusion
CSS padding allows you to control the spacing within elements, creating space between
the content and the border. By using individual padding properties or shorthand
notation, you can adjust the padding to achieve the desired spacing. Understanding
how padding interacts with the content box and background is essential for creating
visually appealing and well-structured designs. Experiment with different padding values
to achieve the desired layout and enhance the readability and aesthetics of your web
pages.
CSS Padding 2
CSS Height, Width, and Max-
width
CSS provides properties to control the dimensions of HTML elements, including their
height, width, and maximum width. These properties allow you to define the size and
layout of elements, ensuring proper spacing and alignment within your web page. Let's
explore how to use CSS height, width, and max-width properties.
Height Property
The height property is used to define the height of an element. It can have values in
pixels ( px ), percentages ( % ), or other length units. Here's an example:
div {
height: 200px;
}
img {
width: 100%;
}
Max-width Property
The max-width property limits the maximum width of an element, allowing it to scale
down if necessary. It is particularly useful for responsive design, ensuring that elements
do not exceed a certain width on different screen sizes. Here's an example:
p {
max-width: 500px;
}
Percentage Values
Using percentage values for height, width, and max-width allows elements to scale
relative to their parent container. For example, setting width: 50% makes the element
occupy half of its parent's width.
Box Sizing
When setting the height and width properties, keep in mind the box-sizing property. By
default, the content box size includes only the content itself, excluding padding and
borders. You can change this behavior using the box-sizing property with a value of
border-box , which includes padding and border within the specified width and height.
div {
box-sizing: border-box;
width: 200px;
padding: 10px;
border: 1px solid black;
}
Conclusion
CSS height, width, and max-width properties allow you to control the dimensions and
layout of HTML elements. By specifying values in pixels, percentages, or other length
units, you can achieve the desired sizing and responsiveness. Understanding the box-
sizing property is also crucial for accurately defining the overall dimensions of an
element. Experiment with different values and techniques to ensure proper spacing,
alignment, and visual appeal in your web page designs.
Outline Style
The outline-style property specifies the style of the outline, and can have one of the
following values:
CSS Outline 1
outset - Defines a 3D outset outline
Outline Width
The outline-widthproperty controls the width of the outline. It can have values like
thin , medium , thick , or specific measurements in pixels. For example:
input {
outline-width: 2px;
}
Outline Color
The outline-color property sets the color of the outline. You can specify the color using
color names, hexadecimal notation, RGB or RGBA notation, or HSL or HSLA notation.
Here's an example:
a {
outline-color: red;
}
div {
outline-color: #336699;
}
Outline Shorthand
CSS Outline 2
CSS also provides a shorthand property called outline that combines outline-width ,
outline-style , and outline-color into a single declaration. Here's an example:
h1 {
outline: 2px solid red;
}
Outline Offset
The outline-offset property specifies the space between the outline and the element's
border or content. It is useful for controlling the positioning of the outline. For example:
button {
outline-offset: 5px;
}
Conclusion
CSS outlines allow you to add a visible border-like outline around elements, providing
visual emphasis and highlighting. By utilizing properties like outline-style , outline-
width , outline-color , and outline-offset , you can customize the appearance and
behavior of outlines. Experiment with different styles, widths, colors, and offsets to
achieve the desired effects and enhance the interactivity and visual appeal of your web
pages.
CSS Outline 3
CSS Text
Font Family
The font-family property is used to specify the font or font family for text. You can
provide multiple font names, separated by commas, to indicate fallback options in case
the desired font is not available. Here's an example:
p {
font-family: Arial, sans-serif;
}
Font Size
The font-size property sets the size of the text. It can have values in pixels ( px ),
percentages ( % ), em units ( em ), or other length units. Here's an example:
h1 {
font-size: 24px;
}
CSS Text 1
Font Weight
The font-weight property controls the thickness or boldness of the text. It can have
values like normal , bold , bolder , or lighter . Here's an example:
span {
font-weight: bold;
}
CSS Text 2
Text Color
The color property is used to set the color of the text. You can specify the color using
color names, hexadecimal notation, RGB or RGBA notation, or HSL or HSLA notation.
Here's an example:
h2 {
color: #336699;
}
Text Alignment
The text-align property controls the alignment of the text within its container. It can
have values like left , right , center , or justify . Here's an example:
p {
text-align: center;
}
CSS Text 3
Text Transformation
The text-transform property is used to specify uppercase and lowercase letters in a text.
It can be used to turn everything into uppercase or lowercase letters, or capitalize the
first letter of each word:
p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize;
}
CSS Text 4
Text Decoration
The text-decoration property is used to add visual effects to the text, such as
underlining, overlining, or striking through. Here's an example:
a {
text-decoration: underline;
}
CSS Text 5
CSS Text Shadow
The text-shadow property adds a shadow to text.
In its simplest use, you only specify the horizontal shadow and the vertical shadow:
h1 {
text-shadow: 2px 2px;
}
CSS Text 6
Line Height
The line-height property defines the spacing between lines of text. It can have values
in pixels, percentages, or unitless numbers. Here's an example:
p {
line-height: 1.5;
}
CSS Text 7
Letter Spacing
The letter-spacing property controls the spacing between individual characters in text. It
can have values in pixels, percentages, or other length units. Here's an example:
h3 {
letter-spacing: 2px;
}
CSS Text 8
Property Description
Conclusion
CSS provides a wide range of properties to style and format text within HTML elements.
By utilizing properties like font-family , font-size , font-weight , color , text-align , text-
decoration , line-height , and letter-spacing , you can create visually appealing and well-
formatted text. Experiment with different combinations and techniques to achieve the
desired effects and enhance the readability and aesthetics of your web pages.
CSS Text 9
CSS Font Style, Font Size &
Shorthand
CSS provides properties to control the font style and font size of text within HTML
elements. These properties allow you to customize the appearance of text, making it
visually appealing and aligned with your design. Let's explore how to use CSS to style
the font and size of text, including a shorthand notation.
Font Style
The font-style property is used to define the style of the font, such as italic or normal.
Here's an example:
p {
font-style: italic;
}
The font-style property can have values like normal , italic , or oblique .
Font Size
The font-size property sets the size of the font used for text. It can have values in
pixels ( px ), percentages ( % ), em units ( em ), or other length units. Here's an example:
h1 {
font-size: 16px;
}
h2 {
font: italic 20px Arial, sans-serif;
}
Conclusion
CSS font style and font size properties allow you to customize the appearance of text
within HTML elements. By using the font-style property to specify the style of the font,
and the font-size property to set the size of the font, you can achieve the desired visual
effects. Additionally, the shorthand font property enables you to set multiple font
properties in a single declaration. Experiment with different font styles, sizes, and
shorthand combinations to achieve the desired typography in your web pages.
3. Contrast is King
Two fonts that are too similar will often conflict. However, contrasts, done the right way,
brings out the best in each font.
Example: Combining serif with sans serif is a well-known combination.
A strong superfamily includes both serif and sans serif variations of the same font (e.g.
Lucida and Lucida Sans).
body {
background-color: black;
font-family: Verdana, sans-serif;
font-size: 16px;
color: gray;
}
h1 {
font-family: Georgia, serif;
font-size: 60px;
Let's explore how to use CSS to style links and make them visually appealing.
Link Color
The color property is used to set the color of unvisited links. You can specify the color
using color names, hexadecimal notation, RGB or RGBA notation, or HSL or HSLA
notation. Here's an example:
a {
color: blue;
}
a:visited {
color: purple;
}
a:hover {
color: red;
}
CSS Links 1
a:active {
color: green;
}
/* unvisited link */
a:link {
color: red;
}
/* visited link */
a:visited {
color: green;
}
/* selected link */
a:active {
color: blue;
}
Text Decoration
CSS Links 2
The text-decoration property is used to add visual effects to links, such as underlining or
removing the underline. Here's an example:
a {
text-decoration: none;
}
a:visited {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:active {
text-decoration: underline;
}
CSS Links 3
More Examples
CSS Links 4
a.three:visited {color: #0000ff;}
a.three:hover {background: #66ff66;}
Cursor Style
The cursor property allows you to change the appearance of the cursor when hovering
over a link. It can be used to provide visual cues and indicate interactivity. Here's an
example:
a:hover {
cursor: pointer;
}
This example demonstrates the different types of cursors (which can be useful
for links):
Conclusion
CSS Links 5
CSS link styles are crucial for enhancing the user experience and providing visual
feedback. By using properties like color , text-decoration , and cursor , you can
customize the appearance of links, including their color, underlining, and cursor style.
Additionally, pseudo-class selectors such as :visited , :hover , and :active enable you
to apply specific styles based on the link's state. Experiment with different styles and
techniques to create visually appealing and user-friendly links on your web pages.
CSS Links 6
CSS Display and Position
CSS provides properties to control the display and positioning of HTML elements.
These properties allow you to define the layout and arrangement of elements within a
web page. Let's explore how to use CSS to manipulate the display and position of
elements.
Display Property
The display property determines how an element is rendered and displayed within the
document flow. It can have various values, each affecting the element's behavior. Here
are some commonly used values:
block : The element generates a block-level box, taking up the full width available
and starting a new line.
inline : The element generates an inline-level box, flowing within the content and
not starting a new line.
inline-block : The element generates an inline-level box that behaves like a block-
level box, allowing other elements to sit beside it.
none : The element is not displayed at all, effectively removing it from the layout.
span {
display: inline;
}
Position Property
The position property determines how an element is positioned within its containing
element. It can have several values, each controlling the positioning behavior. Here are
some commonly used values:
static : The element is positioned according to the normal flow of the document.
fixed : The element is positioned relative to the viewport and does not move when
the page is scrolled.
div {
position: static;
}
img {
position: absolute;
top: 50px;
left: 50px;
}
div {
position: absolute;
z-index: 2;
}
span {
position: absolute;
Conclusion
CSS display and position properties allow you to control the layout and positioning of
HTML elements. By using values like block , inline , relative , absolute , and fixed ,
you can manipulate the display behavior and position elements relative to their normal
flow. Additionally, the z-index property enables you to control the stacking order of
elements along the z-axis. Experiment with different values and techniques to achieve
the desired layout and positioning effects in your web pages.
ul {
list-style-type: disc;
}
ol {
list-style-type: decimal;
}
ul {
list-style-position: outside;
}
ul {
list-style-image: url("marker.png");
}
CSS Lists 1
List Spacing
CSS provides properties to control the spacing and indentation of lists:
list-style-position property can be used to adjust the position of the list markers.
list-style-image property can be used to replace the default list markers with
custom images.
margin and padding properties can be used to control the spacing around the list.
ul {
list-style-position: inside;
list-style-image: none;
margin-left: 20px;
padding-left: 10px;
}
Specifies the distance between the marker and the text content of a
marker-offset
list item.
counter-reset Creates or resets one or more counters used with content property.
counter-increment Increments one or more counters used with content property.
Conclusion
CSS properties such as list-style-type , list-style-position , list-style-image , margin ,
and padding allow you to style and customize HTML lists. By using different values and
combinations of these properties, you can modify the appearance of list markers, adjust
CSS Lists 2
the spacing and alignment of lists, and create visually appealing list styles. Experiment
with different techniques to achieve the desired list presentation on your web pages.
CSS Lists 3
CSS Tables
CSS provides properties to style and customize HTML tables, allowing you to control
the appearance, layout, and spacing of table elements. Let's explore how to use CSS to
style tables and make them visually appealing.
Table Borders
The border property is used to set the border around the table and its cells. It allows
you to define the border width, style, and color. Here's an example:
table {
border: 1px solid #ccc;
}
td, th {
border: 1px solid #ccc;
}
table {
width: 100%;
height: 300px;
}
table {
padding: 10px;
border-spacing: 5px;
}
CSS Tables 1
Table Header Styling
The th element is used to define table headers. You can apply specific styles to table
headers using CSS selectors. Here's an example:
th {
background-color: #f0f0f0;
font-weight: bold;
}
Table Striping
You can use the :nth-child selector to apply alternating styles to table rows, creating a
striped effect. Here's an example:
tr:nth-child(even) {
background-color: #f9f9f9;
}
caption {
font-size: 18px;
font-weight: bold;
}
CSS Tables 2
caption-side
Specifies the placement of the table caption.
empty-cells Controls the display of empty cells in the table.
table-layout Defines the algorithm used for laying out the table.
width Sets the width of the table.
height Sets the height of the table.
text-align Aligns the text within table cells horizontally.
vertical-align Aligns the content within table cells vertically.
padding Sets the space between the cell content and the cell border.
background-color Sets the background color of the table or table cells.
color Sets the text color within table cells.
font-size Sets the font size of the text within table cells.
font-weight Sets the font weight of the text within table cells.
Conclusion
CSS provides a range of properties to style and customizes HTML tables. By using
properties like border , width , height , padding , border-spacing , and CSS selectors like
th and :nth-child , you can create visually appealing and well-structured tables.
Experiment with different styles and techniques to achieve the desired table layout and
appearance on your web pages.
CSS Tables 3
CSS Pseudo-classes and
Combinators
CSS pseudo-classes and combinators provide powerful selectors that allow you to
target specific elements based on various conditions and relationships within the
document structure. They enable you to apply styles to specific states or positions of
elements. Let's explore CSS pseudo-classes and combinators to enhance your styling
capabilities.
Pseudo-classes
Pseudo-classes select elements based on specific states or conditions. They are
denoted with a colon ( : ) followed by the pseudo-class name. Here are some commonly
used pseudo-classes:
:active : Applies styles when the element is being activated, such as when it is
clicked.
a:hover {
color: red;
}
button:active {
background-color: green;
}
input:focus {
border: 1px solid blue;
}
li:nth-child(odd) {
div:first-child {
font-weight: bold;
}
p:last-child {
margin-bottom: 0;
}
Combinators
CSS combinators allow you to select elements based on their relationships to other
elements. There are four types of combinators:
Child selector ( > ): Selects elements that are direct children of a specific element.
div p {
color: blue;
}
ul > li {
font-weight: bold;
}
h2 + p {
margin-top: 0;
}
p ~ span {
font-style: italic;
}
Conclusion
CSS Flexbox 1
Container and Items
CSS Flexbox 2
To use Flexbox, you need a container element that acts as a flex container and one or
more child elements within it that become flex items. The container is defined using the
display property with the value flex or inline-flex . Here's an example:
.container {
display: flex;
}
.container {
flex-direction: row; /* default: horizontal layout */
}
Justify Content
The justify-content property allows you to control the alignment and distribution of flex
items along the main axis. It offers various values like flex-start , flex-end , center ,
space-between , space-around , and space-evenly . Here's an example:
.container {
justify-content: center; /* items are centered along the main axis */
}
Align Items
The align-items property controls the alignment of flex items along the cross axis. It
offers values like flex-start , flex-end , center , baseline , and stretch . Here's an
example:
.container {
align-items: center; /* items are centered along the cross axis */
}
CSS Flexbox 3
Flexbox Ordering
Flexbox allows you to change the order of flex items using the order property. By
default, items have an order of 0. You can assign positive or negative values to change
their order. Here's an example:
.item {
order: 1; /* item appears after other items */
}
.container {
flex-wrap: wrap; /* items wrap to the next line */
}
.item {
flex-grow: 1; /* items grow to fill available space */
}
Controls whether flex items should wrap to the next line when they exceed the
flex-wrap
container width.
Aligns flex items along the main axis and controls the distribution of space
justify-content
between them.
align-items Aligns flex items along the cross axis within the flex container.
CSS Flexbox 4
align-content
Aligns multiple lines of flex items along the cross axis when they wrap, and
controls their spacing.
flex-grow Determines how flex items grow to fill available space.
flex-shrink Determines how flex items shrink when there is not enough space available.
flex-basis Specifies the initial size of flex items before they are flexed.
flex Shorthand property for flex-grow , flex-shrink , and flex-basis .
order Controls the order of flex items within the flex container.
align-self Allows individual flex items to override the align-items property.
flex-flow Shorthand property for flex-direction and flex-wrap .
gap or row-gap
Sets the gap between flex items along the row and column axes.
column-gap
These properties can be applied to the flex container (parent element) and flex items
(child elements) to create flexible and responsive layouts using Flexbox. Use these
properties in combination to control the layout, alignment, and sizing of flex items within
the flex container.
Conclusion
CSS Flexbox provides a flexible and powerful layout system for creating responsive and
dynamic page layouts. By using the flex container and flex items, along with properties
like justify-content , align-items , order , and responsive flex properties, you can create
sophisticated and adaptive layouts. Experiment with Flexbox and combine it with other
CSS properties to achieve the desired layout and design for your web pages.
CSS Flexbox 5
CSS Grid
CSS Grid is a powerful layout system that allows you to create two-dimensional grid-
based layouts with ease. It provides a flexible and intuitive way to arrange elements in
rows and columns. Let's explore CSS Grid and how you can use it to create
sophisticated and responsive layouts.
CSS Grid 1
Container and Grid Items
CSS Grid 2
To use CSS Grid, you need a container element that acts as a grid container and one or
more child elements within it that become grid items. The container is defined using the
display property with the value grid or inline-grid . Here's an example:
.container {
display: grid;
}
.container {
grid-template-columns: 1fr 2fr 1fr; /* 3 columns with flexible width */
grid-template-rows: 100px 200px; /* 2 rows with specific height */
}
Grid Gaps
The gap property sets the gap between grid items, controlling the spacing between
columns and rows. It can take two values to specify the gap horizontally and vertically
respectively. Here's an example:
.container {
gap: 10px 20px; /* 10px gap between rows, 20px gap between columns */
}
Grid Placement
Grid items can be placed within the grid using the grid-column and grid-row properties.
You can specify the start and end positions of the item within the grid using line
numbers or named grid lines. Here's an example:
.item {
grid-column: 1 / 3; /* spans from column line 1 to column line 3 */
CSS Grid 3
grid-row: 2; /* spans in row 2 */
}
property. It controls how the grid items are automatically placed within the grid when
there is no explicit placement defined. Here's an example:
.container {
grid-auto-flow: dense; /* fills empty grid cells with subsequent items */
}
.container {
grid-template-columns: 1fr 2fr; /* default: 2 columns */
}
CSS Grid 4
grid-column-gap
Sets the gap between columns in the grid.
grid-row-gap Sets the gap between rows in the grid.
gap Shorthand property for grid-row-gap and grid-column-gap .
justify-items Aligns grid items along the inline (horizontal) axis within their grid cell.
align-items Aligns grid items along the block (vertical) axis within their grid cell.
place-items Shorthand property for align-items and justify-items .
Aligns grid items along the inline (horizontal) axis within the grid
justify-content
container.
Aligns grid items along the block (vertical) axis within the grid container
align-content
when there is extra space.
place-content Shorthand property for align-content and justify-content .
grid-auto-columns Specifies the size of implicitly created columns in the grid.
grid-auto-rows Specifies the size of implicitly created rows in the grid.
Controls the placement of items in the grid when they are not explicitly
grid-auto-flow
placed.
Shorthand property for grid-template-rows , grid-template-columns , grid-
grid
template-areas , grid-auto-rows , grid-auto-columns , and grid-auto-flow .
grid-area Specifies a grid item's size and location within the grid.
grid-column-start Specifies the start position of a grid item within the grid.
grid-column-end Specifies the end position of a grid item within the grid.
grid-row-start Specifies the start position of a grid item within the grid.
grid-row-end Specifies the end position of a grid item within the grid.
grid-column Shorthand property for grid-column-start and grid-column-end .
grid-row Shorthand property for grid-row-start and grid-row-end .
justify-self Aligns a grid item along the inline (horizontal) axis within its grid cell.
align-self Aligns a grid item along the block (vertical) axis within its grid cell.
place-self Shorthand property for align-self and justify-self .
These properties can be applied to the grid container and grid items to create flexible
and dynamic grid-based layouts using CSS Grid. Use these properties in combination to
control the grid structure, placement, alignment, and sizing of grid items within the grid
container
CSS Grid 5
Conclusion
CSS Grid provides a powerful and flexible layout system for creating sophisticated and
responsive grid-based layouts. By using the grid container, grid items, grid template
columns and rows, gap properties, grid placement, and responsive techniques, you can
create dynamic and adaptive layouts for your web pages. Experiment with CSS Grid
and combine it with other CSS properties to achieve the desired layout and design for
your web projects.
CSS Grid 6
Difference between Flexbox and
Grid
Flexbox and Grid are two powerful layout systems in CSS, each with its own set of
features and use cases. Here's a comparison of Flexbox and Grid to highlight their
differences:
Flexbox:
One-dimensional layout: Flexbox focuses on arranging elements in a single row or
column, known as the main axis.
Ideal for one-dimensional layouts: It works well for creating layouts where elements
need to be flexibly aligned along a single direction.
Provides control over item alignment: Flexbox offers properties like justify-content
and align-items to control the alignment of items along the main axis and cross
axis, respectively.
Optimized for content reordering: Flexbox allows you to easily reorder elements
within a flex container using the order property.
Grid:
Two-dimensional layout: Grid allows you to create layouts with rows and columns,
forming a grid-like structure.
Ideal for complex layouts: It is suitable for creating intricate and multi-dimensional
designs with precise control over the placement and sizing of items.
cells.
Supports explicit item placement: Grid allows you to explicitly position items using
properties like grid-row and grid-column , specifying the start and end positions of
Responsive layouts: Grid is well-suited for responsive layouts as you can adjust the
grid template columns and rows based on different viewport sizes using media
queries.
1. Media Queries: Media queries allow you to apply different CSS styles based on the
characteristics of the device or viewport size. By specifying different CSS rules for
specific screen widths or device features, you can adjust the layout and appearance
of your web page. Here's an example:
1. Fluid Grids: Using CSS grids or flexbox, you can create fluid layouts that adapt to
different screen sizes. By specifying relative units like percentages or fr (fractional
units), the layout adjusts proportionally based on the available space.
4. CSS Flexbox and Grid: CSS flexbox and grid layout modules offer powerful tools
for building responsive designs. They provide flexible and dynamic options for
arranging and aligning elements within containers.
5. Hidden and Shown Elements: CSS can be used to hide or show specific elements
based on screen size or other conditions. This can help optimize the content and
user experience for different devices.
Remember, responsive web design is not just about adjusting the layout; it also involves
considering touch interactions, optimizing performance, and providing a seamless user
experience across different devices.
By leveraging CSS techniques like media queries, fluid grids, flexible images,
responsive typography, and the power of CSS flexbox and grid, you can create
responsive web designs that adapt beautifully to various screen sizes and devices.
Syntax
Media queries are written using the @media rule, followed by a media type (such as
screen or print ) and one or more conditions. The conditions are defined within
parentheses and can include various criteria, such as screen width, device orientation,
pixel density, and more. Here's the basic syntax:
Use max-width for designing from large screens down to smaller ones.
Test your media queries across different devices and screen sizes to ensure they
behave as expected.
Media queries provide a powerful way to create responsive designs by tailoring your
CSS styles to specific device conditions. By utilizing media queries effectively, you can
Media Types
In the syntax of media queries, you can specify the media type to target specific types of
devices. Some common media types include:
For example, you can target only screens with the following media query:
Breakpoints
Breakpoints in responsive design refer to specific screen widths at which the layout or
styles change to accommodate different devices. Media queries are often used with
breakpoints to define these changes. Here's an example of a mobile-first approach
using a common set of breakpoints:
/* Mobile-first styles */
/* Styles applied to screens up to 767px wide */
By defining styles for different breakpoints, you can create a responsive layout that
adjusts gracefully across a range of screen sizes.
Mobile-First Approach
The mobile-first approach is a design philosophy where you start with the smallest
screen size (mobile devices) and progressively enhance the layout and styles for larger
screens. With this approach, you apply base styles that work well on small screens and
use media queries to add additional styles and adjust the layout as the screen size
increases.
By adopting a mobile-first approach, you ensure that your website is optimized for
mobile devices and can adapt to larger screens, providing a better user experience
across a variety of devices.
CSS media queries provide a powerful mechanism to create responsive and adaptive
designs. By understanding how to use media queries, specifying breakpoints, adopting
a mobile-first approach, and testing your designs thoroughly, you can effectively build
websites that respond and adapt to different devices and screen sizes.
color Matches the number of bits per color component for the output device.
Matches the number of entries in the color lookup table for the output
color-index
device.
Matches the number of bits per pixel in a monochrome frame buffer for the
monochrome
output device.
Specifies the resolution of the output device, typically in dots per inch (dpi)
resolution
or dots per centimeter (dpcm).
hover Matches devices that support hover interactions.
These are just some examples of commonly used media query tags. CSS media
queries provide a powerful toolset to target specific device conditions and create
Using max-width: 100% : Apply the max-width: 100% CSS property to the img tag or the
parent container to ensure that the image scales proportionally within its container while
maintaining its aspect ratio. This technique prevents images from overflowing their
containers on smaller screens.
img {
max-width: 100%;
height: auto;
}
Using srcset attribute: The srcset attribute allows you to provide multiple versions of
an image with different resolutions or sizes. The browser can then choose the most
appropriate image based on the device's pixel density and viewport size.
<img src="image.jpg"
srcset="image-small.jpg 320w,
image-medium.jpg 640w,
image-large.jpg 1024w"
alt="Responsive Image">
In the srcset attribute, you specify the image sources followed by their corresponding
widths ( w ). The browser selects the image with the closest width to the device's
viewport and loads that image.
Using picture element: The picture element allows you to provide multiple sources for
an image and specify different media conditions for each source. This technique is
particularly useful when you need to display different images based on various
conditions, such as screen resolution or device capabilities.
In this example, different images are loaded based on the specified media conditions.
The browser chooses the appropriate source based on the matching media condition.
Using CSS background-image : If you're using CSS background-image to display images,
you can make them responsive by applying the background-size: cover property. This
ensures that the image covers the entire container without distorting its aspect ratio.
.container {
background-image: url('image.jpg');
background-size: cover;
background-position: center;
}
By combining these techniques, you can create responsive images that adapt to
different devices and screen sizes. It's important to optimize your images for the web to
ensure faster loading times and better performance on various devices. Consider using
image compression techniques and formats like WebP or JPEG XR to reduce file sizes
without compromising image quality.
1. Using Percentage Widths: One of the simplest ways to create a fluid layout is by
setting the widths of elements using percentages instead of fixed pixel values. By
specifying a percentage width, elements will automatically adjust their size based on
the available space within the parent container. For example:
.container {
width: 100%;
}
.column {
width: 50%;
}
In this example, the container element takes up the full width of its parent, and each
column element takes up 50% of the container's width. As the screen size changes, the
columns will adjust accordingly.
2. Using CSS Flexbox: Flexbox is a powerful CSS layout module that provides
flexible and responsive layout capabilities. It allows you to create fluid layouts with
ease by defining flexible containers and distributing space among child elements.
Here's an example:
.container {
display: flex;
}
.column {
flex: 1;
}
In this case, the container element becomes a flex container, and the columns become
flex items. By applying flex: 1 to the columns, they will distribute the available space
equally, regardless of the screen size.
.container {
display: grid;
grid-template-columns: 1fr 1fr;
}
In this example, the container element becomes a grid container with two equally sized
columns. The columns will automatically adjust their width based on the available
space.
By combining these techniques and using media queries to define breakpoints, you can
create fluid layouts that adapt to various screen sizes. It's important to consider the
content within your layout and ensure it flows properly as elements adjust their size.
Additionally, optimizing your layout for mobile-first design and testing across different
devices will help ensure a seamless and responsive experience for your users.
Here are a few more tips and techniques for creating fluid layouts
with CSS:
4. Using max-width and min-width : In addition to setting widths using percentages, you
can use max-width and min-width properties to create fluid layouts that have flexible
constraints. By setting a max-width on elements, you can ensure that they don't
exceed a certain width, allowing them to shrink and expand based on available
space. On the other hand, using min-width can prevent elements from becoming too
narrow on smaller screens. For example:
.container {
max-width: 1200px;
}
.column {
width: 100%;
max-width: 400px;
min-width: 200px;
}
5. Using vw and vh units: CSS viewport units, vw (viewport width) and vh (viewport
height), allow you to define sizes relative to the size of the viewport. These units are
particularly useful for creating fluid layouts that adapt to the screen size. For
example:
.container {
width: 90vw;
}
.column {
width: 30vw;
}
In this example, the container element will occupy 90% of the viewport width, and each
column element will occupy 30% of the viewport width. This ensures that the layout
adjusts proportionally to different screen sizes.
6. Using calc() function: The calc() function in CSS allows you to perform
calculations to set widths and sizes of elements. It can be handy for creating fluid
layouts with precise adjustments. For example:
.container {
width: calc(50% - 20px);
}
.column {
width: calc(33.33% - 10px);
}
In this case, the container element will have a width that is 50% of the available space
minus 20 pixels, and each column element will have a width that is approximately one-
third of the available space minus 10 pixels.
Remember to consider responsive design principles and test your layouts across
various devices and screen sizes. It's important to ensure that your fluid layouts are
CSS provides powerful features for transforming, transitioning, and animating elements
on a web page. These features allow you to create visually engaging effects and add
interactivity to your designs. Let's explore each of these concepts in detail:
CSS Transforms:
CSS transforms enable you to modify the appearance and position of elements in 2D or
3D space. Here are some common transform properties:
.rotate {
transform: rotate(45deg);
}
CSS Transitions:
CSS transitions allow you to smoothly animate property changes over a specified
duration. They provide a way to add simple animations to elements when a property
value changes. Here's an example of transitioning the background color of a button:
.button {
background-color: blue;
.button:hover {
background-color: red;
}
In this case, when hovering over the button, the background color transitions from blue
to red over a duration of 0.3 seconds, using an easing function for a smooth effect.
CSS Animations:
CSS animations offer more advanced and complex animations by defining keyframes
and animating between them. Keyframes define specific points in an animation
sequence, and CSS takes care of animating the element between those points. Here's
an example of a pulsating animation:
@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
.pulsate {
animation: pulse 1s infinite;
}
In this example, the element with the class .pulsate scales up and down continuously,
creating a pulsating effect. The animation is defined using keyframes, and the infinite
keyword ensures that it repeats indefinitely.
You can combine these features to create even more complex and dynamic effects. For
example, you can apply transforms along with transitions or animations to create
interactive and visually appealing elements on your web page.
Remember to consider performance implications when using complex animations,
especially on mobile devices, and use CSS hardware acceleration techniques, such as
Here are some additional details and tips about CSS transforms, transitions, and
animations:
CSS Transforms:
CSS transforms work by modifying the coordinate space of an element without
changing its layout or affecting other elements. This makes transforms ideal for
creating visual effects such as rotations, scaling, and 3D transformations.
You can use the transform-origin property to change the reference point around
which the transformation occurs. By default, the transformation occurs around the
center of the element.
Property Description
transform Specifies a list of transformations to apply to an element.
translate() Moves an element along the X and/or Y axis.
translateX() Moves an element along the X axis.
translateY() Moves an element along the Y axis.
scale() Scales an element by a specified factor.
scaleX() Scales an element along the X axis.
scaleY() Scales an element along the Y axis.
rotate() Rotates an element by a specified angle.
skew() Skews an element along the X and/or Y axis.
skewX()
backface- Specifies whether or not the back face of an element is visible when it is facing
visibility
away from the viewer.
CSS Transitions:
CSS transitions allow you to smoothly animate changes in CSS properties over
time. They provide a simple way to add subtle animations to elements.
The transition property is used to define the property or properties that should be
transitioned, along with the duration and timing function.
Timing functions control the speed of the transition. Common timing functions
include ease , ease-in , ease-out , linear , and cubic-bezier .
transition-delay Specifies a delay before the transition starts. All HTML tags
CSS Animations:
CSS animations provide a way to create complex and dynamic animations by
defining keyframes and animating between them.
Keyframes define the intermediate states of an animation. You can specify different
styles for different percentages of the animation's duration.
Animations are created using the @keyframes rule, followed by a name that can be
referenced in the animation property.
The animation property is used to specify the animation name, duration, timing
function, delay, and other parameters. Multiple animations can be applied to an
element, separated by commas.
Additional Tips:
Be mindful of performance when using CSS animations. Complex animations or
animating properties with a high repaint cost (such as box-shadow or transform ) can
lead to reduced performance, especially on older devices or browsers.
Consider using CSS pre-processors like Sass or Less to simplify the creation and
management of animations by leveraging their looping and interpolation features.
For more advanced animations and fine-grained control, you may need to use
JavaScript-based animation libraries like GSAP (GreenSock Animation Platform) or
Improved grid system: Bootstrap 5 comes with an improved and revamped grid
system that is more intuitive and easier to use. It also includes new classes for
responsive spacing and flexbox utilities.
New utility classes: Bootstrap 5 includes new utility classes for customizing
typography, spacing, and colors. These classes allow you to easily customize the
look and feel of your website without having to write custom CSS.
bootstrap 5 1
In addition to the above features, Bootstrap 5 also includes improved accessibility and
documentation, making it easier for developers to build accessible and responsive
websites.
Bootstrap 5 is a great improvement over its predecessor, and it offers developers even
more tools and features to build responsive and mobile-first websites. Below are some
of the features that make Bootstrap 5 stand out from the previous version:
New components
Bootstrap 5 includes new components such as accordions, badges, and spinners.
These components make it easier to create complex UI elements without having to write
custom code. This saves time and makes it easier to create a great-looking website.
Improved accessibility
Bootstrap 5 includes improved accessibility features that make it easier to build
accessible websites. This is an important feature for developers who want to make sure
bootstrap 5 2
that their websites are accessible to everyone.
RTL support
Bootstrap 5 comes with a new feature called "RTL (Right-to-Left) support". This feature
allows developers to create websites that support languages that are written from right
to left, such as Arabic and Hebrew. This is a major improvement for developers who
build websites for a global audience.
bootstrap 5 3
Why Learn Bootstrap?
Mobile first approach − Bootstrap 3, framework consists of Mobile first styles
throughout the entire library instead them of in separate files.
Easy to get started − With just the knowledge of HTML and CSS anyone can get
started with Bootstrap. Also, the Bootstrap official site has a good documentation.
It contains beautiful and functional built-in components which are easy to customize.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.c
ss" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundl
e.min.js"></script>
</head>
<body>
</body>
</html>
Applications of Bootstrap
Scaffolding − Bootstrap provides a basic structure with Grid System, link styles,
and background. This is is covered in detail in the section Bootstrap Basic
Structure
CSS − Bootstrap comes with the feature of global CSS settings, fundamental HTML
elements styled and enhanced with extensible classes, and an advanced grid
system. This is covered in detail in the section Bootstrap with CSS.
JavaScript Plugins − Bootstrap contains over a dozen custom jQuery plugins. You
can easily include them all, or one by one. This is covered in detail in the
section Bootstrap Plugins.
Audience
This tutorial has been prepared for anyone who has a basic knowledge of HTML and
CSS and has the urge to develop websites. After completing this tutorial you will find
yourself at a moderate level of expertise in developing web projects using Twitter
Bootstrap.
Prerequisites
Before you start proceeding with this tutorial, we are assuming that you are already
aware of the basics of HTML and CSS.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Basic HTML File</title>
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
Getting Started 1
Tip: Always include the viewport <meta> tag inside the <head> section of your document
to enable touch zooming and ensure proper rendering on mobile devices.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Basic Bootstrap Template</title>
<!-- Bootstrap CSS file -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" r
el="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65Vohhpuu
COmLASjC" crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<!-- Bootstrap JS file Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.mi
n.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
</body>
</html>
And we're all set! After adding Bootstrap's CSS and JS files to our HTML page, we can
begin to develop any responsive site or application with the Bootstrap framework.
The attributes integrity and crossorigin have been added to CDN links to
implement Subresource Integrity (SRI). It is a security feature that enables you to
mitigate the risk of attacks originating from compromised CDNs, by ensuring that the
files your website fetches (from a CDN or anywhere) have been delivered without
Getting Started 2
unexpected or malicious modifications. It works by allowing you to provide a
cryptographic hash that a fetched file must match.
Note: The biggest change in Bootstrap 5 is it doesn't require jQuery anymore. However,
you can still use jQuery to quickly implement Bootstrap component's methods and
options. If Bootstrap detects jQuery in the window object it'll add all of its components in
jQuery's plugin system. You will learn about them in the advanced section of this tutorial
series.
Tip: If the visitor to your website has already downloaded Bootstrap's CSS and JS files
from the same CDN while visiting the other sites, it will be loaded from the browser's
cache instead of re-downloading, which leads to faster loading time.
Getting Started 3
Using the minified version of CSS and JS files will improve the performance of your
website and saves precious bandwidth because of lesser HTTP request and download
size.
Tip: There's no need to include the required Popper.js (in order to make the Bootstrap's
tooltip and popover components work) separately, as it is already included in the
"bootstrap.bundle.js" and minified "bootstrap.bundle.min.js" files.
Getting Started 4
Bootstrap Containers
Creating Containers with Bootstrap
Containers are the most basic layout element in Bootstrap and are required when using the grid system. Containers are basically
used to wrap content with some padding. They are also used to align the content horizontally center on the page in case of fixed
width layout.
The table below illustrates how each container's max-width changes across each breakpoint.
For example, when using the .container class the actual width of the container will be 100% if the viewport width is <576px, 540px
if the viewport width is ≥576px but <768px, 720px if the viewport width is ≥768px but <992px, 960px if the viewport width is ≥992px
but <1200px, 1140px if the viewport width is ≥1200px but <1400px, and 1320px if the viewport width is ≥1400px.
Similarly, when you use the .container-lg class the actual width of the container will be 100% until the viewport width is <992px,
960px if the viewport width is ≥992px but <1200px, 1140px if the viewport width ≥1200px but <1400px, and 1320px if the viewport
width is ≥1400px.
Example
<div class="container">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>
Example:
Bootstrap Containers 1
<div class="container-fluid">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>
For example, .container-xl will be 100% wide until the xl breakpoint is reached (i.e., viewport width ≥ 1200px), after which max-
width for xl breakpoint is applied, which is 1140px.
Example:
Example:
<!-- Container with dark background and white text color -->
<div class="container bg-dark text-white">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>
Bootstrap Containers 2
Tip: Avoid setting left and right margin on fixed and responsive containers, because the value auto is applied automatically
to margin-left and margin-right property by the Bootstrap at certain breakpoints to align the container horizontally center.
Bootstrap Containers 3
Bootstrap Grid System
Bootstrap's grid system is a powerful tool for creating responsive layouts. It uses a
series of containers, rows, and columns to create a grid that can be used to organize
content on any device.
Containers
Containers are the basic building blocks of the Bootstrap grid system. They define the
width of the grid and provide a way to center content. Containers can be nested to
create more complex layouts.
Rows
Rows are used to create horizontal rows of columns. Rows can be divided into columns
using the col- class. The col- class takes a width argument that specifies the width of
the column. For example, col-md-4 creates a column that is 4 columns wide on medium
devices (screens 992px and up).
Columns
Columns are used to create vertical columns of content. Columns can be nested to
create more complex layouts.
Grid Classes
Bootstrap provides a number of grid classes that can be used to control the layout of
content within the grid. These classes can be used to specify the width, alignment, and
spacing of columns.
Responsiveness
Bootstrap's grid system is responsive, which means that the layout will change
depending on the size of the device. For example, on a small device, the columns will
be stacked on top of each other, while on a large device, the columns will be displayed
next to each other.
Examples
<div class="container">
<div class="row">
<div class="col-md-6">
Content 1
</div>
<div class="col-md-6">
Content 2
</div>
</div>
</div>
This code will create a two-column layout with equal-width columns on medium devices
(screens 992px and up). On smaller devices, the columns will be stacked on top of each
other.
2. A three-column layout:
<div class="container">
<div class="row">
<div class="col-md-4">
Content 1
</div>
<div class="col-md-4">
Content 2
</div>
<div class="col-md-4">
Content 3
</div>
</div>
</div>
This code will create a three-column layout with equal-width columns on medium
devices (screens 992px and up). On smaller devices, the columns will be stacked on
top of each other.
3. A fluid layout:
<div class="container">
<div class="row">
This code will create a fluid layout with one column that will fill the width of the container
on all devices.
Conclusion
The Bootstrap grid system is a powerful tool for creating responsive layouts. It is easy to
use and provides a great deal of flexibility. If you are looking for a way to create
responsive layouts for your website or web app, Bootstrap is a great option.
NOTE: I encourage you to actively experiment with each code snippet and
observe the results firsthand. This hands-on approach will empower you to grasp
the intricacies of Bootstrap more effectively, especially considering the slightly
complex nature of its properties for beginners.
Further, in large screen size devices like laptops and desktops it is rendered as three
column grid layout which has 3 columns and 4 rows and finally in extra large screen
devices like large desktops it is rendered as four column grid layout which has 4
columns and 3 rows.
Now the question is how we can create such responsive layouts using this Bootstrap
flexbox grid system. Let's start with the primary target device. Suppose our primary
target device is laptop or normal desktop. Since our laptop layout has 3 columns and 4
rows i.e. 3x4 grid layout, so the HTML code for making such grid structure would look
something like this.
Example:
<div class="container-lg">
<div class="row">
<div class="col-xl-4"><p>Box 1</p></div>
<div class="col-xl-4"><p>Box 2</p></div>
<div class="col-xl-4"><p>Box 3</p></div>
<div class="col-xl-4"><p>Box 4</p></div>
<div class="col-xl-4"><p>Box 5</p></div>
<div class="col-xl-4"><p>Box 6</p></div>
<div class="col-xl-4"><p>Box 7</p></div>
<div class="col-xl-4"><p>Box 8</p></div>
<div class="col-xl-4"><p>Box 9</p></div>
<div class="col-xl-4"><p>Box 10</p></div>
<div class="col-xl-4"><p>Box 11</p></div>
<div class="col-xl-4"><p>Box 12</p></div>
</div>
</div>
Tip: The .container-lg class makes the container 100% wide if the width of the viewport
is less than 992px, thus utilizing the full available width on smaller screens.
If you see the output of the above example in a large device such as a laptop or desktop
which has screen or viewport width greater than or equal to 1200px but less than
1400px, you will find the layout has 4 rows where each row has 3 equal columns
resulting in 3x4 grid layout.
<div class="container-lg">
<div class="row">
<div class="col-xl-4 col-md-6"><p>Box 1</p></div>
<div class="col-xl-4 col-md-6"><p>Box 2</p></div>
<div class="col-xl-4 col-md-6"><p>Box 3</p></div>
<div class="col-xl-4 col-md-6"><p>Box 4</p></div>
<div class="col-xl-4 col-md-6"><p>Box 5</p></div>
<div class="col-xl-4 col-md-6"><p>Box 6</p></div>
<div class="col-xl-4 col-md-6"><p>Box 7</p></div>
<div class="col-xl-4 col-md-6"><p>Box 8</p></div>
<div class="col-xl-4 col-md-6"><p>Box 9</p></div>
<div class="col-xl-4 col-md-6"><p>Box 10</p></div>
<div class="col-xl-4 col-md-6"><p>Box 11</p></div>
<div class="col-xl-4 col-md-6"><p>Box 12</p></div>
</div>
</div>
Tip: For convenience choose your primary target device and create layout for that
device first after that add classes to make it responsive for other devices.
Similarly, you can customize the layout for extra extra large devices such as a large
desktop screen by adding the class .col-xxl-3 on each column, as every row in that
layout contains 4 columns (i.e. 4x3 grids layout). Here's the final code after combining
the whole process.
Example
<div class="container-lg">
<div class="row">
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 1</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 2</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 3</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 4</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 5</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 6</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 7</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 8</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 9</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 10</p></div>
Tip: According to the above illustration there is no need to customize the layout for
mobile phones; since columns on extra small devices will automatically become
horizontal and rendered as 1x12 column grid layout in absence of .col-* or .col-sm-
* classes.
<div class="container">
<div class="row">
<div class="col-sm-8">Column left</div>
<div class="col-sm-4">
<!--Column right with nested rows and columns-->
<div class="row">
<div class="col-12"></div>
</div>
<div class="row">
<div class="col-6"></div>
<div class="col-6"></div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-3">Column left</div>
<div class="col-md-auto">Variable width column</div>
<div class="col-md-3">Column right</div>
</div>
<div class="row">
<div class="col">Column left</div>
<div class="col-auto">Variable width column</div>
<div class="col">Column right</div>
</div>
</div>
<div class="container">
<div class="row align-items-start">
<div class="col">Column one</div>
<div class="col">Column two</div>
<div class="col">Column three</div>
</div>
<div class="row align-items-center">
<div class="col">Column one</div>
<div class="col">Column two</div>
<div class="col">Column three</div>
</div>
<div class="row align-items-end">
<div class="col">Column one</div>
<div class="col">Column two</div>
<div class="col">Column three</div>
Individual columns inside a row can also be aligned vertically. Here's an example:
Example
<div class="container">
<div class="row">
<div class="col align-self-start">Column one</div>
<div class="col align-self-center">Column two</div>
<div class="col align-self-end">Column three</div>
</div>
</div>
Note: You can skip the number in .col-* grid class and just use the .col class to
create equal size columns for all devices (extra small, small, medium, large, and extra
large).
container, respectively. Let's check out the following example to see how it works:
Example
<div class="container">
<div class="row justify-content-start">
<div class="col-4">Column one</div>
<div class="col-4">Column two</div>
</div>
<div class="row justify-content-center">
<div class="col-4">Column one</div>
<div class="col-4">Column two</div>
</div>
<div class="row justify-content-end">
<div class="col-4">Column one</div>
<div class="col-4">Column two</div>
</div>
</div>
start and the last column placed at the end. Try out the following example to see how it
actually works:
Example
<div class="container">
<div class="row justify-content-around">
<div class="col-4">Column one</div>
<div class="col-4">Column two</div>
</div>
<div class="row justify-content-between">
<div class="col-4">Column one</div>
<div class="col-4">Column two</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col order-last">First, but ordered at last</div>
<div class="col">Second, but unordered</div>
<div class="col order-first">Last, but ordered at first</div>
</div>
</div>
You can also use the .order-* classes to order the grid columns depending on the order
numbers. Grid column with higher order number comes after the grid column with lower
order number or grid column with no order classes. It includes support for 1 through 12
across all five grid tiers.
<div class="container">
<div class="row">
<div class="col order-4">First, but ordered at last</div>
<div class="col">Second, but ordered at first</div>
<div class="col order-1">Last, but ordered at second</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-8"></div>
</div>
<div class="row">
<div class="col-sm-8 offset-sm-4"><!--Column with 4 columns offset--></div>
</div>
</div>
You can also offset columns using the margin utility classes. These classes are useful in
the situations where the width of the offset is not fixed. Here's an example:
Example
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4 ms-auto"><!--Offset this column to right--></div>
Note: You can use the class .col-auto to create columns that only take up as much
space as needed, i.e. the column sizes itself based on the contents.
<div class="container">
<!-- Break columns on all devices -->
<div class="row">
<div class="col">.col</div>
<div class="col">.col</div>
<div class="w-100"></div>
<div class="col">.col</div>
We hope you've understood the basics of the new Bootstrap 5 grid system.
Headings
Bootstrap offers six levels of headings ( h1 to h6 ) with predefined styles. These
headings have a decreasing hierarchy, with h1 being the highest and h6 the lowest. By
applying these classes to your HTML headings, you can ensure consistent and visually
appealing typography across your website.
Example usage:
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
Display Headings
Bootstrap also provides larger display headings for creating attention-grabbing
headlines. These headings are specifically designed to stand out on the page, making
them ideal for important titles or key sections.
Example usage:
Lead Text
Bootstrap Typography 1
Bootstrap offers a .lead class to emphasize introductory or important paragraphs. It
adds extra visual weight and increases the font size slightly to grab the reader's
attention.
Example usage:
<p class="lead">This is an example of lead text. It stands out and grabs attention.</p>
Text Formatting
Bootstrap provides several classes for text formatting, allowing you to style and
emphasize text as needed.
The .text-capitalize class can be used to capitalize the first letter of each word in
the text.
Example usage:
Blockquotes
Bootstrap provides styles for formatting and presenting blockquotes, which are used to
highlight quoted content.
Example usage:
Bootstrap Typography 2
<blockquote class="blockquote">
<p class="mb-0">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere
erat a ante.</p>
<footer class="blockquote-footer">Someone famous in <cite title="Source Title">Source Ti
tle</cite></footer>
</blockquote>
These are just a few examples of the typography features provided by Bootstrap. By
utilizing these classes and styles, you can easily create visually appealing and
consistent typography throughout your website, even if you are a beginner with limited
CSS knowledge.
Remember to refer to the Bootstrap documentation for a comprehensive list of
typography classes and their usage.
More about Typography 🔗
Bootstrap Typography 3
Bootstrap Tables
What is Table?
The HTML tables are used to present data in grid manner like row and columns. Using
Bootstrap you can greatly improve the appearance of the table in a quick and easy way.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Simple Table</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Clark</td>
<td>Kent</td>
<td>clarkkent@mail.com</td>
Bootstrap Tables 1
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
</tr>
<tr>
<td>3</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
— The output of the above example will look something like this:
For example, you can create a dark version of the table (i.e. table with light text on dark
backgrounds) by adding the contextual class .table-dark to the .table base class, like
this:
Example
Bootstrap Tables 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Dark Table</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<table class="table table-dark">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Clark</td>
<td>Kent</td>
<td>clarkkent@mail.com</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
</tr>
<tr>
<td>3</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
— The output of the above example will look something like this:
Bootstrap Tables 3
Similarly, you can use other contextual classes. For instance, the following example
uses the class .table-success on the .table to create green colored variant of a table.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Accented Tables</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<table class="table table-primary">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Clark</td>
<td>Kent</td>
<td>clarkkent@mail.com</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
</tr>
Bootstrap Tables 4
<tr>
<td>3</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
</tr>
</tbody>
</table>
Bootstrap Tables 5
<td>clarkkent@mail.com</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
</tr>
<tr>
<td>3</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
</tr>
</tbody>
</table>
Bootstrap Tables 6
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Clark</td>
<td>Kent</td>
<td>clarkkent@mail.com</td>
</tr>
<tr>
<td>2</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
</tr>
<tr>
<td>3</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
</tr>
</tbody>
</table>
Bootstrap Tables 7
</table>
— The output of the above example will look something like this:
Bootstrap Tables 8
Tip: You can use these contextual classes on the .table base class to create colored
version of any table such as stripped, hoverable, bordered, compact table, and so on.
Similar to the tables you can also use these contextual classes to emphasize the rows
within a table. Here's an example of a table with emphasized rows, let's take a look:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Table with Accented Rows</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Bill</th>
<th>Payment Date</th>
<th>Payment Status</th>
</tr>
</thead>
<tbody>
<tr class="table-primary">
<td>1</td>
<td>Credit Card</td>
<td>04/07/2021</td>
<td>Waiting for statement</td>
</tr>
<tr class="table-secondary">
<td>2</td>
<td>Insurance</td>
<td>02/07/2021</td>
<td>Cancelled</td>
</tr>
<tr class="table-success">
<td>3</td>
<td>Water</td>
<td>01/07/2021</td>
<td>Paid</td>
</tr>
<tr class="table-info">
<td>4</td>
Bootstrap Tables 9
<td>Internet</td>
<td>05/07/2021</td>
<td>Change plan</td>
</tr>
<tr class="table-warning">
<td>5</td>
<td>Electricity</td>
<td>03/07/2021</td>
<td>Pending</td>
</tr>
<tr class="table-danger">
<td>6</td>
<td>Telephone</td>
<td>06/07/2021</td>
<td>Due</td>
</tr>
<tr class="table-light">
<td>7</td>
<td>Car Service</td>
<td>08/07/2021</td>
<td>Call in to confirm</td>
</tr>
<tr class="table-dark">
<td>8</td>
<td>Gas</td>
<td>06/07/2021</td>
<td>Payment failed</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
— The output of the above example will look something like this:
Bootstrap Tables 10
Creating Responsive Tables with Bootstrap
You can also create responsive tables to enable horizontal scrolling on small devices.
To make any table responsive just place it inside a <div> element and apply the .table-
responsive class on it. You can also specify when the table should have a scrollbar,
based on the viewport width (i.e. breakpoints), using the classes .table-responsive{-sm|-
md|-lg|-xl} .
Let's try out the following example to understand how it basically works:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Responsive Table</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
<style>
/* Custom style to make this example easy to understand */
table * {
Bootstrap Tables 11
white-space: nowrap;
}
</style>
</head>
<body>
<div class="m-4">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Biography</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Clark</td>
<td>Kent</td>
<td>clarkkent@mail.com</td>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</td>
</tr>
<tr>
<td>2</td>
<td>John</td>
<td>Carter</td>
<td>johncarter@mail.com</td>
<td>Vestibulum consectetur scelerisque bibendum scelerisque purus.</td
>
</tr>
<tr>
<td>3</td>
<td>Peter</td>
<td>Parker</td>
<td>peterparker@mail.com</td>
<td>Integer pulvinar leo id risus interdum vel metus dignissim.</td>
</tr>
</tbody>
</table>
</div>
<p class="mt-4"><strong>Note:</strong> Change the editor layout/orientation to see how
the responsive table works.</p>
</div>
</body>
</html>
Bootstrap Tables 12
Tip: Text inside the cells of <thead> are always vertically aligned to the bottom.
Whereas, text inside the cells of <tbody> inherit their alignment from <table> and are
vertically aligned to the top by default. Use the vertical-align classes to re-align text
where needed.
Bootstrap Tables 13
Bootstrap Lists
Creating Lists With Bootstrap
You can create three different types of HTML lists:
Unordered lists — A list of items in which the order does not explicitly matter. The
list items in unordered lists are marked with bullets, e.g. ⚬, ●, etc.
Ordered lists — A list of items in which the order does explicitly matter. The list
ⅵ
items in ordered lists are marked with numbers, e.g. 1, , etc.
See the tutorial on HTML lists, to learn more about the different lists types.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Unstyled List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<ul class="list-unstyled">
<li>Home</li>
<li>Products
<ul>
<li>Gadgets</li>
<li>Accessories</li>
</ul>
Bootstrap Lists 1
</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
</body>
</html>
— The output of the above example will look something like this:
Note: The .list-unstyled class removes the default list-style and left padding only
from the list items which are immediate children of the <ul> or <ol> element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Inline List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
Bootstrap Lists 2
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<ul class="list-inline">
<li class="list-inline-item">Home</li>
<li class="list-inline-item">Products</li>
<li class="list-inline-item">About Us</li>
<li class="list-inline-item">Contact</li>
</ul>
</div>
</body>
</html>
— The output of the above example will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap Horizontal Definitoin List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel
="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.j
s"></script>
</head>
<body>
<div class="m-4">
<dl class="row">
<dt class="col-sm-3">User Agent</dt>
<dd class="col-sm-9">An HTML user agent is any device that interprets HTML documen
ts.</dd>
<dt class="col-sm-3 text-truncate">Client-side Scripting</dt>
<dd class="col-sm-9">Client-side scripting generally refers to the category of com
puter programs on the web that are executed by the user's web browser.</dd>
<dt class="col-sm-3">Document Tree</dt>
Bootstrap Lists 3
<dd class="col-sm-9">The tree of elements encoded in the source document.</dd>
</dl>
</div>
</body>
</html>
— The output of the above example will look something like this:
Note: For longer definition terms, you can optionally apply the class .text-truncate on
the <dt> element to truncate the text with an ellipsis (…).
MORE ABOUT Bootstrap Lists
Bootstrap Lists 4
Bootstrap Forms
Introduction to Bootstrap Forms:
Forms play a crucial role in web development as they are used to gather user input and
enable various interactions on websites. Bootstrap Forms provide a set of CSS classes
and JavaScript components that make it easier to create forms that are consistent,
responsive, and visually appealing across different devices
Bootstrap Forms offer several features, including:
Pre-styled form elements such as input fields, checkboxes, radio buttons, select
dropdowns, etc.
Form validation and feedback classes to indicate errors and success states.
Inline and horizontal form layouts for flexible positioning of form controls.
Setting up Bootstrap:
To use Bootstrap Forms, you need to include the Bootstrap CSS and JavaScript files in
your HTML document. You have two options for including Bootstrap: downloading the
files and hosting them locally or using a content delivery network (CDN) to load them
remotely.
Here's an example of including Bootstrap files using CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/boots
trap.min.css">
<title>Bootstrap Forms</title>
</head>
<body>
<!-- Your form code goes here -->
Bootstrap Forms 1
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></sc
ript>
</body>
</html>
By including the CSS file within the <head> section and the JavaScript file before the
closing </body> tag, you can leverage the full power of Bootstrap's form features.
<form>
<div class="mb-3">
<label for="nameInput" class="form-label">Name</label>
<input type="text" class="form-control" id="nameInput">
</div>
<div class="mb-3">
<label for="emailInput" class="form-label">Email</label>
<input type="email" class="form-control" id="emailInput">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
In this example, we have two form controls: a text input for the name and an email input
for the email address. The form-control class is applied to the input elements to style
them according to Bootstrap's form style.
The form-label class is used to style the labels associated with the input elements. The
mb-3 class adds a margin-bottom spacing of 1.5rem (provided by Bootstrap's spacing
Bootstrap Forms 2
Form Controls and Input Types:
Bootstrap provides styling for various form controls and supports multiple input types.
Here are some examples:
Text Input:
<div class="mb-3">
<label for="textInput" class="form-label">Text Input</label>
<input type="text" class="form-control" id="textInput">
</div>
Password Input:
<div class="mb-3">
<label for="passwordInput" class="form-label">Password</label>
<input type="password" class="form-control" id="passwordInput">
</div>
Email Input:
<div class="mb-3">
<label for="emailInput" class="form-label">Email</label>
<input type="email" class="form-control" id="emailInput">
</div>
Textarea:
<div class="mb-3">
<label for="messageTextarea" class="form-label">Message</label>
<textarea class="form-control" id="messageTextarea" rows="3"></textarea>
</div>
Bootstrap Forms 3
Checkbox:
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="checkboxInput">
<label class="form-check-label" for="checkboxInput">
Check me out
</label>
</div>
Radio Buttons:
<div class="form-check">
<input class="form-check-input" type="radio" name="radioInput" id="radioInput1" checked>
<label class="form-check-label" for="radioInput1">
Option 1
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="radioInput" id="radioInput2">
<label class="form-check-label" for="radioInput2">
Option 2
</label>
</div>
Select Dropdown:
<div class="mb-3">
<label for="selectInput" class="form-label">Select</label>
<select class="form-select" id="selectInput">
<option selected>Select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</div>
These are just a few examples of form controls supported by Bootstrap. You can
explore the Bootstrap documentation to find more options and customize them as
Bootstrap Forms 4
needed.
Inline Forms:
Inline forms allow you to place form controls side by side without line breaks. This
layout is useful when you have a small number of form controls or want to save
space.
<form class="form-inline">
<div class="form-group mb-2">
<label for="inlineInput" class="sr-only">Username</label>
<input type="text" class="form-control" id="inlineInput" placeholder="Username">
</div>
<div class="form-group mx-sm-3 mb-2">
<label for="inlinePassword" class="sr-only">Password</label>
<input type="password" class="form-control" id="inlinePassword" placeholder="Passwor
d">
</div>
<button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>
In the above example, the form-inline class is added to the <form> element to enable
the inline form layout. The form-group class is used to wrap each form control, and the
mb-2 class adds margin-bottom spacing between the form controls.
Horizontal Forms:
Horizontal forms display form controls in a grid-like structure with labels aligned to
the left. This layout is useful for creating more complex forms with labels positioned
alongside the inputs.
Bootstrap Forms 5
<label for="horizontalPassword" class="form-label">Password</label>
<input type="password" class="form-control" id="horizontalPassword" placeholder="Passw
ord">
</div>
<div class="col-auto">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="horizontalCheckbox">
<label class="form-check-label" for="horizontalCheckbox">
Remember me
</label>
</div>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary mb-3">Submit</button>
</div>
</form>
In this example, the row class is added to the <form> element, and the col-auto class is
added to each form control to create a grid structure using Bootstrap's grid system.
Form Validation:
Bootstrap provides built-in form validation classes and JavaScript components to
enhance form validation. These features help ensure that users provide valid input and
receive feedback on any errors.
Validation States:
Bootstrap offers different validation states to indicate the success, warning, and
error states of form controls. These states are represented using the following
classes: is-valid , is-invalid , valid-feedback , and invalid-feedback .
<div class="mb-3">
<label for="validationInput" class="form-label">Email</label>
<input type="email" class="form-control is-invalid" id="validationInput" required>
<div class="invalid-feedback">
Please enter a valid email address.
</div>
</div>
Bootstrap Forms 6
In this example, the is-invalid class is applied to the input element to indicate an
invalid state. The invalid-feedback class is used to display an error message to the user.
Similarly, you can use the is-valid class and valid-feedback class to indicate a valid
state and provide positive feedback to the user.
To use JavaScript-based form validation, you need to include the Bootstrap JavaScript
file in your HTML, as shown in the setup section earlier.
<form>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" required>
<div id="passwordHelp" class="form-text">
Your password must be at least 8 characters long.
</div>
</div>
<div class="mb-3">
<label for="confirmPassword" class="form-label">Confirm Password</label>
<input type="password" class="form-control" id="confirmPassword" required>
<div id="confirmPasswordHelp" class="form-text">
Please make sure your passwords match.
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
// Example JavaScript validation
(function () {
'use strict';
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation');
Bootstrap Forms 7
}
form.classList.add('was-validated');
}, false);
});
})();
</script>
In this example, the form elements are wrapped in a <form> tag. The JavaScript code at
the bottom adds an event listener to the form's submit event. It checks if the form is
valid using the checkValidity() method. If the form is not valid, it prevents the default
form submission behavior and adds the was-validated class to the form, which triggers
the display of validation styles.
<form>
<div class="mb-3">
<label for="customInput" class="form-label">Custom Input</label>
<input type="text" class="form-control bg-primary text-white" id="customInput" placeho
lder="Enter custom input">
</div>
<div class="mb-3">
<label for="customSelect" class="form-label">Custom Select</label>
<select class="form-select bg-secondary text-white" id="customSelect">
<option selected>Select an option</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Bootstrap Forms 8
In this example, we have applied the bg-primary and text-white classes to the input
field and the bg-secondary and text-white classes to the select dropdown to customize
their background and text colors.
You can also create your own CSS classes and apply them to form elements to achieve
custom styling.
Conclusion:
Bootstrap Forms provide a comprehensive set of features and styling options to create
user-friendly and visually appealing forms. With Bootstrap, you can easily create
responsive forms, customize their appearance, and implement form validation. By
leveraging the pre-built CSS classes and JavaScript components provided by
Bootstrap, you can save time and effort in creating forms from scratch. Remember to
refer to the official Bootstrap documentation for detailed information and explore
additional form-related features offered by Bootstrap.
Bootstrap Forms 9
Bootstrap Buttons
1. Introduction to Bootstrap Buttons:
Buttons are essential elements in web development that allow users to interact with a
website or perform specific actions. Bootstrap Buttons provide a range of pre-styled
button components with different styles, sizes, and states, making it easier to create
visually appealing buttons in your web applications.
Bootstrap Buttons offer the following features:
Customization options to match the button styles with your website's design.
Now, let's dive into setting up Bootstrap and creating basic buttons.
2. Setting up Bootstrap:
To use Bootstrap Buttons, you need to include the Bootstrap CSS and JavaScript files in
your HTML document. You can either download the Bootstrap files and host them
locally or use a content delivery network (CDN) to load them remotely.
Here's an example of including Bootstrap files using CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/boots
trap.min.css">
<title>Bootstrap Buttons</title>
</head>
<body>
<!-- Your button code goes here -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></sc
Bootstrap Buttons 1
ript>
</body>
</html>
Make sure to include the CSS file within the <head> section and the JavaScript file
before the closing </body> tag to utilize the full capabilities of Bootstrap's button
features.
3. Basic Button Structure:
The basic structure of a Bootstrap button consists of an <a> or <button> element with
the appropriate Bootstrap classes to define the button style. You can also add additional
classes to customize the appearance and behavior of the button.
Here's an example of a basic Bootstrap button:
In this example, the btn class is applied to the <button> element, and the btn-primary
class is used to style the button with the primary color defined by Bootstrap. The text
"Click me" represents the button label.
Both the <button> and <a> elements can be styled as buttons using Bootstrap classes.
4. Button Styles:
Bootstrap provides several button styles to choose from. Each style has a distinct visual
appearance and color scheme. Here are some examples:
Primary Button:
Bootstrap Buttons 2
Secondary Button:
Success Button:
Danger Button:
Warning Button:
Info Button:
Light Button:
Dark Button:
Bootstrap Buttons 3
<button class="btn btn-dark">Dark</button>
In these examples, the respective classes ( btn-primary , btn-secondary , etc.) are applied
to the <button> element to set the button style.
5. Button Sizes:
Bootstrap Buttons can be styled with different sizes to fit various design requirements.
Bootstrap offers the following size classes for buttons:
Small Button:
Default Button:
(Default size buttons don't require any additional size class.)
Large Button:
By applying the respective size classes ( btn-sm , btn-lg ) along with the button style
classes, you can adjust the button size accordingly.
6. Button States and Interactions:
Bootstrap Buttons can have different states and interactions to provide visual feedback
and control the behavior of the button. Bootstrap offers the following states and
interactions:
Active State:
The active state represents a pressed or clicked button. You can add the active
Bootstrap Buttons 4
<button class="btn btn-primary active">Active Button</button>
Disabled State:
The disabled state prevents the button from being clicked or interacted with. You
can add the disabled class to a button to indicate the disabled state.
In the above example, both the disabled class and the disabled attribute are applied to
the button. The disabled attribute is used for better accessibility.
Toggle Buttons:
Bootstrap also provides the ability to create toggle buttons using the data-bs-toggle
attribute and the btn-toggle class. This allows you to create buttons that toggle
between different states or show/hide content.
Bootstrap Buttons 5
Additionally, Bootstrap provides the ability to group buttons together using the btn-group
class. This allows you to create button groups, dropdown menus, and toolbars.
Here's an example of a button group:
In this example, the <div> element contains multiple buttons with the btn class. The
btn-group class is added to the container <div> to create the button group. The
role="group" attribute and the aria-label attribute are used for better accessibility.
In this example, the btn-rounded class is added to the button to give it rounded corners.
You can use other utility classes to modify the button's appearance, such as btn-
outline-* for an outlined style or btn-* for a gradient background.
You can also create your own CSS classes and apply them to buttons to achieve
custom styling.
9. Conclusion:
Bootstrap Buttons provide a convenient way to create visually appealing and interactive
buttons in your web applications. With a wide range of pre-styled button styles, sizes,
and customization options, Bootstrap allows you to create buttons that match your
website's design and provide a great user experience. By following the examples and
guidelines outlined in this explanation, you can easily implement Bootstrap Buttons in
your projects. Remember to refer to the official Bootstrap documentation for more
Bootstrap Buttons 6
detailed information and explore additional button-related features offered by
Bootstrap.
Bootstrap Buttons 7
Bootstrap Images
Bootstrap provides a variety of classes and components to easily incorporate images
into your web applications. Whether you need to display responsive images, create
image thumbnails, or apply different styling options, Bootstrap has got you covered. In
this explanation, we'll explore the various features and options available for working with
images in Bootstrap.
Setting up Bootstrap
Before we dive into Bootstrap's image features, let's ensure that you have Bootstrap
properly set up in your project. You can include Bootstrap in your project by
downloading the CSS and JavaScript files and hosting them locally, or you can use a
Content Delivery Network (CDN) to load Bootstrap files remotely. Here's an example of
including Bootstrap using a CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/boots
trap.min.css">
<title>Bootstrap Images</title>
</head>
<body>
<!-- Your image code goes here -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></sc
ript>
</body>
</html>
Ensure that you include the CSS file within the <head> section and the JavaScript file
just before the closing </body> tag to utilize the full capabilities of Bootstrap's image
features.
Responsive Images
Bootstrap Images 1
Bootstrap offers a convenient way to make your images responsive, ensuring they
adjust properly based on the device screen size. The img-fluid class allows images to
automatically scale with the container. Here's an example:
In this example, the img-fluid class is applied to the <img> tag. This ensures that the
image scales appropriately within its parent container.
Image Thumbnails
Bootstrap provides a class, img-thumbnail , to create image thumbnails. Thumbnails are
smaller versions of an image, often used in image galleries or as previews. Here's an
example:
In this example, the img-thumbnail class is applied to the <img> tag, resulting in a
bordered and rounded image thumbnail.
Image Shapes
You can also modify the shape of images using Bootstrap's image shape classes. The
available shape classes are rounded , rounded-circle , and rounded-pill . Here's how you
can apply them:
Bootstrap Images 2
In these examples, the respective shape classes are added to the <img> tag to create
different shapes for the images.
Image Alignment
You can easily align images horizontally within their parent container using Bootstrap's
flexbox utilities. The available alignment classes are float-start and float-end . Here's
an example:
In these examples, the alignment classes are added to the <img> tag to align the
images to the left and right, respectively.
Image Overlays
Bootstrap allows you to add text overlays on top of images using the position-relative
class along with the position-absolute class. This is particularly useful for creating image
captions or adding additional information to an image. Here's an example:
<div class="position-relative">
<img src="path/to/image.jpg" alt="Image" class="img-fluid">
<div class="position-absolute top-0 start-0">
<h3 class="text-white">Image Caption</h3>
</div>
</div>
In this example, a <div> container with the position-relative class wraps the image and
the text overlay. The <img> tag with the img-fluid class represents the image itself. The
text overlay is added as a <div> with the position-absolute top-0 start-0 classes, and a
heading element ( <h3> in this case) is used to display the caption text.
Bootstrap Images 3
Image Shapes and Captions
Bootstrap provides a special component, called the figure component, to combine
images with optional captions. The figure component encapsulates the image and the
caption, providing proper semantic structure. Here's an example:
<figure class="figure">
<img src="path/to/image.jpg" alt="Image" class="figure-img img-fluid rounded">
<figcaption class="figure-caption">Image Caption</figcaption>
</figure>
In this example, the <figure> element with the figure class is used as a wrapper for the
image and the caption. The <img> tag has the figure-img and img-fluid classes to
make the image responsive and fit within the container. The <figcaption> element with
the figure-caption class represents the image caption.
<div class="row">
<div class="col-sm-6 col-md-4 col-lg-3">
<img src="path/to/image1.jpg" alt="Image 1" class="img-thumbnail">
</div>
<div class="col-sm-6 col-md-4 col-lg-3">
<img src="path/to/image2.jpg" alt="Image 2" class="img-thumbnail">
</div>
<!-- Add more images as needed -->
</div>
In this example, the <div> elements with the col-* classes are used to create a
responsive grid layout. The <img> tags with the img-thumbnail class represent the
individual images within the grid.
Conclusion
Bootstrap Images 4
Bootstrap provides a comprehensive set of classes and components to work with
images and enhance their appearance in your web applications. Whether you need to
make images responsive, create thumbnails, customize image shapes, or apply image
overlays, Bootstrap has the necessary features to simplify the process. By following the
examples and guidelines presented in this explanation, you can easily leverage
Bootstrap's image capabilities and create visually appealing and responsive image
content in your projects.
Bootstrap Images 5
Bootstrap Cards
Bootstrap Cards are flexible and responsive content containers that can be used to
display various types of content in a visually appealing manner. Cards are a popular
component in web design and are commonly used to present information, images, or
media in a structured and organized format. In this explanation, we'll explore the
features and options available for working with Bootstrap Cards.
Setting up Bootstrap
Before we dive into Bootstrap's card features, let's ensure that you have Bootstrap
properly set up in your project. You can include Bootstrap in your project by
downloading the CSS and JavaScript files and hosting them locally, or you can use a
Content Delivery Network (CDN) to load Bootstrap files remotely. Here's an example of
including Bootstrap using a CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/boots
trap.min.css">
<title>Bootstrap Cards</title>
</head>
<body>
<!-- Your card code goes here -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></sc
ript>
</body>
</html>
Ensure that you include the CSS file within the <head> section and the JavaScript file
just before the closing </body> tag to utilize the full capabilities of Bootstrap's card
features.
Bootstrap Cards 1
A Bootstrap Card consists of several elements that work together to create the desired
content presentation. The basic structure of a card includes a <div> container with the
class card . Inside the card container, you can add header, body, footer, and other
components as needed. Here's an example of a basic card structure:
<div class="card">
<!-- Card content goes here -->
</div>
You can add additional classes and components to enhance the appearance and
functionality of the card.
<div class="card">
<div class="card-header">
Card Header
</div>
<div class="card-body">
Card Content
</div>
</div>
In this example, the <div> element with the class card-header represents the card
header.
To add a footer to a card, use the card-footer class:
<div class="card">
<div class="card-body">
Card Content
</div>
<div class="card-footer">
Card Footer
</div>
Bootstrap Cards 2
</div>
In this example, the <div> element with the class card-footer represents the card
footer.
<div class="card">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<h6 class="card-subtitle">Card Subtitle</h6>
<p class="card-text">Card Content</p>
</div>
</div>
In this example, the <h5> element with the class card-title represents the card title,
and the <h6> element with the class card-subtitle represents the card subtitle.
<div class="card">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Card Content</p>
</div>
</div>
In this example, the <p> element with the class card-text represents the card content.
You can also include links within card content. Bootstrap provides the card-link class to
style links in a card. Here's an example:
Bootstrap Cards 3
<div class="card">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Card Content</p>
<a href="#" class="card-link">Read More</a>
</div>
</div>
In this example, the <a> element with the class card-link represents the link within the
card content.
Card Images
Bootstrap Cards can also include images. You can add an image to a card using the
card-img-top class. Here's an example:
<div class="card">
<img src="path/to/image.jpg" alt="Card Image" class="card-img-top">
<div class="card-body">
<h5 class="card-title">Card Title</h5>
<p class="card-text">Card Content</p>
</div>
</div>
In this example, the <img> tag with the class card-img-top represents the card image.
The src attribute specifies the path to the image, and the alt attribute provides
alternative text for screen readers and if the image fails to load.
Card Styles
Bootstrap Cards provide various styles to match different design requirements. You can
use the bg-* classes to apply different background colors to the card. For example:
Bootstrap Cards 4
In this example, the bg-primary class is added to the card to give it a primary
background color, and the text-white class is used to set the text color to white.
Additionally, you can use the border-* classes to add borders of different styles and
colors to the card. For example:
In this example, the border-primary class is added to the card to give it a primary border
color.
Card Groups
Bootstrap allows you to group multiple cards together using the card-group class. This is
useful when you want to display related cards in a visually cohesive manner. Here's an
example:
<div class="card-group">
<div class="card">
Card 1
</div>
<div class="card">
Card 2
</div>
<div class="card">
Card 3
</div>
</div>
In this example, the card-group class is added to the container <div> , and individual
cards are placed inside it.
Conclusion
Bootstrap Cards provide a versatile and powerful way to present content in an
organized and visually appealing manner. Whether you need to display information,
Bootstrap Cards 5
images, or media, Bootstrap Cards offer a flexible and responsive solution. By following
the examples and guidelines presented in this explanation, you can effectively utilize
Bootstrap's card component to create attractive and functional content containers in
your web applications
Bootstrap Cards 6
Bootstrap Media Objects
Bootstrap provides a useful component called "Media Objects" that allows you to
display images, videos, or other media content alongside textual information. Media
objects are commonly used for creating news feeds, blog posts, and other content
layouts that combine media with descriptive text. In this explanation, we'll explore the
features and options available for working with Bootstrap Media Objects.
Setting up Bootstrap
Before we dive into Bootstrap's media object features, let's ensure that you have
Bootstrap properly set up in your project. You can include Bootstrap in your project by
downloading the CSS and JavaScript files and hosting them locally, or you can use a
Content Delivery Network (CDN) to load Bootstrap files remotely. Here's an example of
including Bootstrap using a CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/boots
trap.min.css">
<title>Bootstrap Media Objects</title>
</head>
<body>
<!-- Your media object code goes here -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></sc
ript>
</body>
</html>
Make sure to include the CSS file within the <head> section and the JavaScript file just
before the closing </body> tag to utilize the full capabilities of Bootstrap's media object
features.
<div class="media">
<img src="path/to/image.jpg" alt="Media Object" class="mr-3">
<div class="media-body">
<h5 class="mt-0">Media Object Title</h5>
<p>Media Object Text</p>
</div>
</div>
In this example, the <img> tag represents the media component with the src attribute
specifying the path to the image. The alt attribute provides alternative text for screen
readers and if the image fails to load. The mr-3 class is used to apply margin to the
right side of the media component. The textual content is wrapped within a <div> with
the class media-body . The <h5> tag represents the title of the media object, and the <p>
tag represents the textual content.
<div class="media">
<img src="path/to/image.jpg" alt="Media Object" class="mr-3 float-right">
<div class="media-body">
<h5 class="mt-0">Media Object Title</h5>
<p>Media Object Text</p>
</div>
</div>
In this example, the float-right class is added to the <img> tag to align the media
component to the right.
<div class="media">
<img src="path/to/image1.jpg" alt="Media Object 1" class="mr-3">
<div class="media-body">
<h5 class="mt-0">Media Object Title 1</h5>
<p>Media Object Text 1</p>
In this example, a parent media object is created, and inside it, a nested media object is
added. The nested media object follows the same structure as the parent media object.
<div class="media">
<img src="path/to/image.jpg" alt="Media Object" class="mr-3 media-lg">
<div class="media-body">
<h5 class="mt-0">Media Object Title</h5>
<p>Media Object Text</p>
</div>
</div>
<div class="media">
<img src="path/to/image.jpg" alt="Media Object" class="mr-3 align-self-start">
<div class="media-body">
<h5 class="mt-0">Media Object Title</h5>
<p>Media Object Text</p>
</div>
</div>
In this example, the align-self-start class is added to the <img> tag to align the media
component to the top of the media object.
Conclusion
Bootstrap Media Objects provide a convenient way to combine media components with
textual content in a structured and visually appealing manner. By following the examples
and guidelines presented in this explanation, you can effectively utilize Bootstrap's
media object component to create engaging and informative layouts in your web
applications.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/boo
tstrap-icons.css">
<title>Bootstrap Icons</title>
</head>
<body>
<!-- Your icon code goes here -->
</body>
</html>
Make sure to include the CSS file within the <head> section of your HTML file.
Bootstrap Icons 1
In this example, the bi bi-heart class is added to the <i> tag to display the heart icon.
The bi class is required for all Bootstrap Icons, and the specific icon class ( bi-heart in
this case) represents the desired icon.
Icon Sizes
Bootstrap Icons can be displayed in different sizes. You can control the size of an icon
by adding the bi-* class to the <i> tag. The available size options are sm , lg , 1x ,
2x , 3x , 4x , 5x , 10x , and auto . Here are some examples:
In these examples, the bi-sm class is used to set the icon size to small, the bi-lg class
is used to set the icon size to large, and the bi-2x class is used to set the icon size to
2x.
Icon Colors
You can change the color of an icon by adding a color class to the <i> tag. Bootstrap
Icons include several color classes that you can use to customize the icon's
appearance. Here's an example:
In this example, the text-primary class is added to the <i> tag to set the icon color to
the primary color defined in Bootstrap's color palette. Similarly, the text-danger class
sets the icon color to the danger color.
Bootstrap Icons 2
bi-rotate-* : Rotates the icon. The available options are 90 , 180 , and 270 .
bi-flip-* : Flips the icon horizontally or vertically. The available options are
horizontal and vertical .
In this example, the icon is rotated 90 degrees, flipped horizontally, and has a spinning
animation.
Icon Accessibility
When using Bootstrap Icons, it's important to ensure that the icons are accessible to all
users, including those who rely on screen readers. To improve accessibility, you should
provide appropriate alternative text for the icons using the aria-label attribute. Here's
an example:
In this example, the aria-label attribute is added to the <i> tag to provide a descriptive
label for the heart icon.
Conclusion
Bootstrap Icons provide a vast collection of scalable vector icons that can enhance the
visual appeal and usability of your web projects. By following the examples and
guidelines presented in this explanation, you can effectively utilize Bootstrap Icons to
add stylish and meaningful icons to your web applications.
Bootstrap Icons 3
Bootstrap Navbar
The Bootstrap Navbar component is a versatile and customizable navigation bar that
helps you create responsive and user-friendly navigation menus for your web
applications. It offers a wide range of features, including responsive behavior, dropdown
menus, collapsible behavior, and various styling options. In this explanation, we'll
explore the features and options available for working with Bootstrap Navbar.
Setting up Bootstrap
Before we dive into the details of Bootstrap Navbar, let's make sure you have Bootstrap
properly set up in your project. You can include Bootstrap in your project by
downloading the CSS and JavaScript files and hosting them locally, or you can use a
Content Delivery Network (CDN) to load Bootstrap files remotely. Here's an example of
including Bootstrap using a CDN:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/boots
trap.min.css">
<title>Bootstrap Navbar</title>
</head>
<body>
<!-- Your navbar code goes here -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></sc
ript>
</body>
</html>
Make sure to include the CSS file within the <head> section and the JavaScript file just
before the closing </body> tag to utilize the full capabilities of Bootstrap Navbar.
Bootstrap Navbar 1
other components. Here's an example of a basic navbar structure:
In this example, the navbar class is added to the <nav> element to define it as a navbar
component. The navbar-expand-lg class ensures that the navbar expands to occupy the
full width on larger screens. The navbar-light and bg-light classes are used to set the
navbar's light background color.
The <a> tags inside the navbar represent the navigation links. The navbar-brand class is
added to the logo or brand element. The <button> element with the navbar-toggler class
is used to toggle the collapse behavior of the navbar on smaller screens. The data-bs-
toggle and data-bs-target attributes are used to specify the target collapsible element.
The collapsible content is placed inside a <div> element with the navbar-collapse class.
The collapse class is used to specify the collapsible behavior, and the navbar-nav class
is added to the <ul> element to define it as a navbar navigation component.
Dropdown Menus
Bootstrap Navbar allows you to include dropdown menus in your navigation. Dropdown
menus are useful when you have multiple sub-level navigation items. Here's an
Bootstrap Navbar 2
example of a navbar with a dropdown menu:
In this example, the third navigation item "Services" has a dropdown menu. The parent
<li> element has the dropdown class, and the child <a> element has the dropdown-
toggle class. The data-bs-toggle attribute is used to specify the dropdown behavior, and
tag inside.
Bootstrap Navbar 3
Bootstrap Navbar provides different color schemes to match your project's design. By
adding color classes, you can customize the navbar's appearance. Here are some
commonly used color classes:
You can combine these classes to create various color schemes for your navbar. For
example:
In this example, the navbar-light and bg-light classes are used to create a light-
colored navbar.
Responsive Behavior
Bootstrap Navbar is designed to be responsive and adapt to different screen sizes. On
smaller screens, the navbar collapses into a hamburger menu icon, which can be
expanded to reveal the navigation links. This behavior is achieved using the navbar-
toggler class and the collapse class.
By default, the navbar collapses at the lg breakpoint. You can control the collapsing
behavior by changing the value of the navbar-expand-* class. Here are the available
options:
For example, if you want the navbar to collapse at the medium breakpoint, you can use
the following class:
Bootstrap Navbar 4
<nav class="navbar navbar-expand-md navbar-light bg-light">
<!-- Navbar content -->
</nav>
Sticky Navbar: You can make the navbar stick to the top of the page by adding the
fixed-top class to the <nav> element.
Fluid Navbar: By default, the navbar is contained within a container element. If you
want the navbar to span the full width of the viewport, you can add the container-
fluid class to the <nav> element.
Navbar Variations: Bootstrap Navbar offers different variations, such as the dark
navbar ( navbar-dark ), the sticky top navbar ( sticky-top ), and the transparent navbar
( navbar-transparent ). These classes can be combined to achieve the desired effect.
Navbar Placement: The navbar can be placed at different positions in your layout,
such as at the top ( fixed-top ), at the bottom ( fixed-bottom ), or within a specific
container.
Conclusion
Bootstrap Navbar is a powerful component that allows you to create responsive and
customizable navigation menus for your web applications. By following the examples
and guidelines presented in this explanation, you can effectively utilize Bootstrap
Navbar to create visually appealing and user-friendly navigation experiences.
Bootstrap Navbar 5
Bootstrap Modals
Bootstrap Modals provide a flexible and interactive way to display content in a layered
window that floats above the rest of the page. Modals are commonly used for displaying
additional information, forms, images, or interactive components without navigating
away from the current page. In this explanation, we'll explore the features and options
available for working with Bootstrap Modals.
Bootstrap Modals 1
In this example, the trigger element is a button with the btn btn-primary classes. The
data-bs-toggle attribute is used to specify the behavior of the trigger element, and the
The modal container is represented by a <div> element with the modal class and a
unique ID ( myModal in this case). The tabindex="-1" attribute ensures that the modal can
be focused. The aria-labelledby attribute specifies the ID of the element that labels the
modal, which in this case is the <h5> element with the ID exampleModalLabel .
Inside the modal container, there are three main sections: the modal header, modal
body, and modal footer. The modal header typically contains a title and a close button.
The modal body holds the main content of the modal, and the modal footer contains any
additional buttons or actions.
To close the modal, you can use the data-bs-dismiss="modal" attribute on a button or a
link within the modal. In this example, both the close button in the modal header and the
"Close" button in the modal footer have this attribute.
Sizes: You can control the size of the modal by adding the modal-dialog-centered
class to the modal dialog container and one of the following size classes: modal-
Backdrop: The modal backdrop is the overlay behind the modal that provides a
dimming effect to the rest of the page. By default, the modal is closed when the
backdrop is clicked. You can control this behavior by adding the data-bs-backdrop
attribute to the trigger element.
Keyboard Interaction: By default, pressing the Escape key ( Esc ) will close the
modal. You can disable this behavior by adding the data-bs-keyboard attribute to the
trigger element with a value of "false" .
Bootstrap Modals 2
Events: Bootstrap provides several events that you can use to trigger custom
functionality when modals are shown, hidden, or transitioned.
shown.bs.modal : This event is fired when the modal is fully shown (after CSS
transitions have completed).
hidden.bs.modal: This event is fired when the modal is fully hidden (after CSS
transitions have completed).
You can attach event handlers to these events using JavaScript to perform custom
actions based on the modal's lifecycle.
Forms: You can place forms inside a modal to collect user input or trigger specific
actions. The form can include input fields, checkboxes, radio buttons, and buttons
for submitting or canceling the form.
Images and Media: Modals are often used to display images or media content in a
larger view. You can place an <img> tag or embed media content, such as videos or
maps, within the modal body.
Tabs and Accordions: Modals can also contain tabs or accordions to organize and
present information in a structured manner. You can use Bootstrap's Tab and
Collapse components inside the modal to achieve this.
Dynamic Content: Modals can be populated with dynamic content from an external
source or loaded dynamically using JavaScript. This allows you to fetch data from a
server, generate content on the fly, or load remote HTML files.
Conclusion
Bootstrap Modals provide a powerful and flexible way to display content in an interactive
overlay. By following the examples and guidelines presented in this explanation, you
Bootstrap Modals 3
can effectively utilize Bootstrap Modals to create visually appealing and interactive
components in your web applications.
Bootstrap Modals 4
Bootstrap Dropdowns
Bootstrap Dropdowns are interactive components that allow users to select options or
trigger additional actions by clicking or hovering over a button or a link. Dropdowns
provide a convenient way to display a list of choices or actions in a compact and
organized manner. In this explanation, we'll explore the features and options available
for working with Bootstrap Dropdowns.
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton"
data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown Button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">Item 1</a>
<a class="dropdown-item" href="#">Item 2</a>
<a class="dropdown-item" href="#">Item 3</a>
</div>
</div>
In this example, the trigger element is a button with the btn btn-secondary dropdown-toggle
classes. The data-bs-toggle attribute is used to specify the behavior of the trigger
element, and the data-bs-target attribute is used to specify the ID of the dropdown
menu. The aria-haspopup and aria-expanded attributes are used for accessibility
purposes.
The dropdown menu is represented by a <div> element with the dropdown-menu class.
The aria-labelledby attribute specifies the ID of the element that labels the dropdown,
which in this case is the trigger button with the ID dropdownMenuButton .
Bootstrap Dropdowns 1
Inside the dropdown menu, there are multiple <a> elements with the dropdown-item
class, representing the individual items or actions in the dropdown. You can customize
the dropdown menu by adding different classes, styles, or additional HTML elements to
each dropdown item.
Dropdown Placement: By default, the dropdown menu appears below the trigger
element. You can change the placement by adding the dropdown-menu-start or
dropdown-menu-end classes to the <div> element of the dropdown menu. These
classes position the dropdown menu to the start or end, respectively, of the trigger
element.
Dropdown Size: You can control the size of the dropdown menu by adding the
dropdown-menu-sm or dropdown-menu-lg classes to the <div> element of the dropdown
menu. These classes adjust the size of the dropdown menu accordingly.
Dropdown Dividers: You can add dividers between dropdown items by adding a
<div> element with the dropdown-divider class inside the dropdown menu.
Dropdown Headers: You can add headers to group related items within the
dropdown menu. Use a <h6> element with the dropdown-header class inside the
dropdown menu to create a header.
Dropdown Forms: Dropdowns can contain form elements such as input fields,
checkboxes, or radio buttons. You can wrap form elements in a <form> tag within
the dropdown menu.
Dropdown Colors: You can customize the colors of the dropdown by using
Bootstrap's color classes. For example, you can add the bg-primary class to the
<div> element of the dropdown menu to apply the primary color to the dropdown.
Bootstrap Dropdowns 2
Click Trigger: The dropdown menu is opened and closed when the trigger element
is clicked. Use the data-bs-toggle="dropdown" attribute to specify the click trigger.
Hover Trigger: The dropdown menu is opened when the trigger element is hovered
over and closed when the mouse moves away. Use the data-bs-toggle="dropdown"
attribute and the data-bs-hover="dropdown" attribute to specify the hover trigger.
Split Dropdown: Bootstrap provides a split dropdown variation where the trigger
element is split into two parts: a main action button and a separate dropdown toggle
button. This allows the main action button to perform a separate action while the
dropdown toggle button controls the dropdown menu. To create a split dropdown,
use the btn-group class and the dropdown-toggle-split class on the main action
button.
Dropdowns in Navbar
Dropdowns are commonly used in navigation menus (navbars) to display additional
options or navigation links. Bootstrap provides specific classes to incorporate
dropdowns into the navbar. Here's an example of a dropdown within a navbar:
Bootstrap Dropdowns 3
In this example, the dropdown is placed within a navbar. The trigger element is an
anchor <a> tag with the nav-link class. The data-bs-toggle attribute is used to specify
the click trigger, and the data-bs-target attribute is not required for the dropdown within
the navbar.
The dropdown menu is contained within a <div> element with the dropdown-menu class.
The aria-labelledby attribute is used to associate the dropdown menu with the trigger
element.
Conclusion
Bootstrap Dropdowns provide a versatile and interactive way to present options and
actions to users. By following the examples and guidelines presented in this
explanation, you can effectively utilize Bootstrap Dropdowns to create dynamic and
user-friendly navigation menus and interactive components in your web applications.
Bootstrap Dropdowns 4
Bootstrap Alerts
Bootstrap Alerts are components used to display important messages or notifications to
users. They provide a visually appealing and attention-grabbing way to convey
information. Alerts can be used to show success messages, error messages, warnings,
or general informational messages. In this explanation, we'll explore the features and
options available for working with Bootstrap Alerts.
In this example, the alert is represented by a <div> element with the alert class and
the alert-primary class. The alert-primary class specifies the color scheme for the alert,
in this case, a primary color.
Inside the alert container, you can place any text or HTML content that you want to
display as the alert message.
The close button is represented by a <button> element with the btn-close class. The
data-bs-dismiss="alert" attribute is used to specify that the button is responsible for
dismissing the alert. The aria-label attribute provides an accessible label for the close
button.
Bootstrap Alerts 1
classes:
You can choose the appropriate color class based on the type of message you want to
convey. Simply replace alert-primary in the example above with the desired color class.
Dismissing Alerts
Bootstrap Alerts can be dismissed or closed by users. The close button provides a
convenient way to dismiss the alert. When the close button is clicked, the alert is hidden
or removed from the page. The data-bs-dismiss="alert" attribute is used to specify the
dismiss behavior.
If you want to dismiss the alert programmatically using JavaScript, you can use the
alert('close') method. For example:
Alert Links: You can include links within the alert to provide additional information
or actions related to the message. Simply wrap the link text in an <a> tag within the
alert container.
Alert Icons: You can include icons within the alert to visually represent the type of
message being displayed. Bootstrap does not provide built-in icons, but you can
Bootstrap Alerts 2
use popular icon libraries like Font Awesome or Bootstrap Icons to add icons to
alerts.
Alert Dismissible: By default, alerts are dismissible. However, if you want to create
non-dismissible alerts that cannot be closed by users, you can omit the close button
from the alert structure.
Closing Thoughts
Bootstrap Alerts are useful components for displaying important messages or
notifications to users. By following the examples and guidelines presented in this
explanation, you can effectively utilize Bootstrap Alerts to provide relevant information
and enhance the user experience in your web applications.
Bootstrap Alerts 3
Bootstrap Carousel
Bootstrap Carousel is a slideshow component that allows you to showcase a series of
images, content, or media in a rotating fashion. It provides an interactive and visually
appealing way to display multiple items within a limited space. In this explanation, we'll
explore the features and options available for working with Bootstrap Carousel.
Bootstrap Carousel 1
-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
In this example, the carousel is represented by a <div> element with the carousel class.
The id attribute is used to uniquely identify the carousel.
Inside the carousel container, there's a <div> element with the carousel-inner class.
This element holds the individual slide items. Each slide is represented by a <div>
element with the carousel-item class. The first slide has the additional active class,
indicating that it should be shown initially.
Inside each slide item, you can place any content you want, such as images, text, or
other HTML elements. In the example, we have an <img> tag for displaying an image,
and a <div> element with the carousel-caption class for adding a caption to each slide.
The navigation controls are represented by <button> elements with the carousel-control-
prev and carousel-control-next classes. The data-bs-target attribute is used to specify
the ID of the carousel, and the data-bs-slide attribute is used to specify the direction of
navigation.
Autoplay: You can enable the carousel to automatically transition between slides
by adding the data-bs-ride="carousel" attribute to the carousel container. This starts
the carousel as soon as the page loads.
Carousel Indicators: You can add indicators at the bottom of the carousel to show
the current slide. To do this, add a <ol> element with the carousel-indicators class
just before the slide items. Inside the <ol> , add <li> elements with the data-bs-
target attribute set to the ID of the carousel and the data-bs-slide-to attribute set to
Carousel Controls: In addition to the default navigation buttons, you can add
custom controls to navigate the carousel. To do this, add any HTML element with
Bootstrap Carousel 2
the data-bs-target and data-bs-slide attributes set to the ID of the carousel and the
desired slide action, respectively.
Carousel Interval: You can control the time interval between slide transitions by
adding the data-bs-interval attribute to the carousel container. The value is
specified in milliseconds, for example, data-bs-interval="5000" for a 5-second
interval.
Carousel Fade Effect: By default, the carousel slides horizontally. However, you
can change the transition effect to a fade effect by adding the carousel-fade class to
the carousel container.
Closing Thoughts
Bootstrap Carousel is a powerful component for creating interactive and visually
appealing slideshows on your website. By following the examples and guidelines
presented in this explanation, you can effectively utilize Bootstrap Carousel to
showcase images, content, or media in an engaging manner
Bootstrap Carousel 3
Bootstrap 5 Examples
Bootstrap Grid System
Bootstrap two column grid layouts for tablets and desktops
Bootstrap three column grid layouts for tablets in landscape mode and desktops
Bootstrap Typography
Bootstrap headings
Bootstrap 5 Examples 1
Bootstrap text transformation
Bootstrap Tables
Creating simple tables with Bootstrap
Bootstrap Lists
Creating lists with Bootstrap
Bootstrap 5 Examples 2
Bootstrap list groups
Bootstrap Forms
Creating vertical form layouts with Bootstrap
Bootstrap 5 Examples 3
Bootstrap form validation
Specifying min, max and step attributes for Bootstrap custom range
Bootstrap Buttons
Bootstrap 5 Examples 4
Creating buttons with Bootstrap
Creating disabled Bootstrap buttons using the input and button element
Bootstrap Images
Making thumbnails, rounded corner and circular images with Bootstrap
Bootstrap 5 Examples 5
Making responsive videos with Bootstrap
Bootstrap Cards
Creating cards with Bootstrap
Bootstrap Icons
Bootstrap 5 Examples 6
Including Bootstrap icons in a web page
Bootstrap Navs
Creating basic nav with Bootstrap
Bootstrap Navbar
Creating navbar with Bootstrap
Bootstrap 5 Examples 7
Adding dropdown menus to navbar in Bootstrap
Bootstrap Accordion
Creating accordion with Bootstrap
Bootstrap Badges
Creating badges with Bootstrap
Bootstrap 5 Examples 8
Creating pill badges with Bootstrap
Bootstrap Spinners
Creating border spinners with Bootstrap
Bootstrap Jumbotron
Bootstrap 5 Examples 9
Creating jumbotron to showcase content in Bootstrap
Bootstrap Modals
Creating modals with Bootstrap
Changing the Bootstrap modal content based on the trigger button via JavaScript
Prevent Bootstrap modal from disappearing on click outside via data attributes
Prevent Bootstrap modal from hiding on click of the dark area via JavaScript
Prevent Bootstrap modal from hiding on press of the escape key via JavaScript
Display a message when Bootstrap modal window has been completely closed
Bootstrap Dropdowns
Bootstrap 5 Examples 10
Creating dropdown menu in Bootstrap
Bootstrap Tabs
Creating a basic tabs with Bootstrap
Bootstrap 5 Examples 11
Bootstrap show() tab method
Get the names of active tab and previous tab in Bootstrap via JavaScript
Bootstrap Tooltips
Creating tooltips with Bootstrap
Display a message when Bootstrap tooltip fade out transition has been completed
Bootstrap 5 Examples 12
Bootstrap Popovers
Creating popovers with Bootstrap
Display a message when Bootstrap popover fade out transition has been completed
Creating primary, secondary, dark, and light alert messages with Bootstrap
Bootstrap 5 Examples 13
Adding icons to Bootstrap alerts
Bootstrap Collapse
Expanding and collapsing elements via data attributes
Bootstrap Carousel
Creating carousels with Bootstrap
Bootstrap 5 Examples 14
Removing auto-sliding from Bootstrap carousel via JavaScript
Display a message when sliding of a Bootstrap carousel item has been completed
Bootstrap Typeahead
Creating Twitter typeahead with local dataset
Bootstrap ScrollSpy
Creating scrollspy with Bootstrap
Bootstrap 5 Examples 15
Get the nav item currently highlighted by Bootstrap scrollspy via JavaScript
Bootstrap Toasts
Creating toasts with Bootstrap
Bootstrap 5 Examples 16
JavaScript
What is JavaScript?
JavaScript is a programming language initially designed to interact with elements of web
pages. In web browsers, JavaScript consists of three main parts:
The Document Object Model (DOM) provides interfaces for interacting with
elements on web pages
The Browser Object Model (BOM) provides the browser API for interacting with the
web browser.
JavaScript allows you to add interactivity to a web page. Typically, you use JavaScript
with HTML and CSS to enhance a web page’s functionality, such as validating forms,
creating interactive maps, and displaying animated charts.
When a web page is loaded, i.e., after downloading HTML and CSS, the web browser's
JavaScript engine executes the JavaScript code. The JavaScript code then modifies the
HTML and CSS to update the user interface dynamically.
The JavaScript engine is a program that executes JavaScript code. In the beginning,
JavaScript engines were implemented as interpreters.
JavaScript 1
However, modern JavaScript engines are typically implemented as just-in-time
compilers that compile JavaScript code to bytecode for improved performance.
JavaScript History
In 1995, JavaScript was created by a Netscape developer named Brendan Eich. First,
its name was Mocha. And then, its name was changed to LiveScript.
Netscape decided to change LiveScript to JavaScript to leverage Java’s fame, which
was popular. The decision was made just before Netscape released its web browser
product Netscape Navigator 2. As a result, JavaScript entered version 1.0.
Netscape released JavaScript 1.1 in Netscape Navigator 3. In the meantime, Microsoft
introduced a web browser product called Internet Explorer 3 (IE 3), which competed
with Netscape. However, IE came with its own JavaScript implementation called JScript.
Microsoft used the name JScript to avoid possible license issues with Netscape.
Hence, two different JavaScript versions were in the market:
JavaScript had no standards that governed its syntax and features. And the community
decided that it was time to standardize the language.
In 1997, JavaScript 1.1 was submitted to the European Computer Manufacturers
Association (ECMA) as a proposal. Technical Committee #39 (TC39) was assigned to
standardize the language to make it a general-purpose, cross-platform, and vendor-
neutral scripting language.
TC39 developed ECMA-262, a standard for defining a new scripting language named
ECMAScript (often pronounced Ek-ma-script).
JavaScript 2
After that, the International Organization for Standardization and International
Electrotechnical Commissions (ISO/IEC) adopted ECMAScript (ISO/IEC-16262).
JavaScript overview
To define a variable in JavaScript, you use the var keyword. For example:
var x = 10;
var y = 20;
ES6 added a new way to declare a variable with the let keyword:
let x = 10;
let y = 20;
There are differences between var and let . And it’s a good practice to use
the let keyword to declare variables.
To declare a function, you use the function keyword. The following example defines a
function that calculates the sum of two arguments:
function add( a, b ) {
return a + b;
}
To log the result into the console window of the web browser, you use
the console.log() :
console.log(result);
JavaScript 3
JavaScript provides you with condition statements such as if-
let a = 20,
b = 30;
function divide(a, b) {
if(b == 0) {
throw 'Division by zero';
}
return a / b;
}
In the divide() function, we check whether the de-numerator (b) is zero. If yes,
we throw an exception. Otherwise, we return the result of a / b.
To declare an array, you use the following syntax:
To declare an array with some initial elements, you specify the elements in the square
brackets:
You can access the number of elements in the items array through its length property:
console.log(items.length);
// 3
To iterate over the elements of the items array, you use the for loop statement as
follows:
JavaScript 4
Or use the for...of loop in ES6:
JavaScript is an evolving language. It has many other features that you’ll learn in the
following Chapter.
JavaScript 5
Web Development Tools
Web development tools allow you to test and debug the JavaScript code. Web
development tools are often called dev tools.
Modern web browsers such as Google Chrome, Firefox, Edge, Safari, and Opera
provide the dev tools as built-in features.
Generally, dev tools allow you to work with a variety of web technologies such as HTML,
CSS, DOM, and JavaScript.
In this Chapter, you will learn how to open the Console tab of the dev tools to view
messages output by JavaScript.
Google Chrome
First, open the devtools.html file.
The devtools.html file has the following JavaScript code:
The dev tools will open the Console tab by default. It will look like this:
console.log('Hello, DevTools!');
To output the value of the variable, you use the following console.log() method. For
example:
This is because the variable msg has not been defined in the code but was referenced
in the assignment.
Now, you can see both normal messages issued by the console.log() and the error
messages. It’s enough to start. We’ll dive into the devtools in the later Chapter.
Safari
If you are using Safari browser on Mac, you need to enable the Developer Menu first:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
<script>
alert('Hello, World!');
</script>
</head>
<body>
</body>
</html>
World! message.
First, create a file whose extension is .js e.g., app.js , and place it in
the js subfolder. Note that placing the JavaScript file in the js folder is not
required however it is a good practice.
alert('Hello, World!');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
<script src="js/app.js"></script>
</head>
<body>
</body>
</html>
If you launch the helloworld.html file in the web browser, you will see an alert that
displays the Hello, World! message.
Note that you can load a JavaScript file from a remote server. This allows you to serve
up JavaScript from various domains e.g., content delivery network (CDN) to speed up
the page.
When you have multiple JavaScript files on a page, the JavaScript engine interprets the
files in the order that they appear. For example:
<script src="js/service.js"></script>
<script src="js/app.js"></script>
In this example, the JavaScript engine will interpret the service.js and the app.js files
in sequence. It completes interpreting the service.js file first before interpreting
the app.js file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
</head>
<body>
The app.js file might execute before the service.js file. Therefore, you must ensure
that there is no dependency between them.
The defer attribute requests the web browser to execute the script file after parsing the
HTML document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
Even though we place the <script> element in the <head> section, the script will wait for
the browser to receive the closing tag <html> to start executing.
Summary
Use <script> element to include a JavaScript file in an HTML page.
The async attribute of the <script> element instructs the web browser to fetch the
JavaScript file in parallel and then parse and execute as soon as the JavaScript file
is available.
The defer attribute of the <script> element allows the web browser to execute the
JavaScript file after the document has been parsed.
Carriage return
Space
New Line
tab
JavaScript engine ignores whitespace. However, you can use whitespace to format the
code to make it easy to read and maintain.
The following JavaScript code doesn’t use whitespace:
It is equivalent to the following code that uses whitespace. Hence, this code is much
easy to read:
if (formatted) {
console.log('The code is easy to read');
}
Note that JavaScript bundlers remove all whitespace from JavaScript files and put them
into a single file for deployment. By doing this, JavaScript bundlers make the JavaScript
code lighter and faster to load in web browsers.
Statements
A statement is a code that declares a variable or instructs the JavaScript engine to do a
task. A semicolon terminates a simple statement ( ; ).
JavaScript Syntax 1
Although the semicolon ( ; ) is optional; you should always use it to terminate a
statement. For example, the following declares a variable and shows it to the console:
Blocks
A block is a sequence of zero or more simple statements. A block is delimited by a pair
of curly brackets {} . For example:
if (window.localStorage) {
console.log('The local storage is supported);
}
Identifiers
An identifier is a name you choose for variables, parameters, functions, classes, etc. An
identifier name starts with a letter ( a-z , or A-Z ), an underscore( _ ), or a dollar sign ( $ )
and is followed by a sequence of characters including ( a-z , A-Z ), numbers ( 0-9 ),
underscores ( _ ), and dollar signs ( $ ).
Note that the letter is not limited to the ASCII character and may include extended
ASCII or Unicode though not recommended.
Identifiers are case-sensitive. For example, the message is different from the Message .
Comments
Comments allow you to add notes or hints to JavaScript code. When executing the
code, the JavaScript engine ignores the words.
JavaScript supports single-line and block comments.
Single-line comments
A single-line comment starts with two forward-slashes characters ( // ). A single-line
comment makes all the text following the // on the same line into a comment. For
example:
JavaScript Syntax 2
//This is a single-line comment code
Block comments
A delimited comment begins with a forward slash and asterisk /* and ends with the
opposite */ as in the following example:
Expressions
An expression is a piece of code that evaluates to a value. For example:
2 + 1
function if import
in switch typeof
JavaScript Syntax 3
yield const do
var
In addition to the reserved keywords, ECMA-252 also define a list of future reserved
words that cannot be used as identifiers or property names:
implements public
Summary
Use whitespace including carriage return, space, newline, and tab to format the
code. The JavaScript engine ignores the whiespace.
Use the curly braces ( {} ) to form a block that groups one or more simple
statements.
Identifiers are names that you choose for variables, functions, classes, etc.
Do not use the reserved keywords and reserved words for identifiers.
JavaScript Syntax 4
JavaScript Variables
A variable is a label that references a value like a number or string. Before using a
variable, you need to declare it.
message: "Hello"
Declare a variable
To declare a variable, you use the var keyword followed by the variable name as
follows:
var message;
A variable name can be any valid identifier. By default, the message variable has a
special value undefined if you have not assigned a value to it.
Variable names follow these rules:
Variable names are case-sensitive. This means that the message and Message are
different variables.
Variable names can only contain letters, numbers, underscores, or dollar signs and
cannot contain spaces. Also, variable names must begin with a letter, an
underscore ( _ ), or a dollar sign ( $) .
By convention, variable names use camelcase like message , yourAge , and myName .
JavaScript is a dynamically typed language. This means that you don’t need to specify
the variable’s type in the declaration like other static-typed languages such as Java
or C#.
Starting in ES6, you can use the let keyword to declare a variable like this:
let message;
JavaScript Variables 1
It’s a good practice to use the let keyword to declare a variable. Later, you’ll learn the
differences between var and let keywords. And you should not worry about it for now.
Initialize a variable
Once you have declared a variable, you can initialize it with a value. To initialize a
variable, you specify the variable name, followed by an equals sign ( = ) and a value.
For example, The following declares the message variable and initializes it with a literal
string "Hello" :
let message;
message = "Hello";
To declare and initialize a variable at the same time, you use the following syntax:
For example, the following statement declares the message variable and initializes it with
the literal string "Hello" :
JavaScript allows you to declare two or more variables using a single statement. To
separate two variable declarations, you use a comma ( , ) like this:
Since JavaScript is a dynamically typed language, you can assign a value of a different
type to a variable. Although, it is not recommended. For example:
JavaScript Variables 2
Change a variable
Once you initialize a variable, you can change its value by assigning a different value.
For example:
let message;
console.log(message);
// undefined
In this example, the message variable is declared but not initialized. Therefore,
the message variable is undefined.
In contrast, an undeclared variable is a variable that has not been declared. For
example:
console.log(counter);
Output:
console.log(counter);
^
ReferenceError: counter is not defined
In this example, the counter variable has not been declared. Hence, accessing it
causes a ReferenceError .
Constants
JavaScript Variables 3
A constant holds a value that doesn’t change. To declare a constant, you use the const
keyword. When defining a constant, you need to initialize it with a value. For example:
const workday = 5;
workday = 2;
Error:
Later, you’ll learn that the const keyword actually defines a read-only reference to a
value in the constants tutorial.
Summary
A variable is a label that references a value.
An undefined variable is a variable that has been declared but not initialized while
an undeclared variable is a variable that has not been declared.
JavaScript Variables 4
JavaScript Data Types
JavaScript has the primitive data types:
1. null
2. undefined
3. boolean
4. number
5. string
Primitive Complex
null object
undefined
boolean
number
bigint
string
symbol
To get the current type of the value that the variable stores, you use
the typeof operator:
counter = false;
console.log(typeof(counter));// "boolean"
counter = "Hi";
console.log(typeof(counter));// "string"
Output:
"number"
"boolean"
"string"
let counter;
console.log(counter);
// undefinedconsole.log(typeof counter);// undefined
In this example, the counter is a variable. Since the counter hasn’t been initialized, it is
assigned the value undefined . The type of counter is also undefined .
It’s important to note that the typeof operator also returns undefined when you call it on
a variable that hasn’t been declared:
console.log(typeof undeclaredVar);
// undefined
The typeof null returns object is a known bug in JavaScript. A proposal to fix this was
proposed but rejected. The reason was the that fix would break a lot of existing sites.
JavaScript defines that null is equal to undefined as follows:
console.log(null == undefined);
// true
console.log(Number.MAX_VALUE);
// 1.7976931348623157e+308
console.log(Number.MIN_VALUE);
// 5e-324
Also, you can use Infinity and -Infinity to represent the infinite number. For example:
console.log(Number.MAX_VALUE + Number.MAX_VALUE);
// Infinity
console.log(-Number.MAX_VALUE - Number.MAX_VALUE);
// -Infinity
NaN
stands for Not a Number. It is a special numeric value that indicates an invalid
NaN
console.log('a'/2);
// NaN;
console.log(NaN/2);
// NaN
console.log(NaN == NaN);
// false
If you want to single quotes or double quotes in a literal string, you need to use the
backslash to escape it. For example:
JavaScript strings are immutable. This means that it cannot be modified once created.
However, you can create a new string from an existing string. For example:
In this example:
Second, use the + operator to combine 'JavaScript' with ' String' to make its
value 'Javascript String' .
Behind the scene, the JavaScript engine creates a new string that holds the new
string 'JavaScript String' and destroys the original strings 'JavaScript' and ' String' .
The following example attempts to change the first character of the string JavaScript:
let s = 'JavaScript';
s[0] = 'j';
console.log(s)
But not:
'javaScript'
console.log(typeof completed);
// boolean
undefined undefined
For example:
console.log(Boolean('Hi'));// true
console.log(Boolean('')); // false
console.log(Boolean(20)); // true
console.log(Boolean(Infinity)); // true
console.log(Boolean(0)); // false
let s1 = Symbol();
The Symbol function creates a new unique value every time you call it.
console.log(Symbol() == Symbol());
// false
Note that you’ll learn more about symbols in the symbol chapter.
let person = {
firstName: 'John',
lastName: 'Doe'
};
A property name of an object can be any string. You can use quotes around the
property name if it is not a valid identifier.
For example, if the person object has a property first-name , you must place it in the
quotes such as "first-name" .
A property of an object can hold an object. For example:
let contact = {
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@example.com',
phone: '(408)-555-9999',
address: {
building: '4000',
street: 'North 1st street',
city: 'San Jose',
state: 'CA',
country: 'USA'
}
}
The contact object has the firstName , lastName , email , phone , and address properties.
The address property itself holds an object that has building , street , city , state ,
and country properties.
To access an object’s property, you can use
If you reference a property that does not exist, you’ll get an undefined value. For
example:
console.log(contact.age);
// undefined
console.log(contact['phone']);
// '(408)-555-9999'
console.log(contact['email']);
// 'john.doe@example.com'
ES2020 introduced a new primitive type bigint representing big integer numbers with
values larger than 253 – 1.
To support various types of numbers, JavaScript uses different number literal formats.
Integer numbers
The following shows how to declare a variable that holds a decimal integer:
Octal (base 8)
When you use the octal and hexadecimal numbers in arithmetic operations, JavaScript
treats them as decimal numbers.
Octal numbers
An octal literal number starts with the digit zero (0) followed by a sequence of octal
digits (numbers from 0 through 7). For example:
Output:
57
JavaScript Numbers 1
If an octal number contains a number not in the range from 0 to 7, the JavaScript engine
ignores the 0 and treats the number as a decimal. For example:
Output:
80
This implicit behavior might cause issues. Therefore, ES6 introduced a new octal
literal that starts with 0o followed by a sequence of octal digits (from 0 to 7). For
example:
Output:
57
If you have an invalid number after 0o , JavaScript will issue a syntax error like this:
Output:
Hexadecimal numbers
JavaScript Numbers 2
Hexadecimal numbers start with 0x or 0X followed by any number of hexadecimal digits
(0 through 9, and a through f). For example:
Output:
26
Floating-point numbers
To define a floating-point literal number, you include a decimal point and at least one
number after that. For example:
When you have a very big number, you can use e-notation. E-notation indicates a
number should be multiplied by 10 raised to a given power. For example:
Output:
31400000
The notation 3.14e7 means that take 3.14 and multiply it by 107 .
Likewise, you can use the E-notation to represent a very small number. For example:
JavaScript Numbers 3
Output:
Output:
5e-7
Output:
0.30000000000000004
Big Integers
JavaScript introduced the bigint type starting in ES2022. The bigint type stores whole
numbers whose values are greater than 253 – 1.
A big integer literal has the n character at the end of an integer literal like this:
JavaScript Numbers 4
let pageView = 9007199254740991n;
Summary
JavaScript Number type represents both integer and floating-point numbers.
JavaScript Numbers 5
JavaScript Numeric Separator
Introduction to the JavaScript numeric separator
The numeric separator allows you to create a visual separation between groups of digits
by using underscores ( _ ) as separators.
For example, the following number is very difficult to read especially when it contains
long digit repetitions:
It’s important to note that all numbers in JavaScript are floating-point numbers.
Also, you can use the numeric separators for factional and exponent parts. For
example:
Summary
Use underscores ( _ ) as the numeric separators to create a visual separation
between groups of digits.
Octal literals
To represent an octal literal in ES5, you use the zero prefix ( 0 ) followed by a sequence
of octal digits (from 0 to 7). For example:
let a = 051;
console.log(a);// 41
If the octal literal contains a number that is out of range, JavaScript ignores the leading
0 and treats the octal literal as a decimal, as shown in the following example:
In this example, since 8 is an invalid digit for representing the octal number, JavaScript
ignores the 0 and treats the whole number as a decimal with a value of 58.
Note you can use the octal literals in non-strict mode. If you use them in strict mode,
JavaScript will throw an error.
"use strict"
let b = 058;
// invalid octal
console.log(b);
SyntaxError: Decimals with leading zeros are not allowed in strict mode.
let c = 0o51;
console.log(c);// 41
If you use an invalid number in the octal literal, JavaScript will throw a SyntaxError as
shown in the following example:
let d = 0o58;
console.log(d);// SyntaxError
Binary literals
In ES5, JavaScript didn’t provide any literal form for binary numbers. To parse a binary
string, you use the parseInt() function as follows:
let e = parseInt('111',2);
console.log(e);// 7
ES6 added support for binary literals by using the 0b prefix followed by a sequence of
binary numbers (0 and 1). Here is an example:
let f = 0b111;
console.log(f);// 7
Summary
Octal literals start with 0o followed by a sequence of numbers between 0 and 7.
The boolean’s literal values are case-sensitive. This means that the True and False are
valid identifiers but they’re not boolean values.
JavaScript allows the values of other types to be cast to boolean values. To cast a non-
Boolean value to a boolean value, you use the built-in Boolean() function. For example:
console.log(hasError);
Output:
true
How it works.
First, declare a variable error that holds a literal string 'An error occurred' .
Second, cast the error variable to a boolean value using the Boolean() function.
Because the error variable holds a non-empty string, the Boolean() function casts its
value to true .
if (error) {
console.log(error);
}
Output:
An error occurred
In this example, since the error variable holds a non-empty string, the if statement
evaluates its value to true . Therefore, it executes the console.log(error) to output
the error to the console.
If you change the value of the error variable to an empty string ( "" ), you won’t see
anything in the output because the if statement evaluates it as false :
Summary
JavaScript boolean type has two literal values true and false .
To create literal strings, you use either single quotes ( ' ) or double quotes ( " ) like this:
ES6 introduced template literals that allow you to define a string backtick (`) characters:
The template literals allow you to use the single quotes and double quotes inside a
string without the need of escaping them. For example:
Also, you can place the variables and expressions inside a template literal. JavaScript
will replace the variables with their value in the string. This is called string interpolation.
For example:
console.log(message);
Output:
JavaScript string 1
In this example, JavaScript replaces the name variable with its value inside the template
literal.
Tab: '\t'
Backslash '\'
The following example uses the backslash character to escape the single quote
character in a string:
Note: JavaScript has the String type (with the letter S in uppercase), which is
the primitive wrapper type of the primitive string type. Therefore, you can access all
properties and methods of the String type from a primitive string.
Accessing characters
To access the characters in a string, you use the array-like [] notation with the zero-
based index. The following example returns the first character of a string with the index
zero:
JavaScript string 2
To access the last character of the string, you use the length - 1 index:
If you want to assemble a string piece by piece, you can use the += operator:
console.log(className);
Output:
String(n);
”+n
n.toString()
Note that the toString() method doesn’t work for undefined and null .
When you convert a string to a boolean, you cannot convert it back. For example:
JavaScript string 3
let status = false;
let str = status.toString();
// "false"
let back = Boolean(str);
// true
In this example:
First, declare the status variable and initialize it with the value of false .
Second, convert the status variable to a string using the toString() method.
Third, convert the string back to a boolean value using the Boolean() function. The
Boolean() function converts the string "false" to a boolean value. The result is true
because "false" is a non-empty string.
Note that only string for which the Boolean() returns false , is the empty string ( '' );
Comparing strings
To compare two strings, you use comparison operators such as > , >= , < , <= ,
and == operators.
The comparison operators compare strings based on the numeric values of the
characters. And it may return a string order that is different from the one used in
dictionaries. For example:
However:
Summary
JavaScript strings are primitive values and immutable.
JavaScript string 4
Literal strings are delimited by single quotes ( ' ), double quotes ( " ), or backticks
(`).
Use the comparison operators `>, >=, <, <=, == to compare strings.
JavaScript string 5
JavaScript Objects
Introduction to the JavaScript 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:
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 in
the above example.
Accessing properties
To access a property of an object, you use one of two notations: dot notation and array-
like notation.
JavaScript Objects 1
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);
2) Array-like notation ( [] )
The following illustrates how to access the value of an object’s property via the array-
like notation:
objectName['propertyName']
For example:
let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person['firstName']);
console.log(person['lastName']);
When a property name contains spaces, you need to place it inside quotes. For
example, the following address object has the 'building no' as a property:
JavaScript Objects 2
let address = {
'building no': 3960,
street: 'North 1st street',
state: 'CA',
country: 'USA'
};
To access the 'building no' property, you need to use the array-like notation:
address['building no'];
Error:
Note that it is not a good practice to use spaces in the property names of an object.
Reading from a property that does not exist will result in an undefined . For example:
console.log(address.district);
Output:
undefined
let person = {
firstName: 'John',
JavaScript Objects 3
lastName: 'Doe'
};
person.firstName = 'Jane';
console.log(person);
Output:
In this example, we changed the value of the firstName property of the person object
from 'John' to 'Jane' .
person.age = 25;
delete objectName.propertyName;
The following example removes the age property from the person object:
delete person.age;
If you attempt to reaccess the age property, you’ll get an undefined value.
JavaScript Objects 4
To check if a property exists in an object, you use the in operator:
propertyName in objectName
let employee = {
firstName: 'Peter',
lastName: 'Doe',
employeeId: 1
};
console.log('ssn' in employee);
console.log('employeeId' in employee);
Output:
false
true
Summary
An object is a collection of key-value pairs.
JavaScript Objects 5
JavaScript Primitive vs.
Reference Values
JavaScript has two different types of values:
Primitive values
Reference values
Primitive values are atomic pieces of data while reference values are objects that might
consist of multiple values.
Primitive values (null, undefined, boolean, number, string, symbol, and BigInt)
Because static data has a size that does not change, the JavaScript engine allocates a
fixed amount of memory space to the static data and stores it on the stack.
For example, the following declares two variables and initializes their values to a literal
string and a number:
Because name and age are primitive values, the JavaScript engine stores these
variables on the stack as shown in the following picture:
age=25
name="John"
Note: that strings are objects in many programming languages, including Java and C#.
However, strings are primitive values in JavaScript.
Unlike the stack, JavaScript stores objects (and functions) on the heap. The JavaScript
engine doesn’t allocate a fixed amount of memory for these objects. Instead, it’ll allocate
more space as needed.
The following example defines the name , age , and person variables:
let person = {
name: 'John',
age: 25,
};
Internally, the JavaScript engine allocates the memory as shown in the following picture:
{ name: "John",
age: 25 }
person
age= 25
name = "John"
In this picture, JavaScript allocates memory on the stack for the three
variables name , age , and person .
The JavaScript engine creates a new object on the heap memory. Also, it links
the person variable on the stack memory to the object on the heap memory.
Because of this, we say that the person variable is a reference that refers to an object.
Dynamic properties
A reference value allows you to add, change, or delete properties at any time. For
example:
let person = {
name: 'John',
age: 25,
};
console.log(person);
Output:
Unlike a reference value, a primitive value cannot have properties. This means that you
cannot add a property to a primitive value.
JavaScript allows you to add a property to a primitive value. However, it won’t take any
effect. For example:
console.log(name.alias);// undefined
Output:
undefined
In this example, we add the alias property to the name primitive value. But when we
access the alias property via the name primitive value, it returns undefined .
Copying values
When you assign a primitive value from one variable to another, the JavaScript engine
creates a copy of that value and assigns it to the variable. For example:
In this example:
First, declare a new variable age and initialize its value with 25 .
Behind the scene, the JavaScript engine creates a copy of the primitive value 25 and
assign it to the newAge variable.
Stack
newAge=25
age=25
On the stack memory, the newAge and age are separate variables. If you change the
value of one variable, it won’t affect the other.
For example:
newAge = newAge + 1;
console.log(age, newAge);
Stack
newAge=26
age=25
let person = {
name: 'John',
age: 25,
};
member.age = 26;
console.log(person);
console.log(member);
How it works.
First, declare a person variable and initialize its value with an object with two
properties name and age .
Second, assign the person variable to the member variable. In the memory, both
variables reference the same object, as shown in the following picture:
Stack Heap
{ name: "John",
member
age: 25 }
person
Third, change the age property of the object via the member variable:
{ name: "John",
member
age: 26 }
person
Since both person and member variables reference the same object, changing the object
via the member variable is also reflected in the person variable.
Summary
Javascript has two types of values: primitive values and reference values.
You can add, change, or delete properties to a reference value, whereas you cannot
do it with a primitive value.
Copying a primitive value from one variable to another creates a separate value
copy. It means that changing the value in one variable does not affect the other.
Copying a reference from one variable to another creates a reference so that two
variables refer to the same object. This means that changing the object via one
variable reflects in another variable.
Index 0 1 2 3 4
Element
1. First, an array can hold values of mixed types. For example, you can have an array
that stores elements with the types number, string, boolean, and null.
2. Second, the size of an array is dynamic and auto-growing. In other words, you don’t
need to specify the array size up front.
JavaScript Arrays 1
To create an array and initialize it with some elements, you pass the elements as a
comma-separated list into the Array() constructor.
For example, the following creates the scores array that has five elements (or
numbers):
Note that if you use the Array() constructor to create an array and pass a number into
it, you are creating an array with an initial size.
However, when you pass a value of another type like string into
the Array() constructor, you create an array with an element of that value. For example:
JavaScript allows you to omit the new operator when you use the Array() constructor.
For example, the following statement creates the artists array.
The array literal form uses the square brackets [] to wrap a comma-separated list of
elements.
The following example creates the colors array that holds string elements:
JavaScript Arrays 2
To create an empty array, you use square brackets without specifying any element like
this:
arrayName[index]
The following shows how to access the elements of the mountains array:
console.log(mountains[0]); // 'Everest'
console.log(mountains[1]); // 'Fuji'
console.log(mountains[2]); // 'Nanga Parbat'
To change the value of an element, you assign that value to the element like this:
console.log(mountains);
Output:
JavaScript Arrays 3
Typically, the length property of an array returns the number of elements. The following
example shows how to use the length property:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
seas.push('Red Sea');
console.log(seas);
Output:
[ 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea', 'Red Sea' ]
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
seas.unshift('Red Sea');
console.log(seas);
Output:
[ 'Red Sea', 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea' ]
JavaScript Arrays 4
3) Removing an element from the end of an array
To remove an element from the end of an array, you use the pop() method:
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
const lastElement = seas.pop();
console.log(lastElement);
Output:
Baltic Sea
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
const firstElement = seas.shift();
console.log(firstElement);
Output:
Black Sea
let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
let index = seas.indexOf('North Sea');
console.log(index);// 2
JavaScript Arrays 5
console.log(Array.isArray(seas));// true
Summary
In JavaScript, an array is an order list of values. Each value is called an element
specified by an index.
JavaScript arrays are dynamic, which means that they grow or shrink as needed.
JavaScript Arrays 6
JavaScript Arithmetic Operators
Introduction to the JavaScript Arithmetic Operators
JavaScript supports the following standard arithmetic operators:
Operator Sign
Addition +
Subtraction -
Multiplication *
Division /
Also, you can use the addition operator with two variables. For example:
console.log(grossPrice);
Output:
11.98
If both values are strings, it concatenates the second string to the first one.
If one value is a string, it implicitly converts the numeric value into a string and
concatenates two strings.
For example, the following uses the addition operator to add concatenate two strings:
let x = '10',
y = '20';
let result = x + y;
console.log(result);
Output:
1020
The following example shows how to use the addition operator to calculate the sum of a
number and a string:
console.log(result);
Output:
1020
In this example, JavaScript converts the number 10 into a string '10' and
concatenates the second string '20' to it.
The following table shows the result when using the addition operator with special
numbers:
+0 +0 +0 +0 + (+0) = +0
-0 +0 +0 -0 + (+0) = +0
-0 -0 -0 -0 + (-0) = -0
The following table shows how to use the subtraction operator with special values:
+0 +0 +0 +0 – (+0) = 0
+0 -0 -0 +0 – (-0) = 0
-0 -0 +0 -0 – (-0) = 0
Output:
If either value is not a number, the JavaScript engine implicitly converts it into a number
using the Number() function and performs the multiplication. For example:
console.log(result);
Output:
10
The following table shows how the multiply operator behaves with special values:
Negative
Infinity -Infinity Infinity * (-100) = -Infinity
number
Infinity Infinity Infinity Infinity * Infinity = Infinity
console.log(result);// 2
If either value is not a number, the JavaScript engine converts it into a number for
division. For example:
The following table shows the divide operators’ behavior when applying to special
values:
A positive
Infinity Infinity Infinity / 2 = Infinity
number
A negative
Infinity -Infinity Infinity / -2 = -Infinity
number
let energy = {
valueOf() {
return 100;
},
};
currentEnergy = energy / 2;
console.log(currentEnergy);
Output:
90
200
50
150
If the object doesn’t have the valueOf() method but has the toString() method, the
JavaScript engine will call the toString() method to get the value for calculation. For
example:
let energy = {
toString() {
return 50;
},
};
currentEnergy = energy / 2;
console.log(currentEnergy);
Output:
40
150
25
75
dividend % divisor
In this equation, the dividend , divisor , quotient , and remainder are all integers. The
sign of the remainder is the same as the sign of the dividend .
The sign of the remainder is the same as the sign of the dividend .
remainder = 5 % 2;
console.log(remainder); // 1
let remainder = -5 % 3;
console.log(remainder); // -2
remainder = -5 % -3;
console.log(remainder); // -2
let remainder = 10 % 0;
console.log(remainder); // NaN
If a dividend is a finite number and the divisor is an Infinity , the remainder is the
dividend. For example:
If the dividend is zero and the divisor is non-zero, the remainder is zero:
In this example, if the num is an odd number, the remainder is one. But if the num is an
even number, the remainder is zero.
Later, you’ll learn how to define a function that returns true if a number is odd
or false otherwise like this:
function isOdd(num) {
return num % 2;
}
Or wrap it in a function:
If the division and divisor have the same sign, the remainder and modulo operators
return the same result. Otherwise, they return different results.
For example:
Output:
remainder: 2
modulo: 2
remainder: -2
modulo: 1
Summary
Use the JavaScript remainder operator ( % ) to get the remainder of a value divided
by another value.
let a = b;
In this syntax, JavaScript evaluates the expression b first and assigns the result to the
variable a .
The following example declares the counter variable and initializes its value to zero:
let counter = 0;
The following example increases the counter variable by one and assigns the result to
the counter variable:
let counter = 0;
counter = counter + 1;
When evaluating the second statement, JavaScript evaluates the expression on the
right-hand first ( counter + 1 ) and assigns the result to the counter variable. After the
second assignment, the counter variable is 1 .
To make the code more concise, you can use the += operator like this:
let counter = 0;
counter += 1;
In this syntax, you don’t have to repeat the counter variable twice in the assignment.
In this example, JavaScript evaluates from right to left. Therefore, it does the following:
b = c;// b is 30
a = b;// a is also 30
Summary
Chain the assignment operators if you want to assign a single value to multiple
variables.
Unary
Name Meaning
Operators
+x Unary Plus Convert a value into a number
Increment Operator
++x Add one to the value
(Prefix)
Decrement Operator
–x Subtract one from the value
(Prefix)
Increment Operator
x++ Add one to the value
(Postfix)
Decrement Operator
x– Subtract one from the value
(Postfix)
let x = 10;
let y = +x;
console.log(y); // 10
When you apply the unary plus operator to a non-numeric value, it performs a number
conversion using the Number() function with the rules in the following table:
Value Result
For example, the following uses the unary plus operator to convert the string '10' to the
number 10 :
let s = '10';
console.log(+s);// 10
The following example uses the unary plus operator ( + ) to convert a boolean value into
a number, false to 0 , and true to 1 .
let f = false,
t = true;
console.log(+f);// 0console.log(+t);// 1
Output:
0
1
Suppose you have a product object with the toString() method as follows:
let person = {
name: 'John',
toString: function () {
return '25';
},
};
console.log(+person);
Output:
25
let person = {
name: 'John',
toString: function () {
return '25';
},
valueOf: function () {
return '30';
},
};
console.log(+person);
Output:
30
In this example, the person object has the valueOf() method, the JavaScript engine
calls it instead of the toString() method to get the value to convert.
let x = 10;
let y = -x;
console.log(y);// -10
If you apply the unary minus operator to a non-numeric value, it converts the value into
a number using the same rules as the unary plus operator and then negates the value.
console.log(age);// 26
The following example uses the prefix decrement operator to subtract one from a
variable:
console.log(weight);// 89
console.log(weight);// 89
When you apply the prefix increment or decrement, JavaScript changes the variable
before evaluating the statement. For example:
console.log(weight);// 96
In this example:
console.log(weight);// 94
In this example:
The postfix increment or decrement operator changes the value after the statement is
evaluated. For example:
console.log(newWeight);// 95console.log(weight);// 91
How it works.
First, add five to weight (90) and assign the result to the newWeight (95)
Second, add one to the weight variable after the second statement completes, the
weight becomes 91.
First, convert the value into a number using the same rules as the unary plus (+)
operator.
Summary
Unary operators work on one value.
Unary plus ( + ) or minus ( ) converts a non-numeric value into a number. The unary
minus negates the value after the conversion.
The prefix increment operator adds one to a value. The value is changed before the
statement is evaluated.
The postfix increment operator adds one to a value. The value is changed after the
statement is evaluated.
The prefix decrement operator subtracts one from a value. The value is changed
before the statement is evaluated.
The postfix decrement operator subtracts one from a value. The value is changed
after the statement is evaluated.
Operator Meaning
== equal to
!= not equal to
Compare numbers
If values are numbers, the comparison operators perform a numeric comparison. For
example:
let a = 10,
b = 20;
>= b expression returns false and the expression a == 10 expression returns true .
Compare strings
If the operands are strings, JavaScript compares the character codes numerically one
by one in the string.
Because JavaScript compares the character codes in the strings numerically, you may
receive an unexpected result, for example:
let f1 = 'apple',
f2 = 'Banana';
let result = f2 < f1;
console.log(result);// true
In this example, f2 is less than f1 because the letter B has the character
code 66 while the letter a has the character code 97 .
To fix this, you need to:
First, convert the strings into a common format, either lowercase or uppercase
For example:
let f1 = 'apple',
f2 = 'Banana';
Note that the toLowerCase() is a method of the String object that converts the string to
lowercase.
In this example, the comparison operator converts the string '10' into the
number 10 and compares them numerically.
let apple = {
valueOf: function () {
return 10;
},
};
let orange = {
toString: function () {
return '20';
},
};
console.log(apple > 10);// falseconsole.log(orange == 20);// true
In this first comparison, the apple object has the valueOf() method that returns 10 .
Therefore, the comparison operator uses the number 10 for comparison.
In the second comparison, JavaScript first calls the valueOf() method. However,
the orange object doesn’t have the valueOf() method. So JavaScript calls
the toString() method to get the returned value of 20 for comparison.
In addition to the above rules, the equal ( == ) and not-equal( != ) operators also have
the following rules.
Even
The not-equal ( != ) operator returns true when comparing the NaN with another value:
And also
Operator Meaning
The strict equal and not strict equal operators behave like the equal and not equal
operators except that they don’t convert the operand before comparison. See the
following example:
In the first comparison, since we use the equality operator, JavaScript converts the
string into a number and performs the comparison.
However, in the second comparison, we use the strict equal operator ( === ), JavaScript
doesn’t convert the string before comparison, therefore the result is false .
In this tutorial, you have learned how to use the JavaScript comparison operators to
compare values.
! (Logical NOT)
|| (Logical OR)
Output:
true
false
In this example, the eligible is true so !eligible returns false . And since
the required is true , the !required returns false .
When you apply the ! operator to a non-Boolean value. The ! operator first converts
the value to a boolean value and then negates it.
The following example shows how to use the ! operator:
!a
If a is an empty string, the result is true. In the case a is a non-empty string, the
result is false
The following demonstrates the results of the logical ! operator when applying to a
non-boolean value:
console.log(!undefined); // true
console.log(!null);// true
console.log(!20);//false
console.log(!0);//true
console.log(!NaN);//true
console.log(!{});// false
console.log(!'');//true
Double-negation ( !! )
Sometimes, you may see the double negation ( !! ) in the code. The !! uses the logical
NOT operator ( ! ) twice to convert a value to its real boolean value.
The result is the same as using the Boolean() function. For example:
The first ! operator negates the Boolean value of the counter variable. If
the counter is true , then the ! operator makes it false and vice versa.
The second ! operator negates that result of the first ! operator and returns the real
boolean value of the counter variable.
If a can be converted to true , the && operator returns the b ; otherwise, it returns
the a . In fact, this rule is applied to all boolean values.
The following truth table illustrates the result of the && operator when it is applied to two
Boolean values:
a b a && b
In this example, the eligible is false , therefore, the value of the expression eligible &&
required is false .
In this example, both eligible and required are true , therefore, the value of the
expression eligible && required is true .
Short-circuit evaluation
The && operator is short-circuited. It means that the && operator evaluates the second
value only if the first one doesn’t suffice to determine the value of an expression. For
example:
let b = true;
let result = b && (1 / 0);
console.log(result);
Output:
Infinity
In this example, b is true therefore the && operator could not determine the result
without further evaluating the second expression ( 1/0 ).
let b = false;
let result = b && (1 / 0);
console.log(result);
Output:
false
In this case, b is false , the && operator doesn’t need to evaluate the second
expression because it can determine the final result as false based value of the first
value.
For each value, converts it to a boolean. If the result is false , stops and returns the
original value.
In other words, The && operator returns the first falsy value or the last value if none
were found.
If a value can be converted to true , it is so-called a truthy value. If a value can be
converted to false , it is a so-called falsy value.
If a can be converted to true , returns a ; else, returns b . This rule is also applied to
boolean values.
The following truth table illustrates the result of the || operator based on the value of
the operands:
a b a || b
The || operator returns false if both values evaluate to false . In case either value
is true , the || operator returns true . For example:
In this example, the expression eligible || required returns false because both values
are false .
For each value, converts it to a boolean value. If the result of the conversion
is true , stops and returns the value.
If all values have been evaluated to false , return the last value.
In other words, the chain of the || operators returns the first truthy value or the last one
if no truthy value was found.
3. Logical OR (||)
Summary
The NOT operator ( ! ) negates a boolean value. The ( !! ) converts a value into its
real boolean value.
The AND operator ( && ) is applied to two Boolean values and returns true if both
values are true.
Both && and || operators are short-circuited. They can be also applied to non-
Boolean values.
The logical operator precedence from the highest to the lowest is ! , && and || .
The following table shows the equivalent of the logical assignments operator:
x ||= y x || (x = y)
x &&= y x && (x = y)
x ??= y x ?? (x = y);
x ||= y
In this syntax, the ||= operator only assigns y to x if x is falsy. For example:
let title;
title ||= 'untitled';
console.log(title);
Output:
untitled
console.log(title);
Output:
'JavaScript Awesome'
In this example, the title is 'JavaScript Awesome' so it is truthy. Therefore, the logical
OR assignment operator ( ||= ) doesn’t assign the string 'untitled' to
the title variable.
The logical OR assignment operator:
x ||= y
x || (x = y)
Like the logical OR operator, the logical OR assignment also short-circuits. It means that
the logical OR assignment operator only performs an assignment when the x is falsy.
The following example uses the logical assignment operator to display a default
message if the search result element is empty:
x &&= y;
x &&= y;
is equivalent to:
x && (x = y);
The following example uses the logical AND assignment operator to change the last
name of a person object if the last name is truthy:
let person = {
firstName: 'Jane',
lastName: 'Doe',
};
console.log(person);
Output:
x ??= y;
x ?? (x = y);
The following example uses the nullish coalescing assignment operator to add a
missing property to an object:
let user = {
username: 'Satoshi'
};
user.nickname ??= 'anonymous';
console.log(user);
Output:
In this example, the user.nickname is undefined , therefore, it’s nullish. The nullish
coalescing assignment operator assigns the string 'anonymous' to
the user.nickname property.
The following table illustrates how the logical assignment operators work:
Summary
The logical OR assignment ( x ||= y ) operator only assigns y to x if x is falsy.
value1 ?? value2
The nullish coalescing operator returns the second value ( value2 ) if the first value
( value2 ) is null or undefined . Technically, the nullish coalescing operator is equivalent
to the following block:
let count;
let result = count || 1 ;
console.log(result);// 1
let count = 0;
let result = count || 1;
In this example, the operator ?? does not evaluate the second expression that displays
the “Hi” to the console because the first value is 1 , which is not null or undefined .
The following example evaluates the second expression because the first one
is undefined :
'Hi'
However, you can avoid this error by wrapping the expression on the left of
the ?? operator in parentheses to explicitly specify the operator precedences:
Summary
The nullish coalescing operator ( ?? ) is a logical operator that accepts two values
and returns the second value if the first one is null or undefined .
The nullish coalescing operator is short-circuited and cannot directly combine with
the logical AND or OR operator.
Math.pow(base, exponent)
For example:
result = Math.pow(2,3);
console.log(result);// 8
ECMAScript 2016 provided an alternative way to get a base to the exponent power by
using the exponentiation operator ( ** ) with the following syntax:
x**n
let result = 2 ** 2;
console.log(result);// 4
result = 2 ** 3;
console.log(result);// 8
Also, you can use the exponentiation operator ( ** ) in the infix notation. For example:
let x = 2;
x **= 4;
console.log(x);// 16
JavaScript does not allow you to put a unary operator immediately before the base
number. If you attempt to do so, you’ll get a SyntaxError .
The following example causes a syntax error:
Error:
Summary
The exponentiation operator * raises a number to the power of an exponent.
if( condition )
statement;
Start
false
Condition
true
If block
End
JavaScript if 1
If you have more than one statement to execute, you need to use wrap them in a block
using a pair of curly braces as follows:
if (condition) {
// statements to execute
}
However, it’s a good practice to always use curly braces with the if statement. By
doing this, you make your code easier to maintain and avoid possible mistakes.
Output:
How it works.
First, declare and initialize the variable age to 18 :
Second, check if the age is greater or equal to 18 using the if statement. Because the
expression age >= 18 is true , the code inside the if statement executes and outputs a
message to the console:
JavaScript if 2
The following example also uses the if statement. However, the age is 16 which
causes the condition to evaluate as false . Therefore, you won’t see any message in
the output:
Nested if statement
It’s possible to use an if statement inside another if statement. For example:
if (state == 'CA') {
if (age >= 16) {
console.log('You can drive.');
}
}
Output:
How it works.
First, declare and initialize the age and state variables:
Second, check if the state is 'CA' using an if statement. If yes, check if the age is
greater than 16 using a nested if statement and output a message to the console:
JavaScript if 3
if (state == 'CA') {
if (age == 16) {
console.log('You can drive.');
}
}
In practice, you should avoid using nested if statements as much as possible. For
example, you can use the && operator to combine the conditions and use
an if statement as follows:
Summary
Use the JavaScript if statement to execute a statement if a condition is true .
JavaScript if 4
JavaScript if else
Introduction to the JavaScript if…else statement
The if statement executes a block if a condition is true . When the condition is false ,
it does nothing. But if you want to execute a statement if the condition is false , you can
use an if...else statement.
The following shows the syntax of the if...else statement:
if( condition ) {
// ...
} else {
// ...
}
In this syntax, the condition is a value or an expression that evaluates to true or false .
If the condition is true , the if...else statement executes the block that follows
the if branch.
If the condition is false , the if...else statement executes the block that follows
the else branch.
Typically, the condition evaluates to a boolean value, which is true or false . However,
if it evaluates to a non-boolean value, the if...else statement will convert it to the
boolean value.
The following flowchart illustrates how the if...else statement works:
JavaScript if else 1
Start
false
Condition
true
End
In this example, the age is 18 . Therefore, the expression age >= 18 is true . Hence,
you’ll see the following message in the console:
The following example is the same as above except that the age is 18 instead of 16 :
JavaScript if else 2
let age = 16;
Output:
In this example, the age is 16 . Therefore, the expression age >= 18 evaluates to false .
Hence, the statement in the else branch executes that output the message to the
console.
The following example uses a logical operator AND (&&) as the condition in the if block:
Because the age is 16 and the country is the USA, the following expression
returns true .
Summary
JavaScript if else 3
Use the JavaScript if...else statement to execute a block if a condition
is true and another block otherwise.
JavaScript if else 4
JavaScript if else if
Introduction to the JavaScript if else if statement
The if and if…else statements accept a single condition and execute
the if or else block accordingly based on the condition.
To check multiple conditions and execute the corresponding block if a condition is true ,
you use the if...else...if statement like this:
if (condition1) {
// ...
} else if (condition2) {
// ...
} else if (condition3) {
//...
} else {
//...
}
In this syntax, the if...else...if statement has three conditions. In theory, you can
have as many conditions as you want to, where each else...if the branch has a
condition.
The if...else...if statement checks the conditions from top to bottom and executes
the corresponding block if the condition is true .
The if...else...if statement stops evaluating the remaining conditions as soon as a
condition is true . For example, if the condition2 is true , the if...else...if statement
won’t evaluate the condition3 .
If all the conditions are false , the if...else...if statement executes the block in
the else branch.
The following flowchart illustrates how the if...else...if statement works:
JavaScript if else if 1
Start
true
Condition1 If Block
false
true
Condition2 Else If Block
false
true
Condition3 Else If Block
false
Else Block
End
let month = 6;
let monthName;
if (month == 1) {
monthName = 'Jan';
JavaScript if else if 2
} else if (month == 2) {
monthName = 'Feb';
} else if (month == 3) {
monthName = 'Mar';
} else if (month == 4) {
monthName = 'Apr';
} else if (month == 5) {
monthName = 'May';
} else if (month == 6) {
monthName = 'Jun';
} else if (month == 7) {
monthName = 'Jul';
} else if (month == 8) {
monthName = 'Aug';
} else if (month == 9) {
monthName = 'Sep';
} else if (month == 10) {
monthName = 'Oct';
} else if (month == 11) {
monthName = 'Nov';
} else if (month == 12) {
monthName = 'Dec';
} else {
monthName = 'Invalid month';
}
console.log(monthName);
Output:
Jun
In this example, we compare the month with 12 numbers from 1 to 12 and assign the
corresponding month name to the monthName variable.
Since the month is 6 , the expression month==6 evaluates to true . Therefore,
the if...else...if statement assigns the literal string 'Jun' to the monthName variable.
Therefore, you see Jun in the console.
If you change the month to a number that is not between 1 and 12, you’ll see
the Invalid Month in the console because the else clause will execute.
JavaScript if else if 3
The following example calculates a body mass index (BMI) of a person. It uses
the if...else...if statement to determine the weight status based on the BMI:
let weightStatus;
console.log(weightStatus);
Output:
Healthy Weight
How it works.
First, declare two variables that hold the weight in kilograms and height in meters. In
a real world application, you’ll get these values from a web form.
Second, calculate the body mass index by dividing the weight by the square of the
height.
Summary
JavaScript if else if 4
Use the JavaScript if...else...if statement to check multiple conditions and
execute the corresponding block if a condition is true .
JavaScript if else if 5
JavaScript Ternary Operator
Introduction to JavaScript ternary operator
When you want to execute a block if a condition evaluates to true , you often use
an if…else statement. For example:
console.log(message);
In this example, we show a message that a person can drive if the age is greater than
or equal to 16. Alternatively, you can use a ternary operator instead of the if-
else statement like this:
age >= 16 ? (message = 'You can drive.') : (message = 'You cannot drive.');
console.log(message);
console.log(message);
In this syntax, if the condition is true , the variableNamewill take the result of the first
expression ( expressionIfTrue ) or expressionIfFalse otherwise.
In this example, the returned value of the ternary operator is the last value in the
comma-separated list.
If the locked is 1, then the canChange variable is set to false , otherwise, it is set to true .
In this case, you can simplify it by using a Boolean expression as follows:
let locked = 1;
let canChange = locked != 1;
console.log(message);
Output:
Fast
It’s a good practice to use the ternary operator when it makes the code easier to read. If
the logic contains many if...else statements, you should avoid using the ternary
operators.
Summary
Use the JavaScript ternary operator ( ?: )to make the code more concise.
Output:
In this example, the spread operator ( ... ) unpacks elements of the colors array and
places them in a new array rgb . The spread operator ( ... ) can be used to merge two
or more arrays into one as shown in the following example:
Output:
ES2018 expands the spread operator ( ... ) to make it works with own enumerable
properties of an object. Suppose that you have a circle object with one
property radius :
const circle = {
radius: 10
};
const coloredCircle = {
...circle,
color: 'black'
};
console.log(coloredCircle);
Output:
{
radius: 10,
color: 'black'
}
const circle = {
radius: 10
};
console.log(clonedCircle);
Output:
{ radius: 10 }
const circle = {
radius: 10,
const clonedCircle = {
...circle
};
clonedCircle.style = 'red';
console.log(clonedCircle);
Output:
2) Merging objects
Like arrays, you can use the spread operator ( ... ) to merge two objects:
const circle = {
radius: 10
};
const style = {
backgroundColor: 'red'
};
const solidCircle = {
...circle,
...style
};
console.log(solidCircle);
Output:
class Circle {
constructor(radius) {
this.radius = radius;
}
set diameter(value) {
this.radius = value / 2;
console.log('SET ', value);
}
get diameter() {
return this.radius * 2;
}
}
let cloneCircle2 = {
...circle
};
Output:
SET 200
Object.defineProperty(blueSquare, 'color', {
value: 'blue',
enumerable: true,
writable: false
});
console.log(blueSquare);
Output:
const greenSquare = {
...blueSquare,
...style
};
console.log(greenSquare);
Output:
However, if you use the Object.assign() method, you will get an error:
Summary
Object spread operator ( ... ) unpacks the own enumerable properties of an object.
Use the object spread operator to clone an object or merge objects into one.
Cloning is always shallow.
When merging objects, the spread operator defines new properties while
the Object.assign() assigns them.
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
case value3:
statement3;
break;
default:
statement;
}
How it works.
First, evaluate the expression inside the parentheses after the switch keyword.
Second, compare the result of the expression with the value1 , value2 , … in
the case branches from top to bottom. The switch statement uses the strict
comparison ( === ).
Third, execute the statement in the case branch where the result of
the expression equals the value that follows the case keyword.
The break statement exits the switch statement. If you skip the break statement,
the code execution falls through the original case branch into the next one. If the
result of the expression does not strictly equal to any value, the switch statement
will execute the statement in the default branch.
That the switch statement will stop comparing the expression ‘s result with the remaining
case values as long as it finds a match.
The switch statement is like the if…else…if statement. But it has more readable syntax.
Start
Evaluate expressi...
true
value1 statement1
false
true
value2 statement2
false
true
value3 statement3
default statement
End
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = 'Sunday';
break;
case 2:
dayName = 'Monday';
break;
case 3:
dayName = 'Tuesday';
break;
case 4:
dayName = 'Wednesday';
break;
case 5:
dayName = 'Thursday';
break;
case 6:
dayName = 'Friday';
break;
case 7:
dayName = 'Saturday';
break;
default:
dayName = 'Invalid day';
}
Output:
Tuesday
How it works.
First, declare the day variable that holds the day number and the day name variable
(dayName).
Second, get the day of the week based on the day number using the switch statement.
If the day is 1 , the day of the week is Sunday . If the day is 2 , the day of the week
is Monday , and so on.
Third, output the day of the week to the console.
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dayCount = 31;
break;
case 4:
case 6:
case 9:
case 11:
dayCount = 30;
break;
case 2:
// leap yearif ((year % 4 == 0 && !(year % 100 == 0)) || year % 400 == 0) {
console.log(dayCount);// 29
If the month is 1, 3,5, 7, 8, 10, or 12, the number of days in a month is 31.
If the month is 2, and the year is not the leap year, the number of days is 28. If the
year is the leap year, the number of days is 29.
If the month is not in the valid range (1-12), the default branch executes and sets
the dayCount variable to -1, which indicates the invalid month.
Summary
The switch statement evaluates an expression, compares its result
with case values, and executes the statement associated with the matching case.
while (expression) {
// statement
}
The while statement evaluates the expression before each iteration of the loop.
If the expression evaluates to true , the while statement executes the statement .
Otherwise, the while loop exits.
Because the while loop evaluates the expression before each iteration, it is known as a
pretest loop.
If the expression evaluates to false before the loop enters, the while loop will never
execute.
The following flowchart illustrates the while loop statement:
false
Condition
true
Statements
End
Note that if you want to execute the statement a least once and check the condition
after each iteration, you should use the do…while statement.
let count = 1;
while (count < 10) {
console.log(count);
count +=2;
}
Output:
1
3
5
7
9
Second, execute the statement inside the loop if the count variable is less than 10 .
In each iteration, output the count to the console and increase the count by 2 .
Third, after 5 iterations, the count is 11 . Therefore, the condition count <
Summary
Use a while loop statement to create a loop that executes a block as long as
a condition evaluates to true .
do {
statement;
} while(expression);
Unlike the while loop, the do-while loop always executes the statement at least once
before evaluating the expression .
Because the do...while loop evaluates expression after each iteration, it’s often referred
to as a post-test loop.
Inside the loop body, you need to make changes to some variables to ensure that
the expression is false after some iterations. Otherwise, you’ll have an indefinite loop.
Note that starting with ES6+, the trailing semicolon ( ; ) after the while(expression) is
optional. So you can use the following syntax:
do {
statement;
} while(expression)
Statements
true
Condition
false
End
In practice, you often use the do...while statement when you want to execute the loop
body at least once before checking the condition.
let count = 0;
do {
console.log(count);
count++;
} while (count < 5)
Output:
0
1
2
In this example:
Second, show the count and increase its value by one in each iteration until its
value is greater or equal to 5.
let guesses = 0;// for storing the number of guesseslet hint = '';
// for storing hintlet number = 0;
do {
// get input from user
let input = prompt(`Please enter a number between ${MIN} and ${MAX}` + hint);
//Check the input number with the secret number and provide a hint if needed
const MIN = 1;
const MAX = 10;
Second, use Math.random() function to generate a random floating-point number with the
value in the range of 0 and 1 (inclusive of zero but not one).
To generate a random number between MIN and MAX (exclusive), you use the following
expression:
To generate a random number between min and max, you use the following expression:
Third, define three variables for storing the number of guesses, hints, and user’s input
number:
let guesses = 0;
// for storing the number of guesses
let hint = '';
// for storing hint
let number = 0;
Fourth, use the input() function to get the input from the user:
let input = prompt(`Please enter a number between ${MIN} and ${MAX}` + hint);
number = parseInt(input);
guesses++;
Sixth, check the input number with the secret number (random) number and give a hint.
If the numbers are matched, show the message using the alert() function:
Seventh, perform the next iteration until the number matches the secret number.
Summary
Use the do…while statement to create a loop that executes a code block until a
condition is false .
1) initializer
The for statement executes the initializer only once the loop starts. Typically, you
declare and initialize a local loop variable in the initializer.
2) condition
The condition is a boolean expression that determines whether the for should execute
the next iteration.
The for statement evaluates the condition before each iteration. If the condition
is true (or is not present), it executes the next iteration. Otherwise, it’ll end the loop.
3) iterator
The for statement executes the iterator after each iteration.
The following flowchart illustrates the for loop:
Initializer
false
Condition End
true
Statement
Iterator
In the for loop, the three expressions are optional. The following shows the for loop
without any expressions:
for ( ; ; ) {
// statements
}
1
2
3
4
How it works.
Second, display the value of counter in the console if counter is less than 5.
Third, increase the value of counter by one in each iteration of the loop.
let j = 1;
for (; j < 10; j += 2) {
console.log(j);
}
Output:
1
3
5
7
9
for (let j = 1; ; j += 2) {
console.log(j);
if (j > 10) {
break;
Output:
1
3
5
7
9
11
let j = 1;
for (;;) {
if (j > 10) {
break;
}
console.log(j);
j += 2;
}
Output:
1
3
5
7
9
4) Using the JavaScript for loop without the loop body example
JavaScript allows the for statement to have an empty statement. In this case, you
place a semicolon ( ; ) immediately after the for statement.
let sum = 0;
for (let i = 0; i <= 9; i++, sum += i);
console.log(sum);
Output:
55
Summary
Use the JavaScript for statement to create a loop that executes a block of code
using various options.
label: statement;
In this syntax, the label can be any valid identifier. For example, the following shows
how to label a for loop using the outer label:
Once defining a label, you can reference it in the break or continue statement.
break [label];
In this syntax, the label is optional if you use the break statement in a loop or switch .
However, if you use the break statement with a label statement, you need to specify it.
This tutorial focuses on how to use the break statement to terminate the loop
prematurely.
JavaScript break 1
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
0
1
2
3
4
To terminate the for loop prematurely, you can use a break statement. For example,
the following illustrates how to use a break statement inside a for loop:
Output:
0
1
2
In this example, we use an if statement inside the loop. If the current value of i is 2 ,
the if statement executes the break statement that terminates the loop.
This flowchart illustrates how the break statement works in a for loop:
JavaScript break 2
Start
Initializer
false
Condition End
true
Statement
Yes
break
No
Statement
Iterator
JavaScript break 3
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
If you use a break statement inside an inner loop, it only terminates the enclosing loop.
For example:
Output:
1 1
1 2
2 1
In this example, if the sum of i and j is 4 , the break statement terminates the inner
loop. To terminate the nested loop, you use a label statement. For example:
JavaScript break 4
Output:
1 1
1 2
In this example, we label the outer loop with the label outer . Inside the inner loop, we
specify the outer label in the break statement. The break statement to terminate the
nested loop if the sum of i and j is 4 .
let i = 0;
while (i < 5) {
i++;
console.log(i);
}
Output:
1
2
3
4
5
Like a for loop, the break statement terminates a while loop prematurely. For
example:
let i = 0;
while (i < 5) {
i++;
console.log(i);
if (i == 3) {
break;
}
}
JavaScript break 5
Output:
1
2
3
In this example, when the current value of i is 3 , the break statement terminates the
loop. Therefore, you see only three numbers in the output.
The following flowchart illustrates how the break statement works in a while loop:
Start
false
Condition
true
Statements
Yes
break
No
Statements
End
JavaScript break 6
The following example uses a do...while statement to output five numbers from 0 to 5
to the console:
let i = 0;
do {
i++;
console.log(i);
} while (i < 5);
Output:
1
2
3
4
5
Like a while loop, you can use a break statement to terminate a do...while loop. For
example:
let i = 0;
do {
i++;
console.log(i);
if (i == 3) {
break;
}
} while (i < 5);
Output:
1
2
3
The following flowchart shows how the break statement works in a do while loop:
JavaScript break 7
Start
Statements
Yes
break
No
Statements
true
Condition
false
End
Summary
Use the break statement to terminate a loop including for , while ,
and do...while prematurely.
When used in a nested loop, the break statement terminates the enclosing loop. To
terminate the nested loop, you use a label statement.
JavaScript break 8
JavaScript continue
Introduction to the JavaScript continue statement
The continue statement terminates the execution of the statement in the current
iteration of a loop such as a for, while, and do…while loop and immediately continues to
the next iteration.
Here’s the syntax of the continue statement:
continue [label];
In this syntax, the label is optional. It is a valid identifier associated with the label of a
statement. Read the break statement tutorial for more information on the label
statement.
Typically, you use the continue with an if statement like this:
// inside a loopif(condition){
continue;
}
In this syntax, the if statement specifies a condition to execute the continue statement
inside a loop.
The following flowchart illustrates how the continue statement works in a for loop:
JavaScript continue with for loop
JavaScript continue 1
Start
Initializer
false
Condition End
true
Statement
Yes
continue
No
Statement
Iterator
The following example uses a continue in a for loop to display the odd number in the
console:
Output:
JavaScript continue 2
1
3
5
7
9
In this example, the for loop iterates over the numbers from 0 to 9 .
The i%2 returns the remainder of the division of the current value of i by 2 .
If the remainder is zero, the if statement executes the continue statement that skips
the current iteration of the loop and jumps to the iterator expression i++ . Otherwise, it
outputs the value of i to the console.
JavaScript continue 3
Start
Initializer
false
Condition End
true
Statement
Yes
continue
No
Statement
Iterator
The following example uses the continue statement in a while loop to display the odd
numbers from 1 to 10:
let i = 0;
while (i < 10) {
i++;
if (i % 2 === 0) {
continue;
}
console.log(i);
}
JavaScript continue 4
Output:
1
3
5
7
9
continue label;
Output:
1 1
1 2
2 1
2 2
The following shows how to use the continue statement with a label:
JavaScript continue 5
Output:
1 1
3 1
3 2
3 3
Summary
Use the JavaScript continue statement to skip the current iteration of a loop and
continue the next one.
JavaScript continue 6
JavaScript Comma Operator
Introduction to the JavaScript comma operator
JavaScript uses a comma ( , ) to represent the comma operator. A comma operator
takes two expressions, evaluates them from left to right, and returns the value of the
right expression.
Here’s the syntax of the comma operator:
leftExpression, rightExpression
For example:
Output:
30
In this example, the 10, 10+20 returns the value of the right expression, which is 10+20.
Therefore, the result value is 30.
See the following example:
let x = 10;
let y = (x++, x + 1);
console.log(x, y);
Output:
11 12
let x = 10;
x++;
let y = x + 1;
console.log(x, y);
let s = '';
for (let i = 0, j = 1; i < board.length; i++, j++) {
s += board[i] + ' ';
if (j % 3 == 0) {
console.log(s);
s = '';
}
}
Output:
1 2 3
4 5 6
7 8 9
Summary
A comma operator takes two expressions and evaluates them from left to right, and
returns the value of the right expression.
Use two statements rather than the comma operator elsewhere to make the code
more explicit and easier to understand.
To avoid repeating the same code all over places, you can use a function to wrap that
code and reuse it.
JavaScript provides many built-in functions such as parseInt() and parseFloat() . In this
tutorial, you will learn how to develop custom functions.
Declare a function
To declare a function, you use the function keyword, followed by the function name, a
list of parameters, and the function body as follows:
function functionName(parameters) {
// function body// ...
}
The function name must be a valid JavaScript identifier. By convention, the function
names are in camelCase and start with verbs like getData() , fetchContents() ,
and isValid() .
A function can accept zero, one, or multiple parameters. In the case of multiple
parameters, you need to use a comma to separate two parameters.
The following declares a function say() that accepts no parameter:
function say() {
}
The following declares a function named square() that accepts one parameter:
function square(a) {
}
JavaScript Functions 1
And the following declares a function named add() that accepts two parameters:
function add(a, b) {
}
Inside the function body, you can write the code to implement an action. For example,
the following say() function simply shows a message to the console:
function say(message) {
console.log(message);
}
In the body of the say() function, we call the console.log() function to output a
message to the console.
Calling a function
To use a function, you need to call it. Calling a function is also known as invoking a
function. To call a function, you use its name followed by arguments enclosing in
parentheses like this:
functionName(arguments);
When calling a function, JavaScript executes the code inside the function body. For
example, the following shows how to call the say() function:
say('Hello');
In this example, we call the say() function and pass a literal string 'Hello' into it.
JavaScript Functions 2
When declaring a function, you specify the parameters. However, when calling a
function, you pass the arguments that are corresponding to the parameters.
For example, in the say() function, the message is the parameter and the 'Hello' string
is an argument that corresponds to the message parameter.
Returning a value
Every function in JavaScript implicitly returns undefined unless you explicitly specify a
return value. For example:
function say(message) {
console.log(message);
}
Output:
Hello
Result: undefined
To specify a return value for a function, you use the return statement followed by an
expression or a value, like this:
return expression;
For example, the following add() function returns the sum of the two arguments:
function add(a, b) {
return a + b;
}
JavaScript Functions 3
Output:
Sum: 30
The following example uses multiple return statements in a function to return different
values based on conditions:
function compare(a, b) {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
return 0;
}
function say(message) {
// show nothing if the message is empty
if (! message ) {
return;
}
console.log(message);
}
In this example, if the message is blank (or undefined ), the say() function will show
nothing.
JavaScript Functions 4
The function can return a single value. If you want to return multiple values from a
function, you need to pack these values in an array or an object.
function add() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
Hence, you can pass any number of arguments to the add() function, like this:
console.log(add(1, 2)); // 3
console.log(add(1, 2, 3, 4, 5)); // 15
Function hoisting
In JavaScript, you can use a function before declaring it. For example:
JavaScript Functions 5
function showMe(){
console.log('an hoisting example');
}
function showMe(){
console.log('a hoisting example');
}
Summary
Use the function keyword to declare a function.
All functions implicitly return undefined if they don’t explicitly return a value.
The function hoisting allows you to call a function before declaring it.
JavaScript Functions 6
JavaScript Functions are First-
Class Citizens
Storing functions in variables
Functions are first-class citizens in JavaScript. In other words, you can treat functions
like values of other types.
The following defines the add() function and assigns the function name to the
variable sum :
function add(a, b) {
return a + b;
}
In the assignment statement, we don’t include the opening and closing parentheses at
the end of the add identifier. We also don’t execute the function but reference the
function.
By doing this, we can have two ways to execute the same function. For example, we
can call it normally as follows:
Alternatively, we can all the add() function via the sum variable like this:
Now, you can pass the sum function to the average() function as follows:
function add(a, b) {
return a + b;
}
console.log(result);
Output:
15
if (x > y) {
return 1;
} else if (x < y) {
return -1;
} else {
return 0;
}
};
}
Note that a[propertyName] returns the value of the propertyName of the a object. It’s
equivalent to a.propertyName . However, if the propertyName contains a space
like 'Discount Price' , you need to use the square bracket notation to access it.
Suppose that you have an array of product objects where each product object has two
properties: name and price .
let products = [
{name: 'iPhone', price: 900},
{name: 'Samsung Galaxy', price: 850},
{name: 'Sony Xperia', price: 700}
];
You can sort an array by calling the sort() method. The sort() method accepts a
function that compares two elements of the array as an argument.
For example, you can sort the product objects based on the name by passing a function
returned from the compareBy() function as follows:
console.table(products);
Output:
Output:
function compareBy(propertyName) {
return function (a, b) {
let x = a[propertyName],
y = b[propertyName];
if (x > y) {
return 1;
} else if (x < y) {
return -1;
} else {
return 0;
}
};
}
let products = [
console.table(products);
function cmToIn(length) {
return length / 2.54;
}
function inToCm(length) {
return length * 2.54;
}
To convert cm to in , you can call the convert() function and pass the cmToIn function
into the convert() function as the first argument:
Output:
3.937007874015748
Output:
25.4
function cmToIn(length) {
return length / 2.54;
}
function inToCm(length) {
return length * 2.54;
}
Output:
3.937007874015748
25.4
Summary
Functions are first-class citizens in JavaScript.
You can pass functions to other functions as arguments, return them from other
functions as values, and store them in variables.
(function () {
//...
});
Note that if you don’t place the anonymous function inside the () , you’ll get a syntax
error. The () makes the anonymous function an expression that returns a function
object.
An anonymous function is not accessible after its initial creation. Therefore, you often
need to assign it to a variable.
For example, the following shows an anonymous function that displays a message:
show();
In this example, the anonymous function has no name between the function keyword
and parentheses () .
Because we need to call the anonymous function later, we assign the anonymous
function to the show variable.
Since the whole assignment of the anonymous function to the show variable makes a
valid expression, you don’t need to wrap the anonymous function inside the
parentheses () .
setTimeout(function() {
console.log('Execute later after 1 second')
}, 1000);
(function() {
console.log('IIFE');
})();
How it works.
First, define a function expression:
(function () {
console.log('Immediately invoked function execution');
})
(function () {
console.log('Immediately invoked function execution');
})();
let person = {
firstName: 'John',
lastName: 'Doe'
};
(function () {
console.log(person.firstName} + ' ' + person.lastName);
})(person);
Arrow functions
ES6 introduced arrow function expressions that provide a shorthand for declaring
anonymous functions:
For example, this function:
Summary
function square(x) {
x = x * x;
return x;
}
let y = 10;
let result = square(y);
console.log(result); // 100
console.log(y); // 10 -- no change
y = 10
Then, pass the y variable into the square() function. When passing the variable y to
the square() function, JavaScript copies y value to the x variable.
x = 10
y = 10
After that, the square() function changes the x variable. However, it does not impact
the value of the y variable because x and y are separate variables.
x = 100
y = 10
Finally, the value of the y variable does not change after the square() function
completes.
Stack
result = 100
y = 10
let person = {
name: 'John',
age: 25,
};
function increaseAge(obj) {
obj.age += 1;
}
increaseAge(person);
console.log(person);
{ name: "John",
age: 25 }
person
Next, define the increaseAge() function that accepts an object obj and increases
the age property of the obj argument by one.
Then, pass the person object to the increaseAge() function:
Stack Heap
{ name: "John",
obj
age: 25 }
person
Internally, the JavaScript engine creates the obj reference and make this variable
reference the same object that the person variable references.
Stack Heap
{ name: "John",
obj
age: 26 }
person
Stack Heap
{ name: "John",
age: 26 }
person
It seems that JavaScript passes an object by reference because the change to the
object is reflected outside the function. However, this is not the case.
In fact, when passing an object to a function, you are passing the reference of that
object, not the actual object. Therefore, the function can modify the properties of the
object via its reference.
However, you cannot change the reference passed into the function. For example:
function increaseAge(obj) {
obj.age += 1;
increaseAge(person);
console.log(person);
Output:
In this example, the increaseAage() function changes the age property via
the obj argument:
Stack Heap
{ name: "John",
obj
age: 26 }
person
{ name: "Jane",
age: 22 }
{ name: "John",
obj
age: 26 }
person
However, the person reference still refers to the original object whose the age property
changes to 26 . In other words, the increaseAge() function doesn’t change
the person reference.
If this concept still confuses you, you can consider function arguments as local
variables.
Summary
JavaScript passes all arguments to a function by values.
Suppose that you have a function called recurse() . The recurse() is a recursive
function if it calls itself inside its body, like this:
function recurse() {
// ...
recurse();
// ...
}
A recursive function always has a condition to stop calling itself. Otherwise, it will call
itself indefinitely. So a recursive function typically looks like the following:
function recurse() {
if(condition) {
// stop calling itself//...
} else {
recurse();
}
}
Generally, you use recursive functions to break down a big problem into smaller ones.
Typically, you will find the recursive functions in data structures like binary trees and
graphs and algorithms such as binary search and quicksort.
function countDown(fromNumber) {
console.log(fromNumber);
}
countDown(3);
function countDown(fromNumber) {
console.log(fromNumber);
countDown(fromNumber-1);
}
countDown(3);
This countDown(3) will run until the call stack size is exceeded, like this:
if (nextNumber > 0) {
countDown(nextNumber);
}
}
countDown(3);
Output:
3
2
1
Error:
The code causes an error because the body of the countDown() function references
the countDown function name, which was set to null at the time of calling the function.
if (nextNumber > 0) {
f(nextNumber);
}
}
sum(n) = n + sum(n-1)
sum(n-1) = n - 1 + sum(n-2)
...
sum(1) = 1
function sum(n) {
if (n <= 1) {
return n;
}
return n + sum(n - 1);
}
A recursive function always has a condition that stops the function from calling itself.
TL;DR
function say(message='Hi') {
console.log(message);
}
say();// 'Hi'
say('Hello')// 'Hello'
The default value of the message parameter in the say() function is 'Hi' .
In JavaScript, default function parameters allow you to initialize named parameters with
default values if no values or undefined are passed into the function.
function add(x, y) {
return x + y;
}
add(100,200);
In this example, the x and y are the parameters of the add() function, and the values
passed to the add() function 100 and 200 are the arguments.
function say(message) {
console.log(message);
}
say(); // undefined
The say() function takes the message parameter. Because we didn’t pass any argument
into the say() function, the value of the message parameter is undefined .
Suppose that you want to give the message parameter a default value 10.
A typical way for achieving this is to test parameter value and assign a default value if it
is undefined using a ternary operator:
function say(message) {
message = typeof message !== 'undefined' ? message : 'Hi';
console.log(message);
}
say(); // 'Hi'
In this example, we didn’t pass any value into the say() function. Therefore, the default
value of the message argument is undefined . Inside the function, we reassigned
the message variable the Hi string.
ES6 provides you with an easier way to set the default values for the function
parameters like this:
In the syntax above, you use the assignment operator ( = ) and the default value after
the parameter name to set a default value for that parameter. For example:
say(); // 'Hi'
say(undefined); // 'Hi'
say('Hello'); // 'Hello'
How it works.
In the first function call, we didn’t pass any argument into the say() function,
therefore message parameter took the default value 'Hi' .
In the second function call, we passed the undefined into the say() function, hence
the message parameter also took the default value 'Hi' .
In the third function call, we passed the 'Hello' string into the say() function,
therefore message parameter took the string 'Hello' as the default value.
The following doesn’t pass any arguments to the function so the createDiv() function
uses the default values for the parameters.
Suppose you want to use the default values for the height and width parameters and
specific border style. In this case, you need to pass undefined values to the first two
parameters as follows:
console.log(put('Toy Car'));
// -> ['Toy Car']
console.log(put('Teddy Bear'));
// -> ['Teddy Bear'], not ['Toy Car','Teddy Bear']
function requiredArg() {
throw new Error('The argument is required');
}
function add(x = requiredArg(), y = requiredArg()){
return x + y;
}
add(10); // error
add(10,20); // OK
function add(x = 1, y = x, z = x + y) {
return x + y + z;
}
console.log(add()); // 4
The parameter list seems to have its own scope. If you reference the parameter that
has not been initialized yet, you will get an error. For example:
Error message:
Using functions
You can use a return value of a function as a default value for a parameter. For
example:
In the getPrice() function, we called the taxRate() function to get the tax rate and use
this tax rate to calculate the tax amount from the price.
function add(x, y = 1, z = 2) {
console.log( arguments.length );
return x + y + z;
}
add(10); // 1
add(10, 20); // 2
add(10, 20, 30); // 3
let person = {
firstName: 'John',
lastName: 'Doe'
};
person.greet = function () {
console.log('Hello!');
}
person.greet();
Output:
Hello!
In this example:
Besides using a function expression, you can define a function and assign it to an object
like this:
let person = {
firstName: 'John',
lastName: 'Doe'
};
function greet() {
person.greet = greet;
person.greet();
In this example:
Second, assign the function name to the the greet property of the person object.
let person = {
firstName: 'John',
lastName: 'Doe',
greet: function () {
console.log('Hello, World!');
}
};
ES6 provides you with the concise method syntax that allows you to define a method for
an object:
let person = {
firstName: 'John',
lastName: 'Doe',
greet() {
console.log('Hello, World!');
}
};
person.greet();
this.propertyName
let person = {
firstName: 'John',
lastName: 'Doe',
greet: function () {
console.log('Hello, World!');
},
getFullName: function () {
return this.firstName + ' ' + this.lastName;
}
};
console.log(person.getFullName());
Output
'John Doe'
Summary
For example, the following creates a new person object with two
properties firstName and lastName :
let person = {
firstName: 'John',
lastName: 'Doe'
};
In practice, you often need to create many similar objects like the person object.
To do that, you can use a constructor function to define a custom type and
the new operator to create multiple objects from this type.
Technically speaking, a constructor function is a regular function with the following
convention:
The name of a constructor function starts with a capital letter like Person , Document ,
etc.
Note that ES6 introduces the class keyword that allows you to define a custom type.
And classes are just syntactic sugar over the constructor functions with some
enhancements.
Assign the arguments 'John' and 'Doe' to the firstName and lastName properties of
the object.
// return this;
}
let person = {
firstName: 'John',
lastName: 'Doe'
};
However, the constructor function Person allows you to create multiple similar objects.
For example:
this.getFullName = function () {
return this.firstName + " " + this.lastName;
};
}
Now, you can create a new Person object and invoke the getFullName() method:
Output:
John Doe
The problem with the constructor function is that when you create multiple instances of
the Person , the this.getFullName() is duplicated in every instance, which is not memory
efficient.
To resolve this, you can use the prototype so that all instances of a custom type can
share the same methods.
In this case, the Person just executes like a regular function. Therefore, the this inside
the Person function doesn’t bind to the person variable but the global object.
If you attempt to access the firstName or lastName property, you’ll get an error:
console.log(person.firstName);
Error:
Similarly, you cannot access the getFullName() method since it’s bound to the global
object.
person.getFullName();
Error:
this.firstName = firstName;
this.lastName = lastName;
this.getFullName = function () {
return this.firstName + " " + this.lastName;
};
}
The following returns undefined because the Person constructor function is called like a
regular function:
Output:
undefined
However, the following returns a reference to the Person function because it’s called
with the new keyword:
Output:
[Function: Person]
By using the new.target , you can force the callers of the constructor function to use
the new keyword. Otherwise, you can throw an error like this:
this.firstName = firstName;
this.lastName = lastName;
}
Alternatively, you can make the syntax more flexible by creating a new Person object if
the users of the constructor function don’t use the new keyword:
this.firstName = firstName;
this.lastName = lastName;
}
console.log(person.firstName);
This pattern is often used in JavaScript libraries and frameworks to make the syntax
more flexible.
Summary
JavaScript constructor function is a regular function used to create multiple similar
objects.
let counter = {
count: 0,
next: function () {
return ++this.count;
},
};
counter.next();
Inside the next() function, the this references the counter object. See the following
method call:
counter.next();
The next() is a function that is the property of the counter object. Therefore, inside
the next() function, the this references the counter object.
If you assign a property to this object in the global context, JavaScript will add the
property to the global object as shown in the following example:
this.color= 'Red';
console.log(window.color);// 'Red'
Function context
In JavaScript, you can call a function in the following ways:
Function invocation
Method Invocation
Constructor invocation
Indirect invocation
Each function invocation defines its own context. Therefore, the this behaves
differently.
function show() {
console.log(this === window);// true
}
show();
window.show();
In the strict mode, JavaScript sets the this inside a function to undefined . For example:
"use strict";
function show() {
console.log(this === undefined);
}
show();
To enable the strict mode, you use the directive "use strict" at the beginning of the
JavaScript file. If you want to apply the strict mode to a specific function only, you place
it at the top of the function body.
Note that the strict mode has been available since ECMAScript 5.1. The strict mode
applies to both function and nested functions. For example:
function show() {
"use strict";
console.log(this === undefined);// true
function display() {
console.log(this === undefined);// true
}
display();
}
show();
Output:
true
true
2) Method invocation
When you call a method of an object, JavaScript sets this to the object that owns the
method. See the following car object:
let car = {
brand: 'Honda',
getBrand: function () {
return this.brand;
}
}
console.log(car.getBrand());// Honda
In this example, the this object in the getBrand() method references the car object.
Since a method is a property of an object which is a value, you can store it in a variable.
console.log(brand());// undefined
You get undefined instead of "Honda" because when you call a method without
specifying its object, JavaScript sets this to the global object in non-strict mode
and undefined in the strict mode.
To fix this issue, you use the bind() method of the Function.prototype object.
The bind() method creates a new function whose the this keyword is set to a
specified value.
let car = {
brand: 'Honda',
getBrand: function () {
return this.brand;
}
}
let bike = {
brand: 'Harley Davidson'
}
Output:
Harley Davidson
In this example, the bind() method sets the this to the bike object, therefore, you see
the value of the brand property of the bike object on the console.
3) Constructor invocation
When you use the new keyword to create an instance of a function object, you use the
function as a constructor.
The following example declares a Car function, then invokes it as a constructor:
function Car(brand) {
this.brand = brand;
}
Car.prototype.getBrand = function () {
return this.brand;
}
Since the this value in the Car() sets to the global object,
the bmw.brand returns undefined .
To make sure that the Car() function is always invoked using constructor invocation,
you add a check at the beginning of the Car() function as follows:
function Car(brand) {
if (!(this instanceof Car)) {
throw Error('Must use the new operator to call the function');
}
this.brand = brand;
}
ES6 introduced a meta-property named new.target that allows you to detect whether a
function is invoked as a simple invocation or as a constructor.
You can modify the Car() function that uses the new.target metaproperty as follows:
function Car(brand) {
if (!new.target) {
throw Error('Must use the new operator to call the function');
}
this.brand = brand;
}
4) Indirect Invocation
In JavaScript, functions are first-class citizens. In other words, functions are objects,
which are instances of the Function type.
function getBrand(prefix) {
console.log(prefix + this.brand);
}
let honda = {
brand: 'Honda'
};
let audi = {
brand: 'Audi'
};
Output:
It's a Honda
It's an Audi
In this example, we called the getBrand() function indirectly using the call() method of
the getBrand function. We passed honda and audi object as the first argument of
the call() method, therefore, we got the corresponding brand in each call.
The apply() method is similar to the call() method except that its second argument is
an array of arguments.
Arrow functions
ES6 introduced a new concept called arrow function. In arrow functions, JavaScript sets
the this lexically.
It means the arrow function does not create its own execution context but inherits
the this from the outer function where the arrow function is defined. See the following
example:
In this example, the this value is set to the global object i.e., window in the web
browser.
Since an arrow function does not create its own execution context, defining a method
using an arrow function will cause an issue. For example:
function Car() {
this.speed = 120;
}
Car.prototype.getSpeed = () => {
return this.speed;
};
Inside the getSpeed() method, the this value reference the global object, not
the Car object but the global object doesn’t have a property called speed. Therefore,
the this.speed in the getSpeed() method returns undefined .
Environment Global
Node.js global
If you write JavaScript code that works across environments and needs to access the
global object, you have to use different syntaxes like window , frames , self , or global .
To standardize this, ES2020 introduced the globalThis that is available across
environments.
For example, the following code checks if the current environment supports the Fetch
API:
console.log(canFetch);
The code checks if the fetch() function is a property of the global object. In the web
browsers, the globalThis is the window object. Therefore, if you run this code on the
modern web browser, the canFetch will be true .
The following code returns true on the web browser:
JavaScript globalThis 1
globalThis === window
Output:
true
Summary
Use the globalThis object to reference the global object to make the code works
across environments.
JavaScript globalThis 2
JavaScript Object Properties
Object Property types
JavaScript specifies the characteristics of properties of objects via internal attributes
surrounded by the two pairs of square brackets, e.g., [[Enumerable]] .
1) Data properties
A data property contains a single location for a data value. A data property has four
attributes:
let person = {
firstName: 'John',
lastName: 'Doe'
};
An object.
If you use the Object.defineProperty() method to define a property of the object, the
default values of [[Configurable]] , [[Enumerable]] , and [[Writable]] are set
to false unless otherwise specified.
The following example creates a person object with the age property:
Since the default value of the [[Configurable]] attribute is set to true , you can remove it
via the delete operator:
delete person.age;
console.log(person.age);
Output:
undefined
The following example creates a person object and adds the ssn property to it using
the Object.defineProperty() method:
'use strict';
Object.defineProperty(person, 'ssn', {
configurable: false,
value: '012-38-9119'
});
delete person.ssn;
Output:
'use strict';
Object.defineProperty(person, 'ssn', {
configurable: false,
value: '012-38-9119'
});
Object.defineProperty(person, 'ssn', {
configurable: true
});
Output:
By default, the enumerable attribute of all the properties defined on an object is true . t
means that you can iterate over all object properties using the for...in loop like this:
age
ssn
Object.defineProperty(person, 'ssn', {
enumerable: false
});
Output
age
2) Accessor properties
Similar to data properties, accessor properties also
have [[Configurable]] and [[Enumerable]] attributes.
But the accessor properties have the [[Get]] and [[Set]] attributes instead
of [[Value]] and [[Writable]] .
When you read data from an accessor property, the [[Get]] function is called
automatically to return a value. The default return value of the [[Get]] function
is undefined .
If you assign a value to an accessor property, the [[Set]] function is called
automatically.
To define an accessor property, you must use the Object.defineProperty() method. or
example:
Object.defineProperty(person, 'fullName', {
get: function () {
return this.firstName + ' ' + this.lastName;
},
set: function (value) {
let parts = value.split(' ');
if (parts.length == 2) {
this.firstName = parts[0];
this.lastName = parts[1];
} else {
throw 'Invalid name format';
}
}
});
console.log(person.fullName);
Output:
'John Doe'
In this example:
First, define the person object that contains two properties: firstName and lastName .
Then, add the fullName property to the person object as an accessor property.
The [[Set]] method splits the argument by the space and assigns
the firstName and lastName properties the corresponding parts of the name.
If the full name is not in the correct format i.e., first name, space, and last name, it
will throw an error.
Object.defineProperties(product, {
name: {
value: 'Smartphone'
},
price: {
value: 799
},
tax: {
value: 0.1
},
netPrice: {
get: function () {
return this.price * (1 + this.tax);
}
}
});
Output:
In this example, we defined three data properties: name , price , and tax , and one
accessor property netPrice for the product object.
1. An object
It returns a descriptor object that describes a property. The descriptor object has four
properties: configurable, enumerable, writable, and value.
let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(descriptor);
Output:
{ value: 'John',
writable: true,
enumerable: true,
configurable: true }
Summary
JavaScript objects have two types of properties: data properties and accessor
properties.
object.propertyName = value;
or
let obj = {
propertyName: value,
...
};
The for...in allows you to access each property and value of an object without
knowing the specific name of the property. For example:
var person = {
firstName: 'John',
lastName: 'Doe',
ssn: '299-24-2351'
};
firstName:John
lastName:Doe
ssn:299-24-2351
In this example, we used the for...in loop to iterate over the properties of the person
object. We accessed the value of each property using the following syntax:
object[property];
var decoration = {
color: 'red'
};
Output:
radius
color
The circle object has its own prototype that references the decoration object.
Therefore, the for...in loop displays the properties of the circle object and its
prototype.
Output:
radius
However, someone may set a property of the built-in Array type in their libraries as
follows:
Array.prototype.foo = 100;
Output:
Or another example:
undefined
undefined
3
Output:
The output shows only the third element, not the first two elements.
Summary
The for...in loop iterates over the enumerable properties of an object. It also goes
up to the prototype chain and enumerates inherited properties.
Avoid using for...in loop to iterate over elements of an array, especially when the
index order is important.
const person = {
firstName: 'John',
lastName: 'Doe',
age: 25
};
}
}
Output:
John
Doe
25
ES2017 introduces a new method called Object.values() that allows you to return
an array of own enumerable property’s values of an object.
The following shows the syntax of the Object.values() :
Object.values(obj)
The Object.values() accepts an object and returns its own enumerable property’s values
as an array. See the following example:
const person = {
firstName: 'John',
lastName: 'Doe',
age: 25
JavaScript Object.values() 1
};
console.log(profile);
Output:
[ 'John', 'Doe', 25 ]
JavaScript Object.values() 2
JavaScript Object.entries()
Introduction to JavaScript Object.entries() method
ES2017 introduces the Object.entries() method that accepts an object and returns its
own enumerable string-keyed property [key, value] pairs of the object.
Object.entries()
const kv = Object.entries(person);
console.log(kv);
Output:
[
['firstName', 'John'],
['lastName', 'Doe'],
['age', 25]
]
In this example:
The firstName, lastName, and age are own enumerable string-keyed property of the
person object, therefore, they are included in the result.
The ssn is not a string-key property of the person object, so it is not included in the
result.
JavaScript Object.entries() 1
Object.entries() vs. for...in
The main difference between the Object.entries() and the for...in loop is that
the for...in loop also enumerates object properties in the prototype chain.
JavaScript Object.entries() 2
JavaScript Object.assign()
The following shows the syntax of the Object.assign() method:
Object.assign(target, ...sources)
The Object.assign() copies all enumerable and own properties from the source objects
to the target object. It returns the target object.
The Object.assign() invokes the getters on the source objects and setters on the target.
It assigns properties only, not copying or defining new properties.
let widget = {
color: 'red'
};
console.log(clonedWidget);
Output
{ color: 'red' }
Note that the Object.assign() only carries a shallow clone, not a deep clone.
let box = {
height: 10,
JavaScript Object.assign() 1
width: 20
};
let style = {
color: 'Red',
borderStyle: 'solid'
};
console.log(styleBox);
Output:
{
height: 10,
width: 20,
color: 'Red',
borderStyle: 'solid'
}
If the source objects have the same property, the property of the later object overwrites
the earlier one:
let box = {
height: 10,
width: 20,
color: 'Red'
};
let style = {
color: 'Blue',
borderStyle: 'solid'
};
console.log(styleBox);
Output:
{
height: 10,
width: 20,
color: 'Blue',
JavaScript Object.assign() 2
borderStyle: 'solid'
}
Summary
Object.assign() assigns enumerable and own properties from a source object to a
target object.
JavaScript Object.assign() 3
JavaScript Object.is()
The Object.is() behaves like the === operator with two differences:
0 and +0
NaN
Negative zero
The === operator treats -0 and +0 are the same value:
Output:
true
Output
false
NaN
The === operator considers NaN and NaN are different values. The NaN is the only
number that does not equal itself. For example:
JavaScript Object.is() 1
let quantity = NaN;
console.log(quantity === quantity);
Output:
false
console.log(Object.is(quantity, quantity));
Output:
true
JavaScript Object.is() 2
JavaScript Object.is() 3
Object Literal Syntax Extensions
in ES6
The object literal is one of the most popular patterns for creating objects in
JavaScript because of its simplicity. ES6 makes the object literal more succinct and
powerful by extending the syntax in some ways.
The createMachine() function takes two arguments name and status and returns a new
object literal with two properties: name and status .
The name and status properties take the values of the name and status parameters.
This syntax looks redundant because name and status mentioned twice in both the
name and value of properties.
ES6 allows you to eliminate the duplication when a property of an object is the same as
the local variable name by including the name without a colon and value.
For example, you can rewrite the createMachine() function in ES6 as follows:
let machine = {
name,
status
};
console.log(machine[name]); // server
console.log(machine['machine hours']); // 10000
The name variable was initialized to a value of 'machine name' . Since both properties of
the machine object contains a space, you can only reference them using the square
brackets.
The machine object’s properties evaluate to 'machine name' and 'machine hours' ,
therefore you can reference them as the properties of the machine object.
let server = {
name: "Server",
restart: function () {
console.log("The" + this.name + " is restarting...");
}
};
ES6 makes the syntax for making a method of the object literal more succinct by
removing the colon (:) and the function keyword.
The following example rewrites the server object above using the ES6 syntax.
let server = {
name: 'Server',
restart() {
console.log("The" + this.name + " is restarting...");
}
};
let server = {
name: 'Server',
restart() {
console.log("The " + this.name + " is restarting...");
},
'starting up'() {
console.log("The " + this.name + " is starting up!");
}
};
server['starting up']();
In this example, the method 'starting up' has spaces in its name. To call the method,
you use the following syntax:
object_name['property name']();
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
};
Output:
John Doe
How it works.
First, create the Person as a constructor function that has a property name called name .
The getName() function is assigned to the prototype so that it can be shared by all
instances of the Person type.
Then, create a new instance of the Person type using the new operator.
The john object, hence, is an instance of the Person and Object through prototypal
inheritance.
JavaScript Class 1
The following statements use the instanceof operator to check if john is an instance of
the Person and Object type:
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
This Person class behaves like the Person type in the previous example. However,
instead of using a constructor/prototype pattern, it uses the class keyword.
In the Person class, the constructor() is where you can initialize the properties of an
instance. JavaScript automatically calls the constructor() method when you instantiate
an object of the class.
The following creates a new Person object, which will automatically call
the constructor() of the Person class:
The getName() is called a method of the Person class. Like a constructor function, you
can call the methods of a class using the following syntax:
objectName.methodName(args)
For example:
JavaScript Class 2
let name = john.getName();
console.log(name);// "John Doe"
To verify the fact that classes are special functions, you can use the typeof operator of
to check the type of the Person class.
Error:
Second, all the code inside a class automatically executes in the strict mode. And you
cannot change this behavior.
Third, class methods are non-enumerable. If you use a constructor/prototype pattern,
you have to use the Object.defineProperty() method to make a property non-
JavaScript Class 3
enumerable.
Finally, calling the class constructor without the new operator will result in an error as
shown in the following example.
Error:
Note that it’s possible to call the constructor function without the new operator. In this
case, the constructor function behaves like a regular function.
Summary
Use the JavaScript class keyword to declare a new class.
JavaScript Class 4
JavaScript Getters and Setters
Introduction to the JavaScript getters and setters
The following example defines a class called Person :
class Person {
constructor(name) {
this.name = name;
}
}
The Person class has a property name and a constructor. The constructor initializes
the name property to a string.
Sometimes, you don’t want the name property to be accessed directly like this:
person.name
To do that, you may come up with a pair of methods that manipulate the name property.
For example:
class Person {
constructor(name) {
this.setName(name);
}
getName() {
return this.name;
}
setName(newName) {
newName = newName.trim();
if (newName === '') {
throw 'The name cannot be empty';
}
this.name = newName;
}
}
person.setName('Jane Smith');
console.log(person.getName());// Jane Smith
In this example, the Person class has the name property. Also, it has two additional
methods getName() and setName() .
The getName() method returns the value of the name property.
The setName() method assigns an argument to the name property.
The setName() removes the whitespaces from both ends of the newName argument and
throws an exception if the newName is empty.
The constructor() calls the setName() method to initialize the name property:
constructor(name) {
this.setName(name);
}
The getName() and setName() methods are known as getter and setter in other
programming languages such as Java and C++.
ES6 provides specific syntax for defining the getter and setter using the get and set
keywords. For example:
class Person {
constructor(name) {
this.name = name;
}
get name() {
return this._name;
}
set name(newName) {
newName = newName.trim();
if (newName === '') {
throw 'The name cannot be empty';
}
this._name = newName;
}
}
How it works.
get name() {
return this._name;
}
When JavaScript sees the access to name property of the Person class, it checks if
the Person class has any name property.
If not, JavaScript checks if the Person class has any method that binds to
the name property. In this example, the name() method binds to the name property via
the get keyword. Once JavaScript finds the getter method, it executes the getter
method and returns a value.
Third, the setter uses the set keyword followed by the method name:
set name(newName) {
newName = newName.trim();
if (newName === '') {
throw 'The name cannot be empty';
}
this._name = newName;
}
JavaScript will call the name() setter when you assign a value to the name property like
this:
If a class has only a getter but not a setter and you attempt to use the setter, the change
won’t take any effect. See the following example:
In this example, the Person class has the name getter but not the name setter. It attempts
to call the setter. However, the change doesn’t take effect since the Person class
doesn’t have the name setter.
let meeting = {
attendees: [],
add(attendee) {
console.log(`${attendee} joined the meeting.`);
this.attendees.push(attendee);
return this;
},
get latest() {
let count = this.attendees.length;
return count == 0 ? undefined : this.attendees[count - 1];
}
};
meeting.add('John').add('Jane').add('Peter');
console.log(`The latest attendee is ${meeting.latest}.`);
Output:
Summary
Use the get and set keywords to define the JavaScript getters and setters for a
class or an object.
The get keyword binds an object property to a method that will be invoked when
that property is looked up.
The set keyword binds an object property to a method that will be invoked when
that property is assigned.
A class expression doesn’t require an identifier after the class keyword. And you can
use a class expression in a variable declaration and pass it into a function as an
argument.
For example, the following defines a class expression:
How it works.
On the left side of the expression is the Person variable. It’s assigned to a class
expression.
The class expression starts with the keyword class followed by the class definition.
A class expression may have a name or not. In this example, we have an unnamed
class expression.
If a class expression has a name, its name can be local to the class body.
The following creates an instance of the Person class expression. Its syntax is the same
as if it were a class declaration.
Similar to function expressions, class expressions are not hoisted. It means that you
cannot create an instance of the class before defining the class expression.
First-class citizen
JavaScript classes are first-class citizens. It means that you can pass a class into a
function, return it from a function, and assign it to a variable.
See the following example:
function factory(aClass) {
return new aClass();
}
greeting.sayHi(); // 'Hi'
How it works.
First, define a factory() function that takes a class expression as an argument and
return the instance of the class:
function factory(aClass) {
return new aClass();
}
Second, pass an unnamed class expression to the factory() function and assign its
result to the greeting variable:
greeting.sayHi(); // 'Hi'
Singleton
Singleton is a design pattern that limits the instantiation of a class to a single instance. It
ensures that only one instance of a class can be created throughout the system.
Class expressions can be used to create a singleton by calling the class constructor
immediately.
To do that, you use the new operator with a class expression and include the
parentheses at the end of class declaration as shown in the following example:
How it works.
The following is an unnamed class expresion:
new class {
constructor(name) {
this.name = name;
}
start() {
console.log(`Starting the ${this.name}...`);
}
}
new class {
constructor(name) {
this.name = name;
}
start() {
console.log(`Starting the ${this.name}...`);
}
}('Awesome App')
This expression returns an instance of the class expression which is assigned to the
app variable.
The following calls the start() method on the app object:
Summary
ES6 provides you with an alternative way to defining a new class using a class
expression.
const rank = {
a: 1,
b: 2,
[propName]: 3,
};
console.log(rank.c);// 3
In this example, the [propName] is a computed property of the rank object. The property
name is derived from the value of the propName variable.
When you access c property of the rank object, JavaScript evaluates propName and
returns the property’s value.
Like an object literal, you can use computed properties for getters and setters of a class.
For example:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get [name]() {
return `${this.firstName} ${this.lastName}`;
}
}
Output:
How it works:
The get[name] is a computed property name of a getter of the Person class. At runtime,
when you access the fullName property, the person object calls the getter and returns
the full name.
Summary
Computed properties allow you to use the values of expressions as property names
of an object.
function Animal(legs) {
this.legs = legs;
}
Animal.prototype.walk = function() {
console.log('walking on ' + this.legs + ' legs');
}
function Bird(legs) {
Animal.call(this, legs);
}
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Animal;
Bird.prototype.fly = function() {
console.log('flying');
}
ES6 simplified these steps by using the extends and super keywords.
The following example defines the Animal and Bird classes and establishes the
inheritance through the extends and super keywords.
bird.walk();
bird.fly();
How it works.
First, use the extends keyword to make the Bird class inheriting from the Animal class:
The Animal class is called a base class or parent class while the Bird class is known
as a derived class or child class. By doing this, the Bird class inherits all methods
and properties of the Animal class.
Second, in the Bird ‘s constructor, call super() to invoke the Animal ‘s constructor with
the legs argument.
JavaScript requires the child class to call super() if it has a constructor. As you can see
in the Bird class, the super(legs) is equivalent to the following statement in ES5:
Animal.call(this, legs);
However, the child class has a constructor, it needs to call super() . For example, the
following code results in an error:
Error:
ReferenceError: Must call super constructor in derived class before accessing 'this' or re
turning from derived constructor
Because the super() initializes the this object, you need to call the super() before
accessing the this object. Trying to access this before calling super() also results in
an error.
Shadowing methods
ES6 allows the child class and parent class to have methods with the same name. In
this case, when you call the method of an object of the child class, the method in the
child class will shadow the method in the parent class.
The following Dog class extends the Animal class and redefines the walk() method:
To call the method of the parent class in the child class, you
use super.method(arguments) like this:
class Animal {
constructor(legs) {
this.legs = legs;
}
walk() {
console.log('walking on ' + this.legs + ' legs');
}
static helloWorld() {
console.log('Hello World');
}
}
In this example, the Animal class has the helloWorld() static method and this method is
available as Bird.helloWorld() and behaves the same as
the Animal.helloWorld() method:
while (!customers.empty()) {
console.log(customers.dequeue());
}
Summary
Use the extends keyword to implement the inheritance in ES6. The class to be
extended is called a base class or parent class. The class that extends the base
class or parent class is called the derived class or child class.
Call the super(arguments) in the child class’s constructor to invoke the parent class’s
constructor.
Use super keyword to call the methods of the parent class in the methods of the
child class.
The new.target is very useful to inspect at runtime whether a function is being executed
as a function or as a constructor. It is also handy to determine a specific derived class
that was called by using the new operator from within a parent class.
function Person(name) {
this.name = name;
}
You can create a new object from the Person function by using the new operator as
follows:
Person('Lily');
console.log(window.name);//Lily
To help you detect whether a function was called using the new operator, you use
the new.target metaproperty.
In a regular function call, the new.target returns undefined . If the function was called
with the new operator, the new.target returns a reference to the function.
Suppose you don’t want the Person to be called as a function, you can use
the new.target as follows:
function Person(name) {
if (!new.target) {
throw "must use new operator with Person";
}
this.name = name;
}
Now, the only way to use Person is to instantiate an object from it by using
the new operator. If you try to call it as a regular function, you will get an error.
class Person {
constructor(name) {
this.name = name;
console.log(new.target.name);
}
}
To define a static method before ES6, you add it directly to the constructor of the class.
For example, suppose you have a Person type as follows:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
};
The following adds a static method called createAnonymous() to the Person type:
If you attempt to call the static method from an instance of the class, you’ll get an error.
For example:
Error:
className.staticMethodName();
Summary
JavaScript static methods are shared among instances of a class. Therefore, they
are bound to the class.
Call the static methods via the class name, not the instances of that class.
class Item {
static count = 0;
}
To access a static property, you use the class name followed by the . operator and the
static property name. For example:
console.log(Item.count);// 0
To access the static property in a static method, you use the class name followed by
the . operator and the static property name. For example:
class Item {
static count = 0;
static getCount() {
return Item.count;
}
}
console.log(Item.getCount());// 0
To access a static property in a class constructor or instance method, you use the
following syntax:
className.staticPropertyName;
Or
this.constructor.staticPropertyName;
class Item {
constructor(name, quantity) {
this.name = name;
this.quantity = quantity;
this.constructor.count++;
}
static count = 0;
static getCount() {
return Item.count;
}
}
When you create a new instance of the Item class, the following statement increases
the count static property by one:
this.constructor.count++;
For example:
console.log(Item.getCount());// 2
This example creates two instances of the Item class, which calls the class constructor.
Since the class constructor increases the count property by one each time it’s called,
the value of the count is two.
Put it all together.
class Item {
constructor(name, quantity) {
this.name = name;
this.quantity = quantity;
this.constructor.count++;
}
static count = 0;
static getCount() {
console.log(Item.getCount());// 2
Summary
A static property of a class is shared by all instances of that class.
For example, the following defines the Circle class with a private field radius :
class Circle {
#radius;
constructor(value) {
this.#radius = value;
}
get area() {
return Math.PI * Math.pow(this.#radius, 2);
}
}
In this example:
Third, calculate the area of the circle by accessing the #radius private field in the
getter method.
The following creates a new instance of the Circle class and calculates its area:
Because the #radius is a private field, you can only access it inside the Circle class. In
other words, the #radius field is invisible outside of the Circle class.
How it works.
The radius setter validates the argument before assigning it to the #radius private
field. If the argument is not a positive number, the radius setter throws an error.
The radius getter returns the value of the #radius private field.
fieldName in objectName
For example, the following adds the hasRadius() static method to the Circle class that
uses the in operator to check if the circle object has the #radius private field:
class Circle {
#radius = 0;
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * Math.pow(this.radius, 2);
}
set radius(value) {
if (typeof value === 'number' && value > 0) {
this.#radius = value;
} else {
throw 'The radius must be a positive number';
}
}
get radius() {
return this.#radius;
}
static hasRadius(circle) {
return #radius in circle;
}
}
console.log(Circle.hasRadius(circle));
Output:
true
class Circle {
#radius = 0;
static #count = 0;
constructor(radius) {
this.radius = radius;// calling setter
Circle.#count++;
}
get area() {
return Math.PI * Math.pow(this.radius, 2);
}
set radius(value) {
if (typeof value === 'number' && value > 0) {
this.#radius = value;
} else {
throw 'The radius must be a positive number';
}
}
get radius() {
return this.#radius;
}
static hasRadius(circle) {
return #radius in circle;
}
static getCount() {
return Circle.#count;
}
}
console.log(Circle.getCount());
How it works.
First, add a private static field #count to the Circle class and initialize its value to zero:
static #count = 0;
Circle.#count++;
static getCount() {
return Circle.#count;
}
Finally, create three instances of the Circle class and output the count value to the
console:
Summary
Prefix the field name with # sign to make it private.
Private fields are accessible only inside the class, not from outside of the class or
subclasses.
Functions properties
Each function has two important properties: length and prototype .
The length property determines the number of named arguments specified in the
function declaration.
function add(x, y) {
return x + y;
}
console.log(add.length);// 2
console.log(add.prototype);// Object{}
The add() function accepts two arguments x and y . Therefore, the length property
returns two.
new.target
Typically, you call a function normally like this:
function add(x, y) {
console.log(new.target);
return x + y;
}
Output:
undefined
[Function: add]
By using the new.target , you can control how a function will be called.
For example, to prevent the add() function from being called with the new keyword as a
constructor, you can throw an error by checking the new.target like this:
function add(x, y) {
if (new.target) {
throw 'The add function cannot be called as a constructor';
}
return x + y;
}
Output:
In this example:
First, declare two objects cat and dog with two properties:
In this example, the first argument of the apply() method is the cat object. Therefore,
the this object in the say() function references the cat object.
Fourth, call say() function and pass the dog object:
In this example, the this in the say() function reference the dog object.
The call() method like the apply() method except for the way you pass the arguments
to the function:
let car = {
speed: 5,
start: function() {
console.log('Start with ' + this.speed + ' km/h');
}
};
let aircraft = {
speed: 10,
fly: function() {
console.log('Flying');
The aircraft has no start() method. To start an aircraft, you can use the bind() method
of the start() method of the car object:
In this statement, we change the this value inside the start() method of
the car object to the aircraft object. The bind() method returns a new function that
is assigned to the taxiing variable.
Now, you can call the start() method via the taxiing variable:
taxiing();
The following uses the call() method to call the start() method on
the aircraft object:
car.start.call(aircraft);
As you can see, the bind() method creates a new function that you can execute later
while the call() method executes the function immediately. This is the main difference
between the bind() and call() methods.
Technically, the aircraft object borrows the start() method of the car object via
the bind() , call() or apply() method.
For this reason, the bind() , call() , and apply() methods are also known as borrowing
functions.
Summary
A function also has three important methods: call() , apply() , and bind() .
To understand the closures, you need to know how the lexical scoping works first.
Lexical scoping
Lexical scoping defines the scope of a variable by the position of that variable declared
in the source code. For example:
function greeting() {
let message = 'Hi';
console.log(message + ' '+ name);
}
In this example:
If you try to access the message variable outside the greeting() function, you will get an
error.
So the JavaScript engine uses the scope to manage the variable accessibility.
According to lexical scoping, the scopes can be nested and the inner function can
access the variables declared in its outer scope. For example:
function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message);
JavaScript Closures 1
}
sayHi();
}
greeting();
The greeting() function creates a local variable named message and a function
named sayHi() .
The sayHi() is the inner function that is available only within the body of
the greeting() function.
The sayHi() function can access the variables of the outer function such as
the message variable of the greeting() function.
Inside the greeting() function, we call the sayHi() function to display the message Hi .
JavaScript closures
Let’s modify the greeting() function:
function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message);
}
return sayHi;
}
let hi = greeting();
hi();// still can access the message variable
Now, instead of executing the sayHi() function inside the greeting() function,
the greeting() function returns the sayHi() function object.
Note that functions are the first-class citizens in JavaScript, therefore, you can return a
function from another function.
Outside of the greeting() function, we assigned the hi variable the value returned by
the greeting() function, which is a reference of the sayHi() function.
Then we executed the sayHi() function using the reference of that function: hi() . If you
run the code, you will get the same effect as the one above.
JavaScript Closures 2
However, the interesting point here is that, normally, a local variable only exists during
the execution of the function.
It means that when the greeting() function has completed executing,
the message variable is no longer accessible.
In this case, we execute the hi() function that references the sayHi() function,
the message variable still exists.
The magic of this is closure. In other words, the sayHi() function is a closure.
A closure is a function that preserves the outer scope in its inner scope.
function greeting(message) {
return function(name){
return message + ' ' + name;
}
}
let sayHi = greeting('Hi');
let sayHello = greeting('Hello');
console.log(sayHi('John'));// Hi John
console.log(sayHello('John'));// Hello John
The greeting() function takes one argument named message and returns a function that
accepts a single argument called name .
The return function returns a greeting message that is the combination of
the message and name variables.
The greeting() function behaves like a function factory. It
creates sayHi() and sayHello() functions with the respective messages Hi and Hello .
The sayHi() and sayHello() are closures. They share the same function body but store
different scopes.
In the sayHi() closure, the message is Hi , while in the sayHello() closure
the message is Hello .
JavaScript Closures 3
Consider the following example:
Output
after 4 second(s):4
after 4 second(s):4
after 4 second(s):4
JavaScript Closures 4
Output
after 1 second(s):1
after 2 second(s):2
after 3 second(s):3
Output
after 1 second(s):1
after 2 second(s):2
after 3 second(s):3
Summary
Lexical scoping describes how the JavaScript engine uses the location of the
variable in the code to determine where that variable is available.
JavaScript Closures 5
JavaScript Arrow Functions
Introduction to JavaScript arrow functions
ES6 arrow functions provide you with an alternative way to write a shorter syntax
compared to the function expression.
The following example defines a function expression that returns the sum of two
numbers:
console.log(add(10, 20));// 30
The following example is equivalent to the above add() function expression but use an
arrow function instead:
In this example, the arrow function has one expression x + y so it returns the result of
the expression.
However, if you use the block syntax, you need to specify the return keyword:
The typeof operator returns function indicating the type of arrow function.
The arrow function is also an instance of the Function type as shown in the following
example:
=> expression
For example, to sort an array of numbers in the descending order, you use
the sort() method of the array object as follows:
p => { statements }
The following example uses an arrow function as an argument of the map() method that
transforms an array of strings into an array of the string’s lengths.
console.log(lengths);
Output:
[ 4, 3, 5 ]
() => { statements }
For example:
JavaScript allows you to have line breaks between parameters as shown in the
following example:
let multiply = (
x,
y
) =>
x * y;
10 + 20;
if (x === y) {
console.log('x equals y');
}
If you use an expression in the body of an arrow function, you don’t need to use the
curly braces.
The setColor() function expression returns an object that has the value property set to
the color argument.
If you use the following syntax to return an object literal from an arrow function, you will
get an error.
p => {object:literal}
Since both block and object literal use curly brackets, the JavasScript engine cannot
distinguish between a block and an object.
To fix this, you need to wrap the object literal in parentheses as follows:
1. First, in the arrow function, the this , arguments , super , new.target are lexical. It
means that the arrow function uses these variables (or constructs) from the
enclosing lexical scope.
function Car() {
this.speed = 0;
};
}
Inside the anonymous function of the setTimeout() function, the this.speed is undefined .
The reason is that the this of the anonymous function shadows the this of
the speedUp() method.
To fix this, you assign the this value to a variable that doesn’t shadow inside the
anonymous function as follows:
function Car() {
this.speed = 0;
};
}
Unlike an anonymous function, an arrow function captures the this value of the
enclosing context instead of creating its own this context. The following code should
work as expected:
function Car() {
this.speed = 0;
};
}
function show() {
return x => x + arguments[0];
}
The arrow function inside the showMe() function references the arguments object.
However, this arguments object belongs to the show() function, not the arrow function.
It is a good practice to use arrow functions for callbacks and closures because the
syntax of arrow functions is cleaner.
Summary
Use the (...args) => expression; to define an arrow function.
Use the (...args) => { statements } to define an arrow function that has multiple
statements.
1) Event handlers
Suppose that you have the following input text field:
And you want to show a greeting message when users type their usernames. The
following shows the <div> element that will display the greeting message:
<div id="greeting"></div>
Once users type their usernames, you capture the current value of the input and update
it to the <div> element:
However, when you execute the code, you will get the following message regardless of
whatever you type:
Hello undefined
It means that the this.value in the event handler always returns undefined .
username.addEventListener('keyup', function () {
input.textContent = 'Hello ' + this.value;
});
2) Object methods
See the following counter object:
const counter = {
count: 0,
next: () => ++this.count,
current: () => this.count
};
The counter object has two methods: current() and next() . The current() method
returns the current counter value and the next() method returns the next counter value.
The following shows the next counter value which should be 1:
console.log(counter.next());
const counter = {
count: 0,
next() {
return ++this.count;
},
current() {
return this.count;
}
};
console.log(counter.next());// 1
3) Prototype methods
See the following Counter object that uses the prototype pattern:
function Counter() {
this.count = 0;
}
Counter.prototype.next = () => {
return this.count;
};
Counter.prototype.current = () => {
return ++this.next;
}
The this value in these next() and current() methods reference the global object.
Since you want the this value inside the methods to reference the Counter object, you
need to use the regular functions instead:
Counter.prototype.next = function () {
return this.count;
};
Counter.prototype.current = function () {
return ++this.next;
}
function concat(separator) {
let args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}
Summary
An arrow function doesn’t have its own this value. Instead, it uses the this value
of the enclosing lexical scope. An arrow function also doesn’t have
the arguments object.
Avoid using the arrow function for event handlers, object methods, prototype
methods, and functions that use the arguments object.
function fn(a,b,...args) {
//...
}
The last parameter ( args ) is prefixed with the three-dots ( ... ). It’s called a rest
parameter ( ...args ).
All the arguments you pass to the function will map to the parameter list. In the syntax
above, the first argument maps to a , the second one maps to b , and the third, the
fourth, etc., will be stored in the rest parameter args as an array. For example:
[3,'A','B','C']
If you pass only the first two parameters, the rest parameter will be an empty array:
fn(1,2);
[]
function fn(a,...rest, b) {
// error
}
Error:
function sum(...args) {
let total = 0;
for (const a of args) {
total += a;
}
return total;
}
sum(1, 2, 3);
In this example, args in an array. Therefore, you could use the for..of loop to iterate
over its elements and sum them up.
Assuming that the caller of the sum() function may pass arguments with various kinds
of data types such as number, string, and boolean, and you want to calculate the total of
numbers only:
function sum(...args) {
return args
The following script uses the new sum() function to sum only numeric arguments:
Output:
30
Note that without the rest parameters, you have to use the arguments object of the
function.
However, the arguments object itself is not an instance of the Array type. Therefore, you
cannot use the filter() method directly. In ES5, you have to
use Array.prototype.filter.call() as follows:
function sum() {
return Array.prototype.filter
.call(arguments, function (e) {
return typeof e === 'number';
})
.reduce(function (prev, curr) {
return prev + curr;
});
}
As you see, the rest parameter makes the code more elegant. Suppose you need to
filter the arguments based on a specific type such as numbers, strings, boolean, and
null. The following function helps you to do it:
Output:
The combine() function is an arrow that takes an indefinite number of arguments and
concatenates these arguments.
Output:
[ 1, 2, 3 ]
By definition, a callback is a function that you pass into another function as an argument
for executing later.
The following defines a filter() function that accepts an array of numbers and returns
a new array of odd numbers:
function filter(numbers) {
let results = [];
for (const number of numbers) {
if (number % 2 != 0) {
results.push(number);
}
}
return results;
}
let numbers = [1, 2, 4, 7, 3, 5, 6];
console.log(filter(numbers));
How it works.
First, define the filter() function that accepts an array of numbers and returns a
new array of the odd numbers.
Second, define the numbers array that has both odd and even numbers.
Third, call the filter() function to get the odd numbers out of the numbers array
and output the result.
If you want to return an array that contains even numbers, you need to modify
the filter() function. To make the filter() function more generic and reusable, you
can:
First, extract the logic in the if block and wrap it in a separate function.
JavaScript Callbacks 1
Here’s the updated code:
function isOdd(number) {
return number % 2 != 0;
}
The result is the same. However, you can pass any function that accepts an argument
and returns a boolean value to the second argument of the filter() function.
For example, you can use the filter() function to return an array of even numbers like
this:
function isOdd(number) {
return number % 2 != 0;
}
function isEven(number) {
return number % 2 == 0;
}
console.log(filter(numbers, isOdd));
console.log(filter(numbers, isEven));
JavaScript Callbacks 2
By definition, the isOdd and isEven are callback functions or callbacks. Because
the filter() function accepts a function as an argument, it’s called a high-order
function.
A callback can be an anonymous function, which is a function without a name like this:
console.log(oddNumbers);
console.log(oddNumbers);
JavaScript Callbacks 3
Synchronous callbacks
A synchronous callback is executed during the execution of the high-order function that
uses the callback. The isOdd and isEven are examples of synchronous callbacks
because they execute during the execution of the filter() function.
Asynchronous callbacks
An asynchronous callback is executed after the execution of the high-order function that
uses the callback.
Asynchronicity means that if JavaScript has to wait for an operation to complete, it will
execute the rest of the code while waiting.
Note that JavaScript is a single-threaded programming language. It carries
asynchronous operations via the callback queue and event loop.
Suppose that you need to develop a script that downloads a picture from a remote
server and process it after the download completes:
function download(url) {
// ...
}
function process(picture) {
// ...
}
download(url);
process(picture);
However, downloading a picture from a remote server takes time depending on the
network speed and the size of the picture.
The following download() function uses the setTimeout() function to simulate the network
request:
function download(url) {
setTimeout(() => {
// script to download the picture here
console.log(`Downloading ${url} ...`);
},1000);
}
JavaScript Callbacks 4
And this code emulates the process() function:
function process(picture) {
console.log(`Processing ${picture}`);
}
download(url);
process(url);
Processing https://xyz.net/pic.jpg
Downloading https://xyz.net/pic.jpg ...
This is not what you expected because the process() function executes before
the download() function. The correct sequence should be:
To resolve this issue, you can pass the process() function to the download() function and
execute the process() function inside the download() function once the download
completes, like this:
function process(picture) {
console.log(`Processing ${picture}`);
JavaScript Callbacks 5
}
Output:
}, 1000);
}
Handling errors
The download() function assumes that everything works fine and does not consider any
exceptions. The following code introduces two callbacks: success and failure to handle
the success and failure cases respectively:
JavaScript Callbacks 6
console.log(`Downloading the picture from ${url} ...`);
!url ? failure(url) : success(url);
}, 1000);
}
download(
'',
(url) => console.log(`Processing the picture ${url}`),
(url) => console.log(`The '${url}' is not valid`)
);
Output:
JavaScript Callbacks 7
The script works perfectly fine.
However, this callback strategy does not scale well when the complexity grows
significantly.
Nesting many asynchronous functions inside callbacks is known as the pyramid of
doom or the callback hell:
asyncFunction(function(){
asyncFunction(function(){
asyncFunction(function(){
asyncFunction(function(){
asyncFunction(function(){
....
});
});
});
});
});
Summary
A callback is a function passed into another function as an argument to be executed
later.
JavaScript Callbacks 8
JavaScript Promises
Imagine that you’re a top singer, and fans ask day and night for your upcoming song.
To get some relief, you promise to send it to them when it’s published. You give your
fans a list. They can fill in their email addresses, so that when the song becomes
available, all subscribed parties instantly receive it. And even if something goes very
wrong, say, a fire in the studio, so that you can’t publish the song, they will still be
notified.
Everyone is happy: you, because the people don’t crowd you anymore, and fans,
because they won’t miss the song.
This is a real-life analogy for things we often have in programming:
1. A “producing code” that does something and takes time. For instance, some code
that loads the data over a network. That’s a “singer”.
2. A “consuming code” that wants the result of the “producing code” once it’s ready.
Many functions may need that result. These are the “fans”.
3. A promise is a special JavaScript object that links the “producing code” and the
“consuming code” together. In terms of our analogy: this is the “subscription list”.
The “producing code” takes whatever time it needs to produce the promised result,
and the “promise” makes that result available to all of the subscribed code when it’s
ready.
The analogy isn’t terribly accurate, because JavaScript promises are more complex
than a simple subscription list: they have additional features and limitations. But it’s fine
to begin with.
The constructor syntax for a promise object is:
The function passed to new Promise is called the executor. When new Promise is created,
the executor runs automatically. It contains the producing code which should eventually
JavaScript Promises 1
produce the result. In terms of the analogy above: the executor is the “singer”.
Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code
is only inside the executor.
When the executor obtains the result, be it soon or late, doesn’t matter, it should call
one of these callbacks:
So to summarize: the executor runs automatically and attempts to perform a job. When
it is finished with the attempt, it calls resolve if it was successful or reject if there was
an error.
The promise object returned by the new Promise constructor has these internal
properties:
// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve("done"), 1000);
});
2. The executor receives two arguments: resolve and reject . These functions are
pre-defined by the JavaScript engine, so we don’t need to create them. We should
JavaScript Promises 2
only call one of them when ready.
After one second of “processing”, the executor calls resolve("done") to produce the
result. This changes the state of the promise object:
The idea is that a job done by the executor may have only one result or an error.
Also, resolve / reject expect only one argument (or none) and will ignore additional
arguments.
Reject with Error objects
In case something goes wrong, the executor should call reject . That can be done with
any type of argument (just like resolve ). But it is recommended to use Error objects (or
objects that inherit from Error ). The reasoning for that will soon become apparent.
JavaScript Promises 3
Immediately calling resolve / reject
In practice, an executor usually does something asynchronously and
calls resolve / reject after some time, but it doesn’t have to. We also can
call resolve or reject immediately, like this:
For instance, this might happen when we start to do a job but then see that everything
has already been completed and cached.
That’s fine. We immediately have a resolved promise.
The state and result are internal
The properties state and result of the Promise object are internal. We can’t directly
access them. We can use the methods .then / .catch / .finally for that. They are
described below.
then
The most important, fundamental one is .then .
The syntax is:
promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);
JavaScript Promises 4
The first argument of .then is a function that runs when the promise is resolved and
receives the result.
The second argument of .then is a function that runs when the promise is rejected and
receives the error.
For instance, here’s a reaction to a successfully resolved promise:
If we’re interested only in successful completions, then we can provide only one function
argument to .then :
catch
JavaScript Promises 5
If we’re interested only in errors, then we can use null as the first
argument: .then(null, errorHandlingFunction) . Or we can
use .catch(errorHandlingFunction) , which is exactly the same:
Cleanup: finally
Just like there’s a finally clause in a regular try {...} catch {...} , there’s finally in
promises.
The call .finally(f) is similar to .then(f, f) in the sense that f runs always, when the
promise is settled: be it resolve or reject.
The idea of finally is to set up a handler for performing cleanup/finalizing after the
previous operations are complete.
E.g. stopping loading indicators, closing no longer needed connections, etc.
Think of it as a party finisher. No matter was a party good or bad, how many friends
were in it, we still need (or at least should) do a cleanup after it.
The code may look like this:
JavaScript Promises 6
1. A finally handler has no arguments. In finally we don’t know whether the
promise is successful or not. That’s all right, as our task is usually to perform
“general” finalizing procedures.
Please take a look at the example above: as you can see, the finally handler has
no arguments, and the promise outcome is handled by the next handler.
2. A finally handler “passes through” the result or error to the next suitable handler.
For instance, here the result is passed through finally to then :
As you can see, the value returned by the first promise is passed
through finally to the next then .
That’s very convenient, because finally is not meant to process a promise result.
As said, it’s a place to do generic cleanup, no matter what the outcome was.
And here’s an example of an error, for us to see how it’s passed
through finally to catch :
3. A finally handler also shouldn’t return anything. If it does, the returned value is
silently ignored.
The only exception to this rule is when a finally handler throws an error. Then this
error goes to the next handler, instead of any previous outcome.
To summarize:
A finally handler doesn’t get the outcome of the previous handler (it has no
arguments). This outcome is passed through instead, to the next suitable handler.
JavaScript Promises 7
If a finally handler returns something, it’s ignored.
When finally throws an error, then the execution goes to the nearest error handler.
These features are helpful and make things work just the right way if we
use finally how it’s supposed to be used: for generic cleanup procedures.
We can attach handlers to settled promises
If a promise is pending, .then/catch/finally handlers wait for its outcome.
Sometimes, it might be that a promise is already settled when we add a handler to it.
In such case, these handlers just run immediately:
Note that this makes promises more powerful than the real life “subscription list”
scenario. If the singer has already released their song and then a person signs up on
the subscription list, they probably won’t receive that song. Subscriptions in real life
must be done prior to the event.
Promises are more flexible. We can add handlers any time: if the result is already there,
they just execute.
Example: loadScript
Next, let’s see more practical examples of how promises can help us write
asynchronous code.
We’ve got the loadScript function for loading a script from the previous chapter.
Here’s the callback-based variant, just to remind us of it:
JavaScript Promises 8
document.head.append(script);
}
function loadScript(src) {
return new Promise(function(resolve, reject) {
let script = document.createElement('script');
script.src = src;
document.head.append(script);
});
}
Usage:
promise.then(
script => alert(`${script.src} is loaded!`),
error => alert(`Error: ${error.message}`)
);
Promises Callbacks
Promises allow us to do things in the natural We must have a callback function at our disposal
order. First, we run loadScript(script) , when calling loadScript(script, callback) . In other
and .then we write what to do with the words, we must know what to do with the
result. result before loadScript is called.
We can call .then on a Promise as many There can be only one callback.
times as we want. Each time, we’re adding
JavaScript Promises 9
a new “fan”, a new subscribing function, to
the “subscription list”. More about this in the
next chapter: Promises chaining.
JavaScript Promises 10
JavaScript async/await
Introduction to JavaScript async / await keywords
In the past, to deal with asynchronous operations, you often used the callback functions.
However, when you nest many callback functions, the code will be more difficult to
maintain. And you end up with a notorious issue which is known as the callback hell.
Suppose that you need to perform three asynchronous operations in the following
sequence:
3. Calculate the service cost based on the services from the server.
The following functions illustrate the three tasks. Note that we use
the setTimeout() function to simulate the asynchronous operation.
JavaScript async/await 1
getUser(100, (user) => {
getServices(user, (services) => {
getServiceCost(services, (cost) => {
console.log(`The service cost is ${cost}`);
});
});
});
Output:
To avoid this callback hell issue, ES6 introduced the promises that allow you to write
asynchronous code in more manageable ways.
First, you need to return a Promise in each function:
function getUser(userId) {
return new Promise((resolve, reject) => {
console.log('Get user from the database.');
setTimeout(() => {
resolve({
userId: userId,
username: 'john'
});
}, 1000);
})
}
function getServices(user) {
return new Promise((resolve, reject) => {
console.log(`Get services of ${user.username} from the API.`);
setTimeout(() => {
resolve(['Email', 'VPN', 'CDN']);
}, 2 * 1000);
});
}
function getServiceCost(services) {
return new Promise((resolve, reject) => {
console.log(`Calculate service costs of ${services}.`);
setTimeout(() => {
resolve(services.length * 100);
JavaScript async/await 2
}, 3 * 1000);
});
}
getUser(100)
.then(getServices)
.then(getServiceCost)
.then(console.log);
ES2017 introduced the async / await keywords that build on top of promises, allowing
you to write asynchronous code that looks more like synchronous code and is more
readable. Technically speaking, the async / await is syntactic sugar for promises.
If a function returns a Promise, you can place the await keyword in front of the function
call, like this:
The await will wait for the Promise returned from the f() to settle. The await keyword
can be used only inside the async functions.
The following defines an async function that calls the three asynchronous operations in
sequence:
showServiceCost();
As you can see, the asynchronous code now looks like the synchronous code.
Let’s dive in the async / await keywords.
JavaScript async/await 3
The async keyword allows you to define a function that handles asynchronous
operations.
To define an async function, you place the async keyword in front of the function
keyword as follows:
Asynchronous functions execute asynchronously via the event loop. It always returns
a Promise .
In this example, because the sayHi() function returns a Promise , you can consume it,
like this:
sayHi().then(console.log);
You can also explicitly return a Promise from the sayHi() function as shown in the
following code:
arrow functions:
JavaScript async/await 4
and methods of classes:
class Greeter {
async sayHi() {
return 'Hi';
}
}
In this example, the await keyword instructs the JavaScript engine to wait for
the sayHi() function to complete before displaying the message.
Note that if you use the await operator outside of an async function, you will get an
error.
Error handling
If a promise resolves, the await promise returns the result. However, when the promise
rejects, the await promise will throw an error as if there were a throw statement.
The following code:
JavaScript async/await 5
}
In the real scenario, it will take a while for the promise to throw an error.
You can catch the error by using the try...catch statement, the same way as a
regular throw statement:
It’s possible to catch errors caused by one or more await promise ‘s:
In this tutorial, you have learned how to use the JavaScript async / await keyword to
write asynchronous code that looks like synchronous code.
JavaScript async/await 6
JavaScript DOM
What is Document Object Model (DOM)
The Document Object Model (DOM) is an application programming interface (API) for
manipulating HTML documents.
The DOM represents an HTML document as a tree of nodes. The DOM provides
functions that allow you to add, remove, and modify parts of the document effectively.
Note that the DOM is cross-platform and language-independent way of manipulating
HTML and XML documents.
<html>
<head>
<title>JavaScript DOM</title>
</head>
<body>
<p>Hello DOM!</p>
</body>
</html>
JavaScript DOM 1
The following tree represents the above HTML document:
In this DOM tree, the document is the root node. The root node has one child node
which is the <html> element. The <html> element is called the document element.
Each document can have only one document element. In an HTML document,
the document element is the <html> element. Each markup can be represented by a
node in the tree.
Node Types
Each node in the DOM tree is identified by a node type. JavaScript uses integer
numbers to determine the node types. The following table illustrates the node type
constants:
JavaScript DOM 2
Node.ELEMENT_NODE 1
An Element node like <p> or <div> .
?> .
node.nodeType
You can compare the nodeType property with the above constants to determine the node
type. For example:
if (node.nodeType == Node.ELEMENT_NODE) {
// node is the element node
}
JavaScript DOM 3
if (node.nodeType == Node.ELEMENT_NODE) {
let name = node.nodeName;// tag name like <p>
}
JavaScript DOM 4
Note that the getElementById() and querySelector() return an object with
the Element type
while getElementsByTagName() or querySelectorAll() returns NodeList which is a collection
of nodes.
Node Relationships
Any node has relationships to other nodes in the DOM tree. The relationships are the
same as the ones described in a traditional family tree.
For example, <body> is a child node of the <html> node, and <html> is the parent of
the <body> node.
The <body> node is the sibling of the <head> node because they share the same
immediate parent, which is the <html> element.
The following picture illustrates the relationships between nodes:
Summary
JavaScript DOM 5
An HTML or XML document can be represented as a tree of nodes, like a traditional
family tree.
JavaScript DOM 6
getElementsByName
Introduction to JavaScript getElementsByName()
method
Every element on an HTML document may have a name attribute:
Unlike the id attribute, multiple HTML elements can share the same value of
the name attribute like this:
To get all elements with a specified name, you use the getElementsByName() method of
the document object:
The getElementsByName() accepts a name which is the value of the name attribute of
elements and returns a live NodeList of elements.
The return collection of elements is live. It means that the return elements are
automatically updated when elements with the same name
are inserted and/or removed from the document.
getElementsByName 1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript getElementsByName Demo</title>
</head>
<body>
<p>Please rate the service:</p>
<p>
<label for="very-poor">
<input type="radio" name="rate" value="Very poor" id="very-poor"> Very poor
</label>
<label for="poor">
<input type="radio" name="rate" value="Poor" id="poor"> Poor
</label>
<label for="ok">
<input type="radio" name="rate" value="OK" id="ok"> OK
</label>
<label for="good">
<input type="radio" name="rate" value="Good"> Good
</label>
<label for="very-good">
<input type="radio" name="rate" value="Very Good" id="very-good"> Very Good
</label>
</p>
<p>
<button id="btnRate">Submit</button>
</p>
<p id="output"></p>
<script>
let btn = document.getElementById('btnRate');
let output = document.getElementById('output');
btn.addEventListener('click', () => {
let rates = document.getElementsByName('rate');
rates.forEach((rate) => {
if (rate.checked) {
output.innerText = `You selected: ${rate.value}`;
}
});
});
</script>
</body>
</html>
getElementsByName 2
How it works:
First, select the submit button by its id btnRate using the getElementById() method.
Third, get all the radio buttons using the getElementsByName() and show the selected
value in the output element.
Notice that you will learn about events like click later. For now, you just need to focus
on the getElementsByName() method.
Summary
The getElementsByName() returns a live NodeList of elements with a specified name.
getElementsByName 3
getElementsByTagName
Introduction to JavaScript getElementsByTagName() method
The getElementsByTagName() is a method of the document object or a specific DOM
element.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript getElementsByTagName() Demo</title>
</head>
<body>
<h1>JavaScript getElementsByTagName() Demo</h1>
<h2>First heading</h2>
<p>This is the first paragraph.</p>
<h2>Second heading</h2>
<p>This is the second paragraph.</p>
<h2>Third heading</h2>
<p>This is the third paragraph.</p>
getElementsByTagName 1
<button id="btnCount">Count H2</button>
<script>
let btn = document.getElementById('btnCount');
btn.addEventListener('click', () => {
let headings = document.getElementsByTagName('h2');
alert(`The number of H2 tags: ${headings.length}`);
});
</script>
</body>
</html>
How it works:
getElementsByTagName 2
Finally, show the number of H2 tags using the alert() function.
Summary
The getElementsByTagName() is a method of the document or element object.
The getElementsByTagName() accepts a tag name and returns a list of elements with
the matching tag name.
getElementsByTagName 3
getElementsByClassName
Introduction to the getElementsByClassName() method
The getElementsByClassName() method returns an array-like of objects of the child
elements with a specified class name. The getElementsByClassName() method is available
on the document element or any other elements.
When calling the method on the document element, it searches the entire document and
returns the child elements of the document:
However, when calling the method on a specific element, it returns the descendants of
that specific element with the given class name:
The method returns the elements which is a live HTMLCollection of the matches
elements.
The names parameter is a string that represents one or more class names to match; To
use multiple class names, you separate them by space.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript getElementsByClassName</title>
</head>
getElementsByClassName 1
<body>
<header>
<nav>
<ul id="menu">
<li class="item">HTML</li>
<li class="item">CSS</li>
<li class="item highlight">JavaScript</li>
<li class="item">TypeScript</li>
</ul>
</nav>
<h1>getElementsByClassName Demo</h1>
</header>
<section>
<article>
<h2 class="secondary">Example 1</h2>
</article>
<article>
<h2 class="secondary">Example 2</h2>
</article>
</section>
</body>
</html>
console.log(data);
Output:
How it works:
First, select the <ul> element with the class name menu using
the getElementById() method.
getElementsByClassName 2
Then, select <li> elements, which are the descendants of the <ul> element, using
the getElementsByClassName() method.
console.log(data);
Output:
Summary
Use the JavaScript getElementsByClassName() method to select the child elements of
an element that has one or more give class names.
getElementsByClassName 3
querySelector
Introduction to JavaScript querySelector() and
querySelectorAll() methods
The querySelector() is a method of the Element interface. The querySelector() method
allows you to select the first element that matches one or more CSS selectors.
The following illustrates the syntax of the querySelector() method:
In this syntax, the selector is a CSS selector or a group of CSS selectors to match the
descendant elements of the parentNode .
If the selector is not valid CSS syntax, the method will raise a SyntaxError exception.
If no element matches the CSS selectors, the querySelector() returns null .
The querySelector() method is available on the document object or any Element object.
Besides the querySelector() , you can use the querySelectorAll() method to select all
elements that match a CSS selector or a group of CSS selectors:
The querySelectorAll() method returns a static NodeList of elements that match the CSS
selector. If no element matches, it returns an empty NodeList .
Note that the NodeList is an array-like object, not an array object. However, in modern
web browsers, you can use the forEach() method or the for...of loop.
To convert the NodeList to an array, you use the Array.from() method like this:
querySelector 1
Basic selectors
Suppose that you have the following HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<title>querySelector() Demo</title>
</head>
<body>
<header>
<div id="logo">
<img src="img/logo.jpg" alt="Logo" id="logo">
</div>
<nav class="primary-nav">
<ul>
<li class="menu-item current"><a href="#home">Home</a></li>
<li class="menu-item"><a href="#services">Services</a></li>
<li class="menu-item"><a href="#about">About</a></li>
<li class="menu-item"><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<h1>Welcome to the JS Dev Agency</h1>
<div class="container">
<section class="section-a">
<h2>UI/UX</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Autem placea
t, atque accusamus voluptas
laudantium facilis iure adipisci ab veritatis eos neque culpa id nostr
um tempora tempore minima.
Adipisci, obcaecati repellat.</p>
<button>Read More</button>
</section>
<section class="section-b">
<h2>PWA Development</h2>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni fugiat
similique illo nobis quibusdam
commodi aspernatur, tempora doloribus quod, consectetur deserunt, faci
lis natus optio. Iure
provident labore nihil in earum.</p>
<button>Read More</button>
</section>
<section class="section-c">
<h2>Mobile App Dev</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi eos culp
a laudantium consequatur ea!
Quibusdam, iure obcaecati. Adipisci deserunt, alias repellat eligendi
odit labore! Fugit iste sit
laborum debitis eos?</p>
querySelector 2
<button>Read More</button>
</section>
</div>
</main>
<script src="js/main.js"></script>
</body>
</html>
1) Universal selector
The universal selector is denoted by * that matches all elements of any type:
The following example uses the querySelector() selects the first element in the
document:
2) Type selector
To select elements by node name, you use the type selector e.g., a selects
all <a> elements:
elementName
querySelector 3
let heading2 = document.querySelectorAll('h2');
3) Class selector
To find the element with a given CSS class, you use the class selector syntax:
.className
The following example finds the first element with the menu-item class:
And the following example finds all elements with the menu class:
4) ID Selector
To select an element based on the value of its id, you use the id selector syntax:
#id
The following example finds the first element with the id #logo :
Since the id should be unique in the document, the querySelectorAll() is not relevant.
5) Attribute selector
To select all elements that have a given attribute, you use one of the following attribute
selector syntaxes:
querySelector 4
[attribute]
[attribute=value]
[attribute~=value]
[attribute|=value]
[attribute^=value]
[attribute$=value]
[attribute*$*=value]
The following example finds the first element with the attribute [autoplay] with any
value:
And the following example finds all elements that have [autoplay] attribute with any
value:
Grouping selectors
To group multiple selectors, you use the following syntax:
The selector list will match any element with one of the selectors in the group.
The following example finds all <div> and <p> elements:
Combinators
1) descendant combinator
To find descendants of a node, you use the space ( ) descendant combinator syntax:
querySelector 5
selector selector
For example p a will match all <a> elements inside the p element:
2) Child combinator
The > child combinator finds all elements that are direct children of the first element:
The following example finds all li elements that are directly inside a <ul> element:
To select all li elements that are directly inside a <ul> element with the class nav :
selector ~ selector
For example, p ~ a will match all <a> elements that follow the p element, immediately
or not:
querySelector 6
The + adjacent sibling combinator selects adjacent siblings:
selector + selector
Pseudo
1) Pseudo-classes
The : pseudo matches elements based on their states:
element:state
For example, the li:nth-child(2) selects the second <li> element in a list:
2) Pseudo-elements
The :: represent entities that are not included in the document.
For example, p::first-line matches the first line of all p elements:
Summary
querySelector 7
The querySelector() finds the first element that matches a CSS selector or a group
of CSS selectors.
The querySelectorAll() finds all elements that match a CSS selector or a group of
CSS selectors.
querySelector 8
JavaScript Get the Parent
Element parentNode
Introduction to parentNode attribute
To get the parent node of a specified node in the DOM tree, you use
the parentNode property:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript parentNode</title>
</head>
<body>
<div id="main">
<p class="note">This is a note!</p>
</div>
<script>
let note = document.querySelector('.note');
console.log(note.parentNode);
</script>
</body>
</html>
How it works:
First, select the element with the .note class by using the querySelector() method.
Summary
The node.parentNode returns the read-only parent node of a specified node or null if
it does not exist.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Get Child Elements</title>
</head>
<body>
<ul id="menu">
<li class="first">Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li class="last">About Us</li>
</ul>
</body>
</html>
If the parentElement does not have any child element, the firstChild returns null .
The firstChild property returns a child node which can be any node type such as an
element node, a text node, or a comment node. The following script shows the first child
of the #menu element:
#text
The Console window show #text because a text node is inserted to maintain the
whitespace between the openning <ul> and <li> tags. This whitespace creates
a #text node.
Note that any whitespace such as a single space, multiple spaces, returns, and tabs will
create a #text node. To remove the #text node, you can remove the whitespaces as
follows:
Or to get the first child with the Element node only, you can use
the firstElementChild property:
The following code returns the first list item which is the first child element of the menu:
Output:
<li class="first">Home</li>
In this example:
Second, get the first child element by using the firstElementChild property.
In case the parentElement does not have any child element, the lastChild returns null .
Similar to the the firstChild property, the lastChild property returns the first element
node, text node, or comment node. If you want to select only the last child element with
the element node type, you use the lastElementChild property:
The following code returns the list item which is the last child element of the menu:
Output:
The childNodes property returns all child elements with any node type. To get the child
element with only the element node type, you use the children property:
The following example selects all child elements of the element with the Id main :
Output:
Summary
The firstChild and lastChild return the first and last child of a node, which can be
any node type including text node, comment node, and element node.
The firstElementChild and lastElementChild return the first and last child Element
node.
The childNodes returns a live NodeList of all child nodes of any node type of a
specified node. The children return all child Element nodes of a specified node.
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li>About Us</li>
</ul>
The nextElementSibling returns null if the specified element is the last one in the list.
The following example uses the nextElementSibling property to get the next sibling of the
list item that has the current class:
console.log(nextSibling);
Output:
<li>Careers</li>
In this example:
First, select the list item whose class is current using the querySelector() .
JavaScript Siblings 1
Second, get the next sibling of that list item using the nextElementSibling property.
To get all the next siblings of an element, you can use the following code:
while(nextSibling) {
console.log(nextSibling);
nextSibling = nextSibling.nextElementSibling;
}
The previousElementSibling property returns null if the current element is the first one in
the list.
The following example uses the previousElementSibling property to get the previous
siblings of the list item that has the current class:
console.log(prevSiblings);
And the following example selects all the previous siblings of the list item that has
the current class:
JavaScript Siblings 2
Get all siblings of an element
To get all siblings of an element, we’ll use the logic:
First, select the parent of the element whose siblings you want to find.
Finally, repeat the 3rd and 4th steps until there are no siblings left. In case the
sibling is the original element, skip the 3rd step.
if(!e.parentNode) {
return siblings;
}
// first child of the parent node
// collecting siblings
while (sibling) {
if (sibling.nodeType === 1 && sibling !== e) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Siblings</title>
JavaScript Siblings 3
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li class="current">Customer Support</li>
<li>Careers</li>
<li>Investors</li>
<li>News</li>
<li>About Us</li>
</ul>
<script>
let getSiblings = function (e) {
// for collecting siblings
let siblings = [];
// if no parent, return no sibling
if(!e.parentNode) {
return siblings;
}
// first child of the parent node
let sibling = e.parentNode.firstChild;
// collecting siblings
while (sibling) {
if (sibling.nodeType === 1 && sibling !== e) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
Output:
Summary
The nextElementSibling returns the next sibling of an element or null if the element
is the last one in the list.
JavaScript Siblings 4
The previousElementSibling returns the previous sibling of an element or null if the
element is the first one in the list.
To get all siblings of an element, you can use a helper function that utilizes
the nextElementSibling property.
JavaScript Siblings 5
CreateElement
To create an HTML element, you use the document.createElement() method:
The document.createElement() accepts an HTML tag name and returns a new Node with
the Element type.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>
</body>
</html>
The following example uses the document.createElement() to create a new <div> element:
To attach the div to the document, you use the appendChild() method:
document.body.appendChild(div);
CreateElement 1
Put it all together:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>
<script>
let div = document.createElement('div');
div.id = 'content';
div.innerHTML = '<p>CreateElement example</p>';
document.body.appendChild(div);
</script>
</body>
</html>
document.body.appendChild(div);
document.body.appendChild(div);
CreateElement 2
To add a piece of text to a <div> , you can use the innerHTML property as the above
example, or create a new Text node and append it to the div :
let h2 = document.createElement('h2');
h2.textContent = 'Add h2 element to the div';
div.appendChild(h2);
document.body.appendChild(div);
<ul id="menu"><li>Home</li></ul>
CreateElement 3
let li = document.createElement('li');
li.textContent = 'Products';
menu.appendChild(li);
li = document.createElement('li');
li.textContent = 'About Us';
Output:
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
You can first create a new helper function that loads a JavaScript file from an URL:
function loadJS(url) {
let script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
CreateElement 4
And then use the helper function to load the /lib.js file:
loadJS('/lib.js');
function loadJSAsync(url) {
let script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
}
Summary
The document.createElement() creates a new HTML element.
CreateElement 5
appendChild
Introduction to the JavaScript appendChild() method
The appendChild() is a method of the Node interface. The appendChild() method allows
you to add a node to the end of the list of child nodes of a specified parent node.
parentNode.appendChild(childNode);
In this method, the childNode is the node to append to the given parent node.
The appendChild() returns the appended child.
<ul id="menu"></ul>
The following example uses the appendChild() method to add three list items to
the <ul> element:
function createMenuItem(name) {
let li = document.createElement('li');
li.textContent = name;
return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
appendChild 1
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));
How it works:
First, the createMenuItem() function create a new list item element with a specified
name by using the createElement() method.
Second, select the <ul> element with id menu using the querySelector() method.
Third, call the createMenuItem() function to create a new menu item and use
the appendChild() method to append the menu item to the <ul> element
Output:
<ul id="menu">
<li>Home</li>
<li>Services</li>
<li>About Us</li>
</ul>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript appendChild() Demo</title>
</head>
<body>
<ul id="menu">
</ul>
<script>
function createMenuItem(name) {
let li = document.createElement('li');
li.textContent = name;
return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
appendChild 2
menu.appendChild(createMenuItem('About Us'));
</script>
</body>
</html>
<ul id="first-list">
<li>Everest</li>
<li>Fuji</li>
<li>Kilimanjaro</li>
</ul>
<ul id="second-list">
<li>Karakoram Range</li>
<li>Denali</li>
<li>Mont Blanc</li>
</ul>
The following example uses the appendChild() to move the first child element from the
first list to the second list:
How it works:
First, select the first element by its id ( first-list ) using the querySelector() method.
Second, select the first child element from the first list.
appendChild 3
Finally, append the first child element from the first list to the second list using
the appendChild() method.
Summary
Use appendChild() method to add a node to the end of the list of child nodes of a
specified parent node.
The appendChild() can be used to move an existing child node to the new position
within the document.
appendChild 4
JavaScript textContent
Reading textContent from a node
To get the text content of a node and its descendants, you use the textContent property:
<div id="note">
JavaScript textContent Demo!
<span style="display:none">Hidden Text!</span>
<!-- my comment -->
</div>
The following example uses the textContent property to get the text of
the <div> element:
How it works.
First, select the div element with the id note by using the getElementById() method.
Then, display the text of the node by accessing the textContent property.
Output:
As you can see clearly from the output, the textContent property returns the
concatenation of the textContent of every child node, excluding comments (and also
processing instructions).
JavaScript textContent 1
textContent vs. innerText
On the other hand, the innerText takes the CSS style into account and returns only
human-readable text. For example:
Output:
As you can see, the hidden text and comments are not returned.
Since the innerText property uses the up-to-date CSS to compute the text, accessing it
will trigger a reflow, which is computationally expensive.
A reflow occurs when a web browser needs to process and draw parts or all of a
webpage again.
node.textContent = newText;
When you set textContent on a node, all the node’s children will be removed and
replaced by a single text node with the newText value. For example:
Summary
Use the textContent property to return the concatenation of the textContent of every
child node. You can use it to set a text for a node.
JavaScript textContent 2
The innerText returns the human-readable text that takes CSS into account.
JavaScript textContent 3
JavaScript innerHTML
The innerHTML is a property of the Element that allows you to get or set the HTML
markup contained within the element:
When you read the innerHTML of an element, the web browser has to serialize the HTML
fragment of the element’s descendants.
<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
The following example uses the innerHTML property to get the content of
the <ul> element:
How it works:
First, select the <ul> element by its id ( menu ) using the getElementById() method.
JavaScript innerHTML 1
Then, get the HTML content of the <ul> element using the innerHTML .
Output:
<li>Home</li>
<li>Services</li>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript innerHTML</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
<script>
let menu = document.getElementById('menu');
console.log(menu.innerHTML);
</script>
</body>
</html>
Output:
<li>Home</li>
<li>Services</li>
<li>About Us</li>
JavaScript innerHTML 2
How it works.
First, get the <ul> element with the id menu using the getElementById() method.
Second, create a new <li> element and add it to the <ul> element using
the createElement() and appendChild() methods.
Third, get the HTML of the <ul> element using the innerHTML property of the <ul>
element. The contents of the <ul> element include the initial content and the
dynamic content created dynamically by JavaScript.
element.innerHTML = newHTML;
The setting will replace the existing content of an element with the new content.
For example, you can remove the entire contents of the document by clearing the
contents of the document.body element:
document.body.innerHTML = '';
⚠ Security Risk
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
Suppose you have the following index.html document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS innerHTML example</title>
</head>
<body>
<div id="main"></div>
<script src="app.js"></script>
JavaScript innerHTML 3
</body>
</html>
main.innerHTML = scriptHTML;
In this example, the alert() inside the <script> tag will not execute.
However, if you change the source code of the app.js to the following:
In this example, the image with the src 1 will not be loaded successfully. Therefore, the
on error will execute that runs the alert().
Instead of having a simple alert(), hackers may include malicious code, the users who
open the webpage will be vulnerable.
Therefore, you should not set the contents that you have no control to the innerHTML or
you will face a potential security risk.
If you want to insert plain text into the document, you can use the textContent property
instead of the innerHTML . The textContent will not be parsed as the HTML but as the raw
text.
Summary
Use innerHTML property of an element to get or set HTML contained within the
element.
JavaScript innerHTML 4
The innerHTML property returns the current HTML source of the element, including
any change that has been made since the page was loaded.
Do not use innerHTML to set new contents that you have no control to avoid a
security risk.
JavaScript innerHTML 5
JavaScript innerHTML vs
createElement
#1) createElement is more performant
Suppose that you have a div element with the class container:
<div class="container"></div>
You can new elements to the div element by creating an element and appending it:
let p = document.createElement('p');
p.textContent = 'JS DOM';
div.appendChild(p);
You can also manipulate an element’s HTML directly using innerHTML like this:
Using innerHTML is cleaner and shorter when you want to add attributes to the element:
However, using the innerHTML causes the web browsers to reparse and recreate all
DOM nodes inside the div element. Therefore, it is less efficient than creating a new
element and appending to the div. In other words, creating a new element and
appending it to the DOM tree provides better performance than the innerHTML .
This code results in recalculation of styles, painting, and layout every iteration. This is
not very efficient.
To overcome this, you typically use a DocumentFragment to compose DOM nodes and
append it to the DOM tree:
div.appendChild(fragment);
In this example, we composed the DOM nodes by using the DocumentFragment object and
append the fragment to the active DOM tree once at the end.
If you make changes to the document fragment, it doesn’t affect the document or incurs
any performance.
Typically, you use the DocumentFragment to compose DOM nodes and append or insert it
to the active DOM tree using appendChild() or insertBefore() method.
To create a new document fragment, you use the DocumentFragment constructor like this:
This DocumentFragment inherits the methods of its parent, Node , and also implements
those of the ParentNode interface such as querySelector() and querySelectorAll() .
JavaScript DocumentFragment 1
JavaScript DocumentFragment example
Suppose that you have a <ul> element with the id language :
<ul id="language"></ul>
The following code creates a list of <li> elements ( <li> ) and append each to
the <ul> element using the DocumentFragment :
langEl.appendChild(fragment);
How it works:
JavaScript DocumentFragment 2
First, select the <ul> element by its id using the querySelector() method.
Third, for each element in the languages array, create a list item element, assign the
list item’s innerHTML to the language , and append all the newly created list items to
the document fragment.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DocumentFragment Demo</title>
</head>
<body>
<ul id="language"></ul>
<script>
let languages = ['JS', 'TypeScript', 'Elm', 'Dart', 'Scala'];
languages.forEach((language) => {
let li = document.createElement('li');
li.innerHTML = language;
fragment.appendChild(li);
})
langEl.appendChild(fragment);
</script>
</body>
</html>
Summary
Use the DocumentFragment to compose DOM nodes before updating them to the
active DOM tree to get better performance.
JavaScript DocumentFragment 3
Working with Attributes
Understanding Relationships Between
HTML Attributes & DOM Object’s Properties
When the web browser loads an HTML page, it generates the corresponding DOM
objects based on the DOM nodes of the document.
For example, if a page contains the following input element:
In other words, the web browser will automatically convert attributes of HTML elements
to properties of DOM objects.
However, the web browser only converts the standard attributes to the DOM object’s
properties. The standard attributes of an element are listed on the element’s
specification.
Attribute methods
To access both standard and non-standard attributes, you use the following methods:
element.attributes
The element.attributes property provides a live collection of attributes available on a
specific element. For example:
Output:
type = text
id = username
secure = true
Attribute-property synchronization
When a standard attribute changes, the corresponding property is auto-updated with
some exceptions and vice versa.
The following example illustrates the change of the tabindex attribute is propagated to
the tabIndex property and vice versa:
The following example shows when the value attribute changes, it reflects in
the value property, but not the other way around:
input.value = 'admin';
console.log(input.getAttribute('value'));// guest
console.dir(input.style);
Output:
[object CSSStyleDeclaration]
The following shows how to access the data-* attributes via the dataset property:
Output:
[object DOMStringMap] {
progress: "pending",
value: "10%"
}
Summary
Attributes are specified in HTML elements.
element.style
The style property returns the read-only CSSStyleDeclaration object that contains a list
of CSS properties. For example, to set the color of an element to red , you use the
following code:
element.style.color = 'red';
If the CSS property contains hyphens ( - ) for example -webkit-text-stroke you can use
the array-like notation ( [] ) to access the property:
element.style.['-webkit-text-stock'] = 'unset';
CSS JavaScript
background background
background-attachment backgroundAttachment
background-color backgroundColor
background-image backgroundImage
background-position backgroundPosition
background-repeat backgroundRepeat
border border
border-bottom borderBottom
border-bottom-color borderBottomColor
JavaScript Style 1
border-bottom-style borderBottomStyle
border-bottom-width borderBottomWidth
border-color borderColor
border-left borderLeft
border-left-color borderLeftColor
border-left-style borderLeftStyle
border-left-width borderLeftWidth
border-right borderRight
border-right-color borderRightColor
border-right-style borderRightStyle
border-right-width borderRightWidth
border-style borderStyle
border-top borderTop
border-top-color borderTopColor
border-top-style borderTopStyle
border-top-width borderTopWidth
border-width borderWidth
clear clear
clip clip
color color
cursor cursor
display display
filter filter
float cssFloat
font font
font-family fontFamily
font-size fontSize
font-variant fontVariant
font-weight fontWeight
height height
JavaScript Style 2
left left
letter-spacing letterSpacing
line-height lineHeight
list-style listStyle
list-style-image listStyleImage
list-style-position listStylePosition
list-style-type listStyleType
margin margin
margin-bottom marginBottom
margin-left marginLeft
margin-right marginRight
margin-top marginTop
overflow overflow
padding padding
padding-bottom paddingBottom
padding-left paddingLeft
padding-right paddingRight
padding-top paddingTop
page-break-after pageBreakAfter
page-break-before pageBreakBefore
position position
stroke-dasharray strokeDasharray
stroke-dashoffset strokeDashoffset
stroke-width strokeWidth
text-align textAlign
text-decoration textDecoration
text-indent textIndent
text-transform textTransform
top top
JavaScript Style 3
vertical-align verticalAlign
visibility visibility
width width
z-index zIndex
To completely override the existing inline style, you set the cssText property of
the style object. For example:
element.style.cssText = 'color:red;background-color:yellow';
element.setAttribute('style','color:red;background-color:yellow');
Once setting the inline style, you can modify one or more CSS properties:
element.style.color = 'blue';
If you do not want to completely overwrite the existing CSS properties, you can
concatenate the new CSS property to the cssText as follows:
element.style.cssText += 'color:red;background-color:yellow';
In this case, the += operator appends the new style string to the existing one.
The following css() helper function is used to set multiple styles for an element from an
object of key-value pairs:
You can use this css() function to set multiple styles for an element with the
id #content as follows:
JavaScript Style 4
let content = document.querySelector('#content');
css(content, { background: 'yellow', border: 'solid 1px red'});
The following example uses the style object to set the CSS properties of a paragraph
with the id content :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Style Demo</title>
</head>
<body>
<p id="content">JavaScript Setting Style Demo!</p>
<script>
let p = document.querySelector('#content');
p.style.color = 'red';
p.style.fontWeight = 'bold';
</script>
</body>
</html>
How it works:
Then, set the color and font-weight properties of the paragraph by setting
the color and fontWeight properties of the style object.
Summary
JavaScript Style 5
Use the properties of element.style object to set the inline CSS properties for the
HTML element.
JavaScript Style 6
Working with Events
Introduction to JavaScript events
An event is an action that occurs in the web browser, which the web browser feedbacks
to you so that you can respond to it.
For example, when users click a button on a webpage, you may want to respond to
this click event by displaying a dialog box.
Each event may have an event handler which is a block of code that will execute when
the event occurs.
An event handler is also known as an event listener. It listens to the event and executes
when the event occurs.
To define the code that will be executed when the button is clicked, you need to register
an event handler using the addEventListener() method:
function display() {
alert('It was clicked!');
}
btn.addEventListener('click',display);
How it works.
First, select the button with the id btn by using the querySelector() method.
Finally, register an event handler using the addEventListener() so that when users
click the button, the display() function will be executed.
btn.addEventListener('click',function() {
alert('It was clicked!');
});
Event flow
Assuming that you have the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>JS Event Demo</title>
</head>
<body>
<div id="container">
<button id='btn'>Click Me!</button>
</div>
</body>
When you click the button, you’re clicking not only the button but also the button’s
container, the div , and the whole webpage.
Event flow explains the order in which events are received on the page from the
element where the event occurs and propagated through the DOM tree.
There are two main event models: event bubbling and event capturing.
Event bubbling
In the event bubbling model, an event starts at the most specific element and then flows
upward toward the least specific element (the document or even window ).
When you click the button, the click event occurs in the following order:
1. button
3. body
5. document
The click event first occurs on the button which is the element that was clicked. Then
the click event goes up the DOM tree, firing on each node along its way until it reaches
the document object.
The following picture illustrates the event bubbling effect when users click the button:
Note that modern web browsers bubble the event up to the window object.
Event capturing
In the event capturing model, an event starts at the least specific element and flows
downward toward the most specific element.
When you click the button, the click event occurs in the following order:
1. document
2. html
3. body
5. button
First, event capturing occurs, which provides the opportunity to intercept the event.
Finally, event bubbling occurs, which allows a final response to the event.
The following picture illustrates the DOM Level 2 event model when users click the
button:
btn.addEventListener('click', function(event) {
console.log(event.type);
});
Output:
'click'
The following table shows the most commonly-used properties and methods of
the event object:
Property /
Description
Method
bubbles true if the event bubbles
cancel the default behavior for the event. This method is only effective if
preventDefault()
the cancelable property is true
cancel any further event capturing or bubbling. This method only can be used
stopPropagation()
if the bubbles property is true.
target the target element of the event
Note that the event object is only accessible inside the event handler. Once all the
event handlers have been executed, the event object is automatically destroyed.
preventDefault()
To prevent the default behavior of an event, you use the preventDefault() method.
For example, when you click a link, the browser navigates you to the URL specified in
the href attribute:
However, you can prevent this behavior by using the preventDefault() method of
the event object:
link.addEventListener('click',function(event) {
console.log('clicked');
event.preventDefault();
});
Note that the preventDefault() method does not stop the event from bubbling up the
DOM. And an event can be canceled when its cancelable property is true .
btn.addEventListener('click', function(event) {
console.log('The button was clicked!');
event.stopPropagation();
});
document.body.addEventListener('click',function(event) {
console.log('The body was clicked!');
});
Without the stopPropagation() method, you would see two messages on the Console
window.
However, the click event never reaches the body because the stopPropagation() was
called on the click event handler of the button.
onmouseout The user moves the mouse away from an HTML element
Summary
An event is an action that occurs in the web browser e.g., a mouse click.
Event flow has two main models: event bubbling and event capturing.
Use preventDefault() method to prevent the default behavior of an event, but does
not stop the event flow.
Use stopPropagation() method to stop the flow of an event through the DOM tree,
but does not cancel the browser default behavior.