[go: up one dir, main page]

0% found this document useful (0 votes)
4K views733 pages

Master Frontend Ebook

front

Uploaded by

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

Master Frontend Ebook

front

Uploaded by

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

Index Of Master Frontend: Zero

to Hero
1. Matser Frontend Development: Zero to Hero

HTML Topic
Quick Learning
1. Task: Create Your Personal Web Page

2. Getting Started with HTML

3. Working with Images

4. Structuring Content with Lists

5. Tables and Data Representation

6. Building Forms for User Input

Deep Knowledge
1. HTML Page Structure

2. HTML Head

3. HTML Elements and Tags

4. HTML Attributes

5. HTML Headings

6. HTML Paragraphs

7. HTML Styles

8. HTML Formatting

Index Of Master Frontend: Zero to Hero 1


9. HTML Comments

10. HTML Links

11. HTML Images

12. HTML Lists

13. HTML Iframes

14. HTML Forms

15. HTML Tables

16. HTML Frames

CSS Topic
1. What do you need before learning CSS?

2. CSS SELECTOR

3. EXAMPLE

4. CSS BOX MODEL

5. CSS Comments

6. CSS Colors

7. CSS Background Color

8. CSS Text Color

9. CSS Border Color

10. CSS Backgrounds

11. CSS Borders

12. CSS Margins

13. CSS Padding

14. CSS Height, Width, and Max-width

15. CSS Outline

Index Of Master Frontend: Zero to Hero 2


16. CSS Text

17. CSS Font Style, Font Size & Shorthand

18. Font Pairing Rules

19. CSS Links

20. CSS Display and Position

21. CSS Lists

22. CSS Tables

23. CSS Pseudo-classes and Combinators

24. CSS Flexbox

25. CSS Grid

26. Difference between Flexbox and Grid

27. CSS Responsive Web Design

28. CSS Media Queries

29. CSS Responsive Images

30. CSS Fluid Layouts

31. CSS Transforms, Transitions,and Animations

JavaScript Topic
1. Web Development Tools

2. JavaScript Hello World

3. JavaScript Syntax

4. JavaScript Variables

5. JavaScript Data Types

6. JavaScript Numbers

7. JavaScript Numeric Separator

Index Of Master Frontend: Zero to Hero 3


8. Quick Look at Octal and Binary Literals in

9. ES6

10. JavaScript Boolean type

11. JavaScript string

12. JavaScript Objects

13. JavaScript Primitive vs. Reference Values

14. JavaScript Arrays

15. JavaScript Arithmetic Operators

16. JavaScript Remainder Operator

17. JavaScript Assignment Operators

18. JavaScript Unary Operators Explained

19. JavaScript Comparison Operators

20. JavaScript Logical Operators

21. JavaScript Logical Assignment Operators

22. JavaScript Nullish Coalescing Operator

23. JavaScript Exponentiation Operator

24. JavaScript if

25. JavaScript if else

26. JavaScript if else if

27. JavaScript Ternary Operator

28. JavaScript Object Spread

29. JavaScript switch case

30. JavaScript while Loop

31. JavaScript do…while Loop

32. JavaScript for Loop

33. JavaScript break

Index Of Master Frontend: Zero to Hero 4


34. JavaScript continue

35. JavaScript Comma Operator

36. JavaScript Functions

37. JavaScript Functions are First-Class Citizens

38. JavaScript Anonymous Functions

39. Understanding JavaScript Pass-By-Value

40. JavaScript Recursive Function

41. JavaScript Default Parameters

42. JavaScript Object Methods

43. JavaScript Constructor Function

44. JavaScript this Keyword

45. JavaScript globalThis

46. JavaScript Object Properties

47. JavaScript for…in Loop

48. JavaScript Object.values()

49. JavaScript Object.entries()

50. JavaScript Object.assign()

51. JavaScript Object.is()

52. Object Literal Syntax Extensions in ES6

53. JavaScript Class

54. JavaScript Getters and Setters

55. JavaScript Class Expressions

56. JavaScript Computed Property

57. JavaScript Inheritance Using extends & super

58. JavaScript new.target Metaproperty

59. JavaScript Static Methods

Index Of Master Frontend: Zero to Hero 5


60. JavaScript Static Properties

61. JavaScript Private Fields

62. JavaScript Function Type

63. JavaScript Closures

64. JavaScript Arrow Functions

65. When You Should Not Use Arrow Functions

66. JavaScript Rest Parameters

67. JavaScript Callbacks

68. JavaScript Promises

69. JavaScript async/await

How JavaScript Work?


1. getElementById

2. getElementsByName

3. getElementsByTagName

4. getElementsByClassName

5. querySelector

6. JavaScript Get the Parent Element

7. parentNode

8. Getting Child Elements

9. JavaScript Siblings

10. CreateElement

11. appendChild

12. JavaScript textContent

13. JavaScript innerHTML

Index Of Master Frontend: Zero to Hero 6


14. JavaScript innerHTML vs createElement

15. JavaScript DocumentFragment

16. Working with Attributes

17. JavaScript Style

18. Working with Events

Bootstrap Topic

1. build responsive and mobile-first websites.

2. Why Learn Bootstrap?

3. Getting Started

4. Bootstrap Containers

5. Bootstrap Grid System

6. Bootstrap Typography

7. Bootstrap Tables

8. Bootstrap Lists

9. bootstrap 5 4

10. Bootstrap Forms

11. Bootstrap Buttons

12. Bootstrap Images

13. Bootstrap Cards

14. Bootstrap Media Objects

15. Bootstrap Icons

16. Bootstrap Navbar

17. Bootstrap Modals

18. Bootstrap Dropdowns

Index Of Master Frontend: Zero to Hero 7


19. Bootstrap Alerts

20. Bootstrap Carousel

21. Bootstrap 5 Examples

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

Index Of Master Frontend: Zero to Hero 8


HTML
Introduction to HTML
HTML stands for Hypertext Markup Language. It is the standard markup language used
for creating web pages and web applications. HTML is a combination of text, images,
and other multimedia resources that are used to create a web page.
HTML is based on a set of tags that are used to define the different elements of a web
page, such as headings, paragraphs, links, images, tables, and forms. These tags are
enclosed in angle brackets (< >) and are placed within the content of the web page.
HTML is a client-side language, which means that it is processed by the web browser
on the user's computer. This allows for a great deal of flexibility in the design and layout
of web pages, as well as the ability to create interactive elements such as forms and
animations.

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.

A Simple Definition of HTML


HTML is a special code that tells a computer how to make a website look. It's like a
recipe that helps the computer put all the pictures, text, and buttons in the right place.
Just like how a recipe helps you bake a cake, HTML helps you make a website!
When you look at a website on your computer or phone, you see pictures, words, and
buttons. HTML is the code that makes all of those things show up in the right place.
Think of it like building with blocks. HTML has different kinds of blocks, and each block
has a different job. Some blocks make words, some blocks make pictures, and some
blocks make buttons. When you put all the blocks together in the right way, you get a
website!
So, when you use HTML, you're like a builder building a really cool website with blocks.
It's kind of like a puzzle, and the more you learn about HTML, the better you'll be at
building awesome websites!

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.

2.1 Basic Document Structure:


Every HTML document follows a basic structure. Let's start by creating our first HTML
document. Open a text editor (like Notepad) and type the following code:

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

Getting Started with HTML 1


Save the file with a .html extension (e.g., index.html ). Now, open the saved file in a
web browser. You will see your first web page displayed with a heading and a
paragraph.
Explanation:

<!DOCTYPE html> : This is the doctype declaration that tells the browser we are using
HTML5.

<html> : The <html> element is the root element of an HTML document.

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

<p> : The <p> element represents a paragraph of text.

2.2 Adding Content to the Page:


HTML allows us to add various types of content to our web pages. Let's add some more
content to our web page example:

<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 Favorite Games</h3>


<ul>
<li>Minecraft</li>
<li>Roblox</li>

Getting Started with HTML 2


<li>Fortnite</li>
</ul>

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

<h2> : The <h2> element represents a subheading.

<h3> : The <h3> element represents a subheading of a lower level.

<ul> : The <ul> element creates an unordered list.

<ol> : The <ol> element creates an ordered (numbered) list.

<li> : The <li> element represents a list item within <ul> or <ol> .

2.3 Formatting Text:

Getting Started with HTML 3


HTML provides various tags to format and style text. Let's add some formatted text to
our web page example:

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

<h3>My Favorite Games</h3>


<ul>
<li><strong>Minecraft</strong></li>
<li><em>Roblox</em></li>
<li><u>Fortnite</u></li>
</ul>
</body>

Save the changes and refresh your web page. You will see the text formatted with bold,
italic, and underlined styles.
Explanation:

<strong>: The <strong> element represents important or emphasized text (typically


rendered in bold).

<em> : The <em> element represents text emphasized or styled in italics.

Getting Started with HTML 4


<u> : The <u> element represents underlined text.

2.4 Creating Links:


One of the key features of HTML is the ability to create links between web pages. Links
allow users to navigate between different pages on the Internet. Let's learn how to
create links in HTML:

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

<a href="<https://www.example.com>">My Favorite Website</a>


</body>

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:

<a> : The <a> element is used to create links in HTML.

href="..." : The attribute specifies the URL or destination of the link. Replace
href

"<https://www.example.com>" with the desired URL.

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:

<a href="about.html">About Me</a>

Getting Started with HTML 5


Save the changes and create a new HTML file called "about.html" in the same directory
as your first page. Add some content to the "about.html" file, such as a heading and a
paragraph.
Now, when you click the "About Me" link, it will take you to the "about.html" page.
That's it! You have learned how to create links in HTML. Links play a crucial role in
connecting web pages and allowing users to navigate through the vast web. In the next
chapter, we will explore more HTML features.
Encourage the young readers to experiment with creating different links, such as linking
to specific sections within a page using anchor tags, or creating links that open in a new
window using the target="_blank" attribute. This will help them grasp the versatility and
power of HTML links.

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.

Getting Started with HTML 6


Task: Create Your Personal Web
Page
1. Open a text editor (like VS code) and create a new HTML file. Save it with a .html

extension (e.g., mypage.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.

Task: Create Your Personal Web Page 1


7. Experiment with formatting text within your web page. Use <strong> , <em> , and <u>

tags to emphasize certain words or phrases in your description or quote.

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!

Task: Create Your Personal Web Page 2


Working with Images
Visual elements, such as images, play a vital role in web design. In this chapter, we will
learn how to add images to our web pages using HTML. Images can enhance the
appearance of a website and make it more engaging and visually appealing.

3.1 Adding Images to a Web Page:


To add an image to a web page, we use the \<img> tag. The \<img> tag is self-closing,
meaning it doesn't require a closing tag. Let's see how to add an image to our web
page:

<body>
<h1>Welcome to My Web Page!</h1>
<p>This is a paragraph of text. Check out the image below:</p>

<img src="image.jpg" alt="A beautiful sunset">

<p>Isn't the sunset amazing?</p>


</body>

Working with Images 1


OR

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:

<img>: The <img> tag is used to embed images in an HTML document.

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.

Working with Images 2


3.2 Controlling Image Size:
You can control the size of an image by using the width and height attributes. Let's
resize the image in our example:

<img src="image.jpg" alt="A beautiful sunset" width="300" height="200">

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.

3.3 Image Accessibility:


It's essential to provide alternative text for images, especially for users who may have
visual impairments or when the image cannot be loaded. The alt attribute serves this
purpose. Let's update our previous example with descriptive alt text:

<img src="image.jpg" alt=" A beautiful sunset over the ocean">

Always strive to provide meaningful alt text that accurately describes the image's
content or purpose.

3.4 Image File Formats:

Working with Images 3


Different image file formats are supported in web development. The most commonly
used formats are JPEG, PNG, and GIF. Consider the following when choosing an image
format:

JPEG (JPG): Ideal for photographs and complex images with many colors.

PNG: Suitable for images with transparency or sharp lines, such as logos.

GIF: Suitable for simple animations or images with limited colors.

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.

Working with Images 4


Structuring Content with Lists
In web development, lists are essential for organizing and structuring content. In this
chapter, we will explore how to create lists in HTML. Lists allow us to present
information in an organized and hierarchical manner, making it easier for users to read
and understand.

4.1 Unordered Lists:


Unordered lists are used to represent a collection of items in no particular order. Each
item is represented by a bullet point. Let's create an unordered list:

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

Structuring Content with Lists 1


Save the changes and refresh the web page. You will see a list of favorite fruits
displayed as bullet points.
Explanation:

<ul>: The <ul> tag represents an unordered list.

<li>: The <li> tag represents a list item within the <ul> or <ol> element.

4.2 Ordered Lists:


Ordered lists are used when the order of items is significant. Each item is represented
by a number. Let's create an ordered list:

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

Structuring Content with Lists 2


Explanation:

<ol>: The <ol> tag represents an ordered list.

<li>: The <li> tag represents a list item within the <ol> or <ul> element.

4.3 Nested Lists:


Lists can be nested within other lists to create a hierarchical structure. Let's create a
nested list example:

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

Structuring Content with Lists 3


By placing a <ul> or <ol> element inside an <li> element, we create a nested list.

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.

Structuring Content with Lists 4


Tables and Data Representation
Tables are a powerful tool for representing structured data in HTML. In this chapter, we
will learn how to create tables and display data in a tabular format. Tables provide a
visual and organized way to present information, making it easier for users to interpret
and analyze data.

5.1 Creating a Basic Table:


To create a table, we use the <table> element along with other related elements. Let's
create a basic table to display some 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>

Tables and Data Representation 1


<td>Jane Smith</td>
<td>30</td>
<td>London</td>
</tr>
</table>
</body>

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>: The <table> tag represents the table itself.

<tr>: The <tr> tag represents a table row.

<th>: The <th> tag represents a table header cell.

<td>: The <td> tag represents a table data cell.

5.2 Table Headers and Data Cells:


In a table, the first row can be designated as the table header using the <th> element.
Let's update our example to include table headers:

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

Tables and Data Representation 2


<td>30</td>
<td>London</td>
</tr>
</table>

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.

5.3 Table Rowspan and Colspan:


Sometimes, a cell may need to span multiple rows or columns. We can achieve this
using the rowspan and colspan attributes.
Let's update our table to include a cell spanning multiple columns:

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

Tables and Data Representation 3


Save the changes and refresh the web page. The "Address" cell will span two columns,
and the address data will span two rows.
Explanation:

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.

Tables offer great flexibility in representing various data structures.


Experiment with different table layouts, including merging cells, adding more columns or
rows, and applying CSS styles to enhance the table's appearance.
In the next chapter, we will explore forms, which allow users to input data and interact
with web pages.

Tables and Data Representation 4


Building Forms for User Input
Forms are a fundamental element of interactive web pages, allowing users to input and
submit data. In this chapter, we will learn how to create forms using HTML. Forms
enable various types of user interactions, such as submitting feedback, making
purchases, or registering for events.

6.1 Creating a Basic Form:


To create a form, we use the <form> element and include different types of input fields.
Let's create a basic form that collects user information:

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

<input type="submit" value="Submit">

Building Forms for User Input 1


</form>
</body>

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.

<textarea>: The <textarea> tag creates a multi-line text input field.

required attribute: The required attribute ensures that the field must be filled in
before submitting the form.

6.2 Form Submission:


When a user submits a form, the data is typically sent to a server for processing. We
can specify the action and method attributes of the form element to control how the data
is handled. Let's update our form with the necessary attributes:

<form action="submit.php" method="post">


<!-- Input fields here -->
<input type="submit" value="Submit">
</form>

In this example, the form data will be sent to a file named "submit.php" on the server
using the HTTP POST method.

Building Forms for User Input 2


Note: For form submission to work, you would need to set up a server-side script (such
as PHP, Node.js, or others) to handle the submitted data.

6.3 Other Input Field Types:


HTML offers various input field types to accommodate different data types and provide
better user experiences. Here are a few examples:

<input type="email">: For collecting email addresses.

<input type="password">: For collecting passwords (displays the input as masked


characters).

<input type="checkbox">: For selecting one or more options from a list.

<input type="radio">: For selecting a single option from a list.

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.

Building Forms for User Input 3


HTML Page Structure
A basic HTML page structure mainly consists of 4 HTML tags:

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

<html> : A Web page begins & end with HTML tag

<head> : It includes the page title, scripts, styles & meta-information about website

<body> : It will contain the main content of the web page.

Example of HTML Page Structure

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

Document Type Declaration:


A document type declaration (DTD), <!DOCTYPE html> is an instruction to the browser
about the type of document. The DTD specifies the rules for the markup language so

HTML Page Structure 1


that the browsers render the content correctly. It is always good to add a declaration to
your HTML documents for proper standards.
Html
HTML starting tag <html> indicates to the browser that it is an HTML document begins
and the HTML closing tag </html> tells the browser that the HTML document is
completed.
Header
The header section does not output text inside the browser, it is used to specify
information about the web page. It is used to display the page title, scripts, and style for
the web page.
Body
This is the main part of the HTML document. The content which we want to display on
the browser will be written inside body tags. The HTML body contains different types of
content and tags. For example, we have used <h1> heading and <p> paragraph tags
inside the body.
We will read more about the other tags in the next chapters.

HTML Page Structure 2


HTML Head
HTML Head element mainly contains metadata (data about data) about the HTML
Page.
You can place the HTML page title, scripts, styles, and other meta information in the
head element. This information is helpful for search engines and provides additional
data for HTML pages.
Type of data in HTML Head element:

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.

Example of HTML Head Element data

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

Nested HTML Elements


HTML elements can be nested. This means that the HTML element can contain many
other elements inside.

HTML Elements and Tags 1


<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<p>My sample paragraph content.</p>

</body>
</html>

HTML Empty Elements


HTML elements with no content are called empty elements. There are many empty
elements that do not have a closing tag.
For example: <br> is an empty element without a closing tag. It is used to create line
breaks.
It is good to close every tag. Empty elements can be “closed” in the same Opening tag.
For example: <br />

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.

Tips while using HTML Tags:


Always close HTML tags to validate your webpage against W3C Validation
Standard.

HTML5 standard does not require lowercase tags but W3C recommends to use
lowercase in HTML

HTML Elements and Tags 2


HTML Attributes
HTML Attributes are part of the HTML Tags & elements. These attributes specify some
additional style or special information about the HTML tags.
Most of the time attributes are specified as pairs. For example: attribute="value"

Syntax of HTML Attributes


Attributes are always specified within a start tag. First, we need to specify the name of
the attribute and then, we assign a value to it (name=” value”)
Example: <h1 title="My Title"> My Heading </h1> tag.

The title Attribute


Each HTML Tag allows some specific attributes. Some HTML Attributes are used by
many different elements. For example, the Title attribute can be used in almost every
HTML element.
HTML Title attribute is used to display some titles to users when they mouse over that
element. For example: Example: <h1 title="My Title"> My Heading </h1> tag.
In the above example, when the user will take his mouse to "My Heading" text a Title (like
tooltip) "My Title" will be visible to the user.

The lang Attribute


The HTML lang attribute is used to declare the language of HTML page content. This
attribute is very helpful for screen readers and search engines.
Example: <html lang="en-US"></h1> tag.

The align Attributes


HTML align attribute can be used in paragraphs, images, and a few other tags for
horizontal alignment. This align attribute can have 3 main values (left, right, and center).
By using those values you can align a paragraph's content to left, right, or center in the
browser window.

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>

HTML width & height Attributes


You can set HTML images’ height & width using these HTML attributes. Images are
defined using HTML images are defined with the
tag. There is another attribute called “src” in this tag. It is used to specify the path of the
image.
Example: <img src="xyz-logo.jpg" width="200" height="300">

The style Attribute


The HTML style attribute is one of the most used attributes to specify the style rules for
different HTML elements. Using style attributes, we can set border, color, font size,
background color, and many other styles.
Example: <p style="color:red;"> This is Tutorials Class</p>

HTML Example with Various Attributes

<!DOCTYPE html>
<html>
<body>

<h1 title="My Title"> My Heading </h1>


<p align="center">This content is aligned center</p>
<p style="color:red;"> This is Tutorials Class's red content</p>
<img src="xyz.jpg" width="300" height="200" alt="Alternate Text" title="Tutorials" />
<a href="http://xyz.com"> Go to Tutorials Class Website </a>

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

Example of All HTML Headings Levels:

<h1>Heading level 1</h1>


<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>

Why HTML Headings Are Important?


HTML Heading tags are important for users as well as Search Engines.

Heading tags helps users to pay attention to the main headings.

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:

<p>This is a sample paragraph.</p>

HTML Paragraphs – Complete HTML Program Example


You can use multiple paragraphs in an HTML program. The following example consists
of three <p> tags.

<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;"

HTML Background Color


We can set background colors for various HTML Elements.
The background-color property is used to define the background color.

Example of HTML Styles – Background Color

<body style="background-color:lightblue;">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>

HTML Text Color


We can change the color of the text using color properties in any HTML element.

Example of HTML Text color

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.

Example of HTML Font

<h1 style="font-family:arial;">This is a heading</h1>


<p style="font-family:Times New Roman;">This is a paragraph.</p>

HTML Text Size


The font-size property defines the text size for an HTML element.

Example of HTML Text Size

<h1 style="font-size:15px;">This is a heading</h1>


<p style="font-size:20px;">This is a paragraph.</p>

HTML Text Alignment

HTML Styles 2
The text-align property is used to set a horizontal text alignment for an HTML element.

Example of HTML Text Alignment

<h1 style="text-align:right;">right heading</h1><p style="text-align:center;">This is a pa


ragraph.</p>

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.

HTML Formatting Tags List


Formatting Tags Example & Syntax

Bold & Strong Tag <b> Sample Text </b> <strong> Sample Text </strong>

Italic & Emphasized


<i> Sample Text </i> <em> Sample Text </em>
Tag

Small Tag <small> Sample Text </small>

Big Tag <big> Sample Text </big>

Marked (Highlighted)
<mark> Sample Text </mark>
Tag
Deleted (Removed)
<del> Sample Text </del>
Tag
Inserted (Added) Tag <ins> Sample Text </ins>

Subscript Tag <sub> Sample Text </sub>

Superscript Tag <sup> Sample Text </sup>

Next, we will cover these HTML Text formatting tags in detail below.

HTML Bold & Strong Text Formatting


HTML Bold Tag: The HTML <b> element defines bold text, without any extra
importance.

Here the text is normal.


<b>Here the text is bold.</b>

HTML Formatting 1
HTML Strong Tag: The HTML <strong> element defines strong text, with added
semantic “strong” importance.

Here the text is normal.


<strong>Here text is strong</strong>

HTML Italic and Emphasized Text Formatting


HTML Italic Tag: The HTML <i> element defines italic text, without any extra
importance.

This text is normal.


<i>Text is italic</i>
The text is normal.
<i>Text is italic</i>

HTML Emphasised Tag: The HTML <em> element defines the emphasized text, with
added semantic importance.

The text is normal.


<em>Text is emphasized</em>

HTML Small Text Formatting

HTML Formatting 2
The HTML <small> element defines small text.

This is normal text


<small>This is Small Text</small>

HTML Big Text Formatting


The HTML <small> element defines bigger text. All text placed between this tag will
have bigger text as compared to normal.

This is normal text


<big>This is Big Text</big>

Note: Note: The big element is not supported in HTML5.

HTML Marked Text Formatting


The HTML <mark> element defines marked text. All content placed inside this tag will be
marked (highlighted).

This is normal text


<mark>This is Marked or Highlighted Text</mark>

HTML Formatting 3
HTML Deleted Text Formatting
The HTML <del> element defines deleted (removed) text.

This is normal text


<del>This is Deleted or Removed Text</del>

HTML Inserted Text Formatting


The HTML <ins> element defines inserted (added) text.

This is normal text


<ins>This is Inserted or Added Text</ins>

HTML Subscript Text Formatting


The HTML <sub> element defines sub-scripted text.

This is normal but this is text


This is <sub> sub-scripted Text</sub>

HTML Superscript Text Formatting


The HTML <sup> element defines super-scripted text.

This is normal but this is text


This is <sup> super-scripted Text</sup>

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

<!-- Add any comment about the following paragraph -->


<p>This is a first paragraph.</p>

<!-- This comment will tell something about the following paragraph -->
<p>This is another paragraph for testing.</p>

Complete HTML Program with Multi-line HTML Comments


You can simply use multiple lines to add large comments using the same tags. See the
multi-line comment example below:

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

More Information About Links:


HTML links are also called Hyperlinks.

Link can be in the form of text as well as images or other media

You can provide a link to any section of the same page, any other page within a
website or any external website as well.

HTML Links Syntax


We can create HTML links using the anchor <a> tag.
For example: <a href="http://www.xyz.com"> Tutorials Class </a>

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>

<a href="http://xyz.com" target="_blank">Go to Tutorials Class</a>

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

HTML Links Target:


We can set HTML Links Target to open into the new window or the same window. The
target attribute is used with one of the following values:
Example of HTML Target Attribute: <a href="page2.html" target="_top"> Link with New
Window </a>

HTML Target Attribute Values List


Target Value Purpose

_blank It opens the linked page in a new window or tab

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

framename It opens the linked page in a named frame

Complete Example of HTML Links


Let us create two files “page1.html” & “page2.html” . We will create a link between these
two files using a relative URL. We will also test a link using an absolute url as well.
Create an HTML file “page1.html” and write the following code:

HTML Links 2
<html>
<body>

<a href="page2.html" >Example of Relative Link</a>

<a href="http://xyz.com" target="_blank">Example of Absolute Link</a>

</body>
</html>

Create an HTML file “page2.html” and write the following code:

<html>
<body>

<a href="page1.html">Example of Relative Link</a>

<a href="http://google.com" target="_blank">Example of Absolute Link</a>

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

How to Insert HTML Images:


Images can be inserted with the <img> tag in HTML.

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

Example using Relative Image URL:


A relative URL specifies a path that is relative to the current folder/page. When you
have an image in the same or nearby folder, you need not specify the full domain or
path of the image. You can only specify the image name in the source if the image
exists in the same folder.

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

Example using Absolute Image URL:

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

Image Alternate Text Attribute


The alt attribute is used to specify an alternate text for an image. This text will be
displayed if the image is not found at a given location. You can test it by using the wrong
image URL in the source. Use the example below:

<img src="test.png" alt="Test Photo Alternate Text">

Image Title Attribute


The title attribute is used to specify the title of an image. This title is visible when you
point your mouse over any image. Use the example below:

<img src="http://xyz.com/wp-content/uploads/2016/04/xyz-logo1.png" title="This is Tutorial


s Logo Title">

Image Size (Width & Height Attribute)


Width and Height attributes are available to specify the image width and height. The
values for Height and Width attributes are specified in pixels (px) by default.

<img src="www.xyz.com/photo.jpg" height="300" width="500" >

Image Border Attribute


You can set a border around the image using “border” attribute. By default border
thickness will be measured in pixels (px) and images will have 0 or no border if not
specified.

HTML Images 2
<img src="www.xyz.com/photo.jpg" border="5px" >

Image Alignment Attribute


You can align the image horizontally using the “align” attribute of “img” tag. Images are
aligned left by default. To test image alignment in a better way, you can add some text
or paragraphs as well.
Commonly used align properties are given below:

Set Image Alignment Left: align="left"

Set Image Alignment Right: align="right “

Set Image Alignment Center: align="center"

This is a sample text. <img src="www.xyz.com/photo.jpg" align="right" >


This is another text.

Complete Example using all Image Attributes


You can use multiple images on any webpage. Different attributes can be used together
for any image as well. Use the following example to test various image properties.
Please change the Image name & URL as per your image.

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

HTML Lists Type


HTML offers three types of lists. Following Table will give you a brief description of them.

List Type Description Tags used

Unordered List used to group a set of items without any order. <ul>,<li>

Ordered List used to group a set of items, in a specific order. <ol>,<li>

used to display some definition term (dt) &


Definition List <dl>,<dt>,<dd>
definition’s description (dd)

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

Example of Unordered List

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

Unordered List Style Type Attribute


HTML offers three types of lists. Following Table will give you a brief description of them.

HTML Unordered List Types


List Style Type Description Example & Syntax

disc Starts a list using discs type bullets (default) <ul type="disc">

circle Starts a list using circle-type bullets <ul type="circle">

square Starts a list using square-type bullets <ul type="square">

none Starts a list without bullets <ul type="type:none">

Example of Unordered List with Different List Styles

<html>
<title> Unordered List Example Test - Tutorials Class </title>
<body>

<h2>Unordered List of Fruits with Disc Bullets</h2>


<ul type="disc">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>

<h2>Unordered List of Colors with Circle Bullets</h2>


<ul type="circle">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>

<h2>Unordered List of Fruits with Square Bullets</h2>


<ul type="square">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>

<h2>Unordered List of Colors without bullets</h2>


<ul type="none">

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

Example of Ordered List

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

Ordered List Style Type Attribute


HTML offers three types of lists. Following Table will give you a brief description of them.

HTML Ordered List Style Type Attribute


List Style Type Description Example and Syntax

Numbers Starts a list using numbers (default) <ol type="1">

Uppercase letters Starts a list using uppercase letters <ol type="A">

Lowercase letters Starts a list using lowercase letters <ol type="a">

Uppercase roman Starts a list using uppercase Roman


<ol type="I">
numbers numbers
Lowercase roman Starts a list using lowercase Roman
<ol type="i">
numbers numbers

Example of Ordered List with Different List Styles

<html>
<title> Ordered List Example - Tutorials Class </title>
<body>

<h2>Ordered List of Fruits with Numbers </h2>


<ol type="1">
<li>Banana</li>
<li>Apple</li>
<li>Grapes</li>
</ol>

<h2>Ordered List of Fruits with Uppercase letters</h2>


<ol type="A">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ol>

<h2>Ordered List of Colors with Lowercase letters</h2>

HTML Lists 4
<ol type="a">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>

<h2>Ordered List of Colors with Uppercase Roman numbers</h2>


<ol type="I">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>

<h2>Ordered List of Colors with Lowercase Roman numbers</h2>


<ol type="i">
<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.

Example of Definition Lists

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

Nested HTML Lists


When we used a list inside the list, it is called Nested List. We will see an example that
will have different lists including the Nested list as well.

Example of a Complete HTML program using different Lists:

<!DOCTYPE html>
<html>
<body>

<h2>A Nested List</h2>


<ul>
<li>Red</li>
<li>Black
<ul>
<li>Light Black</li>
<li>Dark Black</li>
</ul>
</li>
<li>Blue</li>
<li>Green</li>
</ul>

<h2>Unordered List</h2>
<ul type="circle">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>

<h2>Numbered Ordered List </h2>


<ol type="1">

HTML Lists 6
<li>Bannana</li>
<li>Apple</li>
<li>Grapes</li>
</ol>

<h2>Uppercase Ordered List</h2>


<ol type="A">
<li>Red</li>
<li>Green</li>
<li>Blue</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.

Iframe – Attributes List


There are many Iframe Tag Attributes available to use for different purposes. We have
set the Iframe source using The src attribute in the previous example. You can also
use attributes to set Iframe height and width as well. See more attributes in the following
table:

Attribute Description Syntax & Example

used to give the webpage URL that needs to


Source (src) src="page.html"
load in the frame.
Height used to set the height of the frame. height="400"

Width used to set the width of the frame width="500"

used to enable or disable resizing of frames by


No Resize noresize="noresize"
users
Frame Border used to define the border of the frame frameborder="1"

Scrolling used to enable or disable scrolling scrolling="yes"

Iframe – Height and Width

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>

<iframe src="http://xyz.com" height="400" width="500"></iframe>

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

<iframe src="http://google.com" frameborder="4"></iframe>


<iframe src="http://xyz.com" frameborder="0"></iframe>

Iframe as a Target for a Link


An HTML iframe can be used as the target frame for an HTML link. This works in two
simple steps:

1. Assign a name to the Iframe using the name attribute.

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>

<iframe height="50%" width="60%" src="page1.html" name="tc_frame"></iframe>

<p><a href="http://xyz.com" target="tc_frame">Tutorials Class</a></p>

<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

<form><input type="text" /></form>

Form – Attributes List


Attributes Description Syntax & Example

defines the URL of the program or page


action where the action will be performed on form action="page2.php"

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

The POST method transfers information via HTTP headers. For


Example: <form method="POST">

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

_blank will open a new page after the form is submitted.

_self will open the action page in the same window.

_parent will open the action page in the parent frame.

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>

Form – Input Elements


The input element is the most commonly used element in the form. Input elements are
defined by <input> tag. There are many input-type elements available in the form.
Depending upon the type attribute different input elements can be displayed. Some
examples of input elements are text, buttons, check-box, and radio-button.

Form – Input type element


Attribute Description Syntax & Example

used to define a text box that allows users to


Text Box input type="text"
enter some text.
defines a radio button that allows users to select
Radio Button input type="radio"
any one option or choice
defines a checkbox that allows users to select
Checkbox input type="checkbox"
multiple options or choices
Button defines normal buttons for users for some action input type="button"

defines a button that resets form data when the


Reset Button input type="submit"
user clicks on it.
defines a Form submission button that submits
Submit Button input type="reset"
form data when the user clicks on it

Form – Input Text Field & Attributes


Input Text field defines a single line input field for users. Example: <input type="text">

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:

type="radio" defines the Form’s input element as a radio button

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.

checked It will set the current checkbox checked by default.

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

type="radio" defines the Form’s input element as a radio button

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.

checked It will set the current checkbox checked by default.

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

Form – Submit & Reset Button


You can create buttons in Form. Depending upon the type of button, it performs some
action on form data.
Type of buttons: There are 3 commonly used buttons in Form:

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

value specifies the button value.

name defines a unique name for every button to identify later.

<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

Form – Select Menu


Select Element is used to create a drop-down list. Users can select any item from the
list. All list items are specified using the option tag.
Select Attributes

the name defines a unique name for every select menu to identify later get its list
data

size scrolling list box

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 Forms Element – Complete Example


Here is an example of various HTML Form elements. Most HTML Forms use more than
one HTML form element.

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

List of Table Tags


Attribute Description Syntax & Example

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>

Table Data Used to define table data in cells <td></td>

Example of Simple HTML Table:


HTML Table is created using <table> tag. All other table tags are placed under this tag.
The first row often contains heading in tables. A row starts with <tr> tag and then each
heading is created using <th> tag for each column.
Then we create another row for data. Again, A new row starts with <tr> tag while data
is created using <td> tag for each column.

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

HTML Table Tag & Attributes


You can make some changes in Table styles using the given attributes.
For example, the above simple html table program has a border attribute that draws a
border around the table. Here, is the list of common table attributes.

HTML Table Attributes


Attribute Description Syntax & Example

Border used to specify borders around the table & cells border="2"

specify the amount of spacing between the cell border


Cell Padding cellpadding="5"
and cell content.
specify the amount of spacing between two adjacent
Cell Spacing cellspacing="3"
cells.
Width used to set the width of the table. width="80%"

align used to set the alignment of the table horizontally. align="center"

bgcolor used to set the background color of the table. bgcolor="blue"

background used to set the image in the table background. background="image.jpg"

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>

<table width="80%" border="2" bgcolor="skyblue" align="center" cellspacing="3" cellpadding


="5">
<tr>
<th>Name</th>
<th>City</th>
<th>Phone</th>
</tr>
<tr>
<td>Robin</td>
<td>Delhi</td>
<td>9876459089</td>
</tr>
<tr>
<td>Rocky</td>
<td>New York</td>
<td>9876459089</td>
</tr>
</table>
</body>
</html>

Basic HTML Page layout using table tag


A web page layout is often divided into multiple columns. Then these columns are
treated as different sections of data.
There are two most popular ways to create those columns in html page. One way is
using <div> tag and another way is using HTML <table> tag.

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.

Creating an HTML page layout using table tags


Let us create a two-column layout along with the header and footer area using an HTML
table.

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

HTML Frames Tags and Element List


<frameset>Attribute List
Syntax &
Attribute Description
Example
used to define the number of rows in the frameset and
rows rows="20%,60%,20%"
the size of each row.
used to define the number of columns in the frameset
cols cols="25%,50%,25%"
and the size of each column.
border used to define the border width of the frameset. border="5"

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.

used to give a name to a frame. It is useful to identify a


name name="left-frame"
frame to load a document using the link’s target.
noresize used to disable frame window resize noresize="noresize"

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.

Complete Example of Frameset

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

Learning CSS is so much fun.


You can apply different CSS properties to change the webpage formatting.
Here is an example of CSS Code:

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.

A Sample HTML Table with CSS


In the below code, a sample HTML Table is displayed using a Style Sheet. As you can
see, the look and feel of the table is completely different than a normal HTML table
without 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;
}

What do you need before learning CSS? 1


table{
width:100%;
}
</style>

There are 3 methods through which you can add CSS to the HTML document.

External Style Sheet

Internal Style Sheet

Inline Style.

External Style Sheets


If you are planning on using the same style sheet again and again for many pages, your
ideal choice would be External Style Sheets.
An External Style Sheet is a separate file with CSS code saved in it .css format
It is linked to the HTML page using the <link> tag shown below.

<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>

Internal Style Sheets


If an HTML document needs a unique style that is not going to be reused, Internal Style
Sheet would be the ideal choice.
Internal Style Sheets are added to the HTML document in the head section using the
<style> tag as shown below.

What do you need before learning CSS? 2


<head>
<style>
body{
background-color:#FFEBF0;
}
thead {
background-color:#ADDFE7;
}
table{
width:100%;
}
</style>
</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.

<table style:"width:100%; height:100%">

Multiple Style Sheets


If multiple style sheets are used on the same page, the browser's priority will be based
on the following order.

1. Inline Styles.

2. Internal Style Sheets.

3. External Style Sheets.

4. Browser's Default Styles.

CSS SYNTAX
The basic CSS syntax is shown below.

What do you need before learning CSS? 3


p {
color: red;
font-size:10px;
}

Syntax Explained
The above syntax is explained below using tables.

p {color:red;font-size:10px;}

Selector Declaration

In the declaration part, properties are given values shown below.

color : blue

Property Value

A working CSS example of the above code is given below.

<html>
<head>

<style>
p{
color: red;
font-size:20px;
}
</style>

</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>

What do you need before learning CSS? 4


CSS SELECTOR
In addition to adding CSS to HTML elements like paragraphs, it can also be added to Id
Selectors and Class Selectors.
The three types of CSS Selectors are,

1. Id Selector

2. Class Selector

3. HTML Element Selector

Id Selector
First of all, what is an Id?

Id is a property of HTML elements that you can specify like shown below.

<p id="para1">This is a Paragraph.</p>

You can use the specified Id to manipulate the corresponding HTML Element as shown
below.

#para1{
color: red;
font-size:20px;
}

The above style is applied to the HTML element with Id "para1".

"#" symbol is used to specify the Id

Class Selector
Class is a property of HTML elements that you can specify like shown below.

<p class="class1">This is a Paragraph.</p>


<h4 class="class1">This is a Heading.</h4>

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.

HTML Element Selector


Styles are applied to HTML elements without "#" or "." as shown below.

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.

First name Lastname Age

Samara Miller 20

Allen Scarlet 25

Samara Miller 20

Allen Scarlet 25

Table without CSS

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

The CSS applied to the table is given below.

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

Sets the table width to match its


table width 100%
background element.
tr:nth-of- Sets the background of the odd
background #eee
type(odd) numbers table rows(1,3,...)to #eee.
Sets the text property of the table
th color white
header to a while.
td padding 6px Creates a small space of 6px around

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.

CSS BOX MODEL 1


As you can see, around the actual content, the CSS box model contains Padding,
Border, and Margin.

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.

CSS BOX MODEL 2


</div>
<div class="div2">
Content of div2.
</div>

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;
}

CSS BOX MODEL 3


CSS Comments
CSS comments are a useful feature that allows you to add notes and explanations
within your CSS code without affecting its functionality.
Comments are ignored by the browser and serve as documentation for yourself
or other developers working on the codebase. They can help you understand the
purpose of certain styles or provide context for future modifications.

The Syntax for CSS Comments


To add a comment in CSS, you can use the following syntax:

/* This is a CSS comment */

Example Usage:

/* Styles for the navigation menu */


.navbar {
background-color: #333;
color: #fff;
/* Adding padding for better spacing */
padding: 10px;
}

/* Styles for the main content area */


.content {
font-size: 16px;
/* Margin to create separation */
margin-top: 20px;
}

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.

Similarly, in the .content rule, a comment /* Margin to create separation */ clarifies


the purpose of the margin-top property.

By using comments effectively, you can improve code readability, enhance


collaboration, and make future maintenance or modifications easier.

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);
}

HSL and HSLA Notation


HSL (Hue, Saturation, Lightness) and HSLA (HSL with alpha) notations define colors
based on their hue, saturation, and lightness. Hue is represented by an angle (0 to 360),
saturation and lightness are percentages (0% to 100%), and alpha represents the
opacity (0 to 1). Example:

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

Using Color Names:

ody {
background-color: yellow;
}

button {
background-color: aqua;
}

Using Hexadecimal Notation:

h1 {
background-color: #336699;
}

CSS Background Color 1


div {
background-color: #FFA500;
}

Using RGB Notation:

p {
background-color: rgb(255, 0, 0);
}

span {
background-color: rgb(0, 128, 0);
}

Using RGBA Notation:

.container {
background-color: rgba(0, 0, 255, 0.5);
}

.header {
background-color: rgba(255, 0, 0, 0.8);
}

Using HSL Notation:

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

CSS Background Color 2


By using color names, hexadecimal notation, RGB or RGBA notation, or HSL or HSLA
notation, you can customize the background color and enhance the visual appeal of
your web pages.
Experiment with different colors to achieve the desired effects and create
engaging designs.

CSS Background Color 3


CSS Text Color
The text color in CSS allows you to define the color of the text within HTML elements. It
plays a crucial role in the overall appearance and readability of your web page. Let's
explore how to use the color property to set the text color.

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

Using Color Names:

h1 {
color: red;
}

p {
color: blue;
}

Using Hexadecimal Notation:

h2 {
color: #336699;
}

span {

CSS Text Color 1


color: #FFA500;
}

Using RGB Notation:

a {
color: rgb(255, 0, 0);
}

li {
color: rgb(0, 128, 0);
}

Using RGBA Notation:

.heading {
color: rgba(0, 0, 255, 0.5);
}

.paragraph {
color: rgba(255, 0, 0, 0.8);
}

Using HSL Notation:

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

CSS Text Color 2


CSS Text Color 3
CSS Border Color
The border color property in CSS allows you to define the color of an element's border.
It enables you to customize the appearance and style of borders, making them visually
distinct and complementing the overall design of your web page.

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

Using Color Names:

.button {
border-color: red;
}

.container {
border-color: blue;
}

Using Hexadecimal Notation:

.box {
border-color: #336699;
}

CSS Border Color 1


.image {
border-color: #FFA500;
}

Using RGB Notation:

.card {
border-color: rgb(255, 0, 0);
}

.link {
border-color: rgb(0, 128, 0);
}

Using RGBA Notation:

.header {
border-color: rgba(0, 0, 255, 0.5);
}

.footer {
border-color: rgba(255, 0, 0, 0.8);
}

Using HSL Notation:

.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

CSS Border Color 2


pages. Experiment with different colors to achieve the desired effects and create
engaging designs that make your elements stand out.

CSS Border Color 3


CSS Backgrounds
CSS provides powerful features for styling the backgrounds of HTML elements.
Backgrounds can include colors, images, gradients, and other effects, allowing you to
create visually appealing and engaging web pages. Let's explore various techniques to
style backgrounds using CSS.

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>

<p>This page has a light blue background color!</p>

</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:

dotted - Defines a dotted border

dashed - Defines a dashed border

solid - Defines a solid border

double - Defines a double border

groove - Defines a 3D grooved border. The effect depends on the border-color


value

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

none - Defines no border

hidden - Defines a hidden border

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;
}

The example above gives the same result as this:

p {
border-style: dotted solid;
}

So, here is how it works:


If the border-style property has four values:

border-style: dotted solid double dashed;

top border is dotted

right border is solid

bottom border is double

CSS Borders 4
left border is dashed

If the border-style property has three values:

border-style: dotted solid double;

top border is dotted

right and left borders are solid

bottom border is double

If the border-style property has two values:

border-style: dotted solid;

top and bottom borders are dotted

right and left borders are solid

If the border-style property has one value:

border-style: dotted;

all four borders are 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 .

Padding and Content Box


The padding is added to the content area of an element, increasing the space inside the
border. It does not affect the size of the element itself. When specifying the width or
height of an element, the padding is added to the overall dimensions.

Padding and Background


The background color or background image of an element extends to include the
padding area. This ensures that the background covers the entire visible space,
including the padding.

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;
}

CSS Height, Width, and Max-width 1


Width Property
The width property is used to define the width of an element. It follows the same units
and values as the height property. Here's an example:

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;
}

CSS Height, Width, and Max-width 2


All CSS Dimension Properties
Property Description

height Sets the height of an element

max-height Sets the maximum height of an element

max-width Sets the maximum width of an element

min-height Sets the minimum height of an element

min-width Sets the minimum width of an element

width Sets the width of an element

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.

CSS Height, Width, and Max-width 3


CSS Outline
CSS provides the outline property, which allows you to add a visible border-like outline
around elements. Outlines are often used to highlight or emphasize elements, such as
when an element receives focus or is hovered over. Let's explore how to use the
outline property in CSS.

Outline Style
The outline-style property specifies the style of the outline, and can have one of the
following values:

dotted - Defines a dotted outline

dashed - Defines a dashed outline

solid - Defines a solid outline

double - Defines a double outline

groove - Defines a 3D grooved outline

ridge - Defines a 3D ridged outline

inset - Defines a 3D inset outline

CSS Outline 1
outset - Defines a 3D outset outline

none - Defines no outline

hidden - Defines a hidden outline

The following example shows the different outline-style values:

p.dotted {outline-style: dotted;}


p.dashed {outline-style: dashed;}
p.solid {outline-style: solid;}
p.double {outline-style: double;}
p.groove {outline-style: groove;}
p.ridge {outline-style: ridge;}
p.inset {outline-style: inset;}
p.outset {outline-style: outset;}

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;
}

The CSS Text Spacing Properties


Property Description

letter-spacing Specifies the space between characters in a text

CSS Text 8
Property Description

line-height Specifies the line height

text-indent Specifies the indentation of the first line in a text-block

white-space Specifies how to handle white-space inside an element

word-spacing Specifies the space between words in a text

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;
}

CSS Font Style, Font Size & Shorthand 1


Shorthand Font Property
CSS provides a shorthand notation for setting multiple font properties at once, including
font style, font size, and font family. Here's an example:

h2 {
font: italic 20px Arial, sans-serif;
}

CSS Font Style, Font Size & Shorthand 2


In the example above, the font style is set to italic , the font size is 20px , and the font
family is set to Arial , with a fallback to sans-serif if Arial is not available.

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.

CSS Font Style, Font Size & Shorthand 3


Font Pairing Rules
1. Complement
It is always safe to find font pairings that complement one another.
A great font combination should harmonize, without being too similar or too different.

2. Use Font Superfamilies


A font superfamily is a set of fonts designed to work well together. So, using different
fonts within the same superfamily is safe.
For example, the Lucida superfamily contains the following fonts: Lucida Sans, Lucida
Serif, Lucida Typewriter Sans, Lucida Typewriter Serif, and Lucida Math.

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

4. Choose Only One Boss


One font should be the boss. This establishes a hierarchy for the fonts on your page.
This can be achieved by varying the size, weight, and color.
Example

body {
background-color: black;
font-family: Verdana, sans-serif;
font-size: 16px;
color: gray;
}

h1 {
font-family: Georgia, serif;
font-size: 60px;

Font Pairing Rules 1


color: white;
}

Font Pairing Rules 2


CSS Links
CSS provides properties to style and customizes the appearance of hyperlinks, allowing
you to differentiate them from regular text and provide visual feedback to users.
Links can be styled with any CSS property (e.g. color , font-family , background , etc.).

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;
}

Visited Link Color


The color property can also be used to set the color of visited links. By applying
the :visited pseudo-class selector, you can target links that have been previously
visited by users. Here's an example:

a:visited {
color: purple;
}

Hover and Active Link Color


You can use the :hover and :active pseudo-class selectors to apply styles when the
user hovers over or clicks on a link, respectively. This allows you to provide visual
feedback and enhance the interactive experience. Here's an example:

a:hover {
color: red;
}

CSS Links 1
a:active {
color: green;
}

/* unvisited link */
a:link {
color: red;
}

/* visited link */
a:visited {
color: green;
}

/* mouse over link */


a:hover {
color: hotpink;
}

/* 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

a.one:link {color: #ff0000;}


a.one:visited {color: #0000ff;}
a.one:hover {color: #ffcc00;}

a.two:link {color: #ff0000;}


a.two:visited {color: #0000ff;}
a.two:hover {font-size: 150%;}

a.three:link {color: #ff0000;}

CSS Links 4
a.three:visited {color: #0000ff;}
a.three:hover {background: #66ff66;}

a.four:link {color: #ff0000;}


a.four:visited {color: #0000ff;}
a.four:hover {font-family: monospace;}

a.five:link {color: #ff0000; text-decoration: none;}


a.five:visited {color: #0000ff; text-decoration: none;}
a.five:hover {text-decoration: underline;}

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):

<span style="cursor: auto">auto</span><br>


<span style="cursor: crosshair">crosshair</span><br>
<span style="cursor: default">default</span><br>
<span style="cursor: e-resize">e-resize</span><br>
<span style="cursor: help">help</span><br>
<span style="cursor: move">move</span><br>
<span style="cursor: n-resize">n-resize</span><br>
<span style="cursor: ne-resize">ne-resize</span><br>
<span style="cursor: nw-resize">nw-resize</span><br>
<span style="cursor: pointer">pointer</span><br>
<span style="cursor: progress">progress</span><br>
<span style="cursor: s-resize">s-resize</span><br>
<span style="cursor: se-resize">se-resize</span><br>
<span style="cursor: sw-resize">sw-resize</span><br>
<span style="cursor: text">text</span><br>
<span style="cursor: w-resize">w-resize</span><br>
<span style="cursor: wait">wait</span>

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.

CSS Display and Position 1


CSS Display and Position 2
div {
display: block;
}

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.

relative : The element is positioned relative to its normal position, allowing it to be


shifted using the top , right , bottom , and left properties.

absolute: The element is positioned relative to its nearest positioned ancestor, or


the document if no positioned ancestor exists.

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;
}

CSS Display and Position 3


Z-Index
The z-index property specifies the stacking order of positioned elements along the z-
axis. It determines which elements appear in front of or behind others. Elements with a
higher z-index value appear in front of elements with a lower value.

div {
position: absolute;
z-index: 2;
}

span {
position: absolute;

CSS Display and Position 4


z-index: 1;
}

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.

CSS Display and Position 5


CSS Lists
CSS provides properties to style and customize the appearance of HTML lists. You can
modify the list markers, spacing, alignment, and other aspects of lists to match your
design requirements. Let's explore how to use CSS to style lists and make them visually
appealing.

List Style Type


The list-style-type property is used to specify the type of marker or bullet that appears
before each list item. It can have values like disc , circle , square , decimal , lower-alpha ,
upper-alpha , and more. Here's an example:

ul {
list-style-type: disc;
}

ol {
list-style-type: decimal;
}

List Style Position


The list-style-position property controls the position of the list marker in relation to the
list item content. It can have values like inside or outside . Here's an example:

ul {
list-style-position: outside;
}

List Style Image


The list-style-image property allows you to use a custom image as the list marker. You
can provide the URL of the image file. Here's an example:

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;
}

Here's a table summarizing the CSS properties related to lists:


Property Description
list-style-type Specifies the type of marker or bullet for the list items.
list-style-position Determines the position of the list marker in relation to the content.
list-style-image Allows the use of a custom image as the list marker.
list-style Shorthand property for setting all list-related properties at once.

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.

Specifies generated content before or after the content of an


content
element.

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 and Height


The width and height properties control the dimensions of the table. You can set them
to specific pixel values or use relative units like percentages. Here's an example:

table {
width: 100%;
height: 300px;
}

Table Cell Padding and Spacing


The padding property controls the space between the cell content and the cell border,
while the border-spacing property sets the space between adjacent cells. Here's an
example:

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;
}

Table Caption Styling


The caption element is used to provide a title or caption for the table. You can style the
caption using CSS properties. Here's an example:

caption {
font-size: 18px;
font-weight: bold;
}

CSS properties related to tables:


Property Description
border Sets the border around the table and its cells.

Specifies whether the table borders should be collapsed into a single


border-collapse
border or separated.
border-spacing Sets the space between adjacent cells in the table.

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:

:hover : Applies styles when the element is being hovered over.

:active : Applies styles when the element is being activated, such as when it is
clicked.

:focus : Applies styles when the element has keyboard focus.

: Selects elements based on their position in relation to their parent. For


:nth-child()

example, :nth-child(odd) selects every odd child element.

:first-child : Selects the first child element of its parent.

:last-child : Selects the last child element of its parent.

a:hover {
color: red;
}

button:active {
background-color: green;
}

input:focus {
border: 1px solid blue;
}

li:nth-child(odd) {

CSS Pseudo-classes and Combinators 1


background-color: lightgray;
}

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:

Descendant selector ( ): Selects elements that are descendants of a specific


element.

Child selector ( > ): Selects elements that are direct children of a specific element.

Adjacent sibling selector ( + ): Selects the element immediately following another


element.

General sibling selector ( ~ ): Selects elements that are siblings 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 Pseudo-classes and Combinators 2


CSS pseudo-classes and combinators provide powerful selectors that allow you to
target specific elements based on various conditions and relationships. By using
pseudo-classes like :hover , :active , and :focus , you can apply styles to elements
based on user interactions. Combinators like the descendant selector, child selector,
adjacent sibling selector, and general sibling selector help you target elements based on
their relationship to other elements. Experiment with different pseudo-classes and
combinators to enhance your CSS styling capabilities and create dynamic and targeted
styles for your web pages.

CSS Pseudo-classes and Combinators 3


CSS Flexbox
CSS Flexbox (Flexible Box Layout) is a powerful layout system that allows you to create
flexible and responsive page layouts. It provides a convenient way to distribute space
among items in a container, align them, and control their order. Let's explore CSS
Flexbox and how you can use it to create flexible and dynamic layouts.

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;
}

Main Axis and Cross Axis


Flexbox introduces two axes: the main axis and the cross axis. By default, the main axis
runs horizontally, from left to right, and the cross axis runs vertically, from top to bottom.
The flex-direction property can be used to change the direction of the main axis.
Here's an example:

.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 */
}

Flexbox Responsive Layouts


Flexbox is particularly useful for creating responsive layouts. By adjusting the flex
properties, you can control how items grow, shrink, and wrap within the container. For
example, the flex-grow property determines how flex items grow to fill available space.
The flex-wrap property controls whether items should wrap to the next line when they
exceed the container width. Here's an example:

.container {
flex-wrap: wrap; /* items wrap to the next line */
}

.item {
flex-grow: 1; /* items grow to fill available space */
}

CSS properties related to Flexbox


Property Description
display Defines the element as a flex container.
flex-direction Specifies the direction of the main axis and the order of flex items.

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

justify-self Allows individual flex items to override the justify-content property.

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;
}

Grid Template Columns and Rows


The grid-template-columns and grid-template-rows properties define the columns and
rows of the grid respectively. You can specify the size and number of columns or rows
using values like pixels ( px ), percentages ( % ), or the fr unit for flexible sizing. Here's
an example:

.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 */
}

Grid Auto Placement


CSS Grid also offers automatic placement of grid items using the grid-auto-flow

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 */
}

Grid Responsive Layouts


CSS Grid is particularly useful for creating responsive layouts. By using media queries
and changing the grid template columns and rows based on the viewport size, you can
create layouts that adapt to different screen sizes. Here's an example:

.container {
grid-template-columns: 1fr 2fr; /* default: 2 columns */
}

@media (max-width: 768px) {


.container {
grid-template-columns: 1fr; /* 1 column for smaller screens */
}
}

CSS properties related to CSS Grid


Property Description
display Defines the element as a grid container.
grid-template-columns Specifies the columns of the grid and their sizes.
grid-template-rows Specifies the rows of the grid and their sizes.
grid-template-areas Defines named grid areas and their layout within the grid.

Shorthand property for grid-template-rows , grid-template-columns , and


grid-template
grid-template-areas .

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.

Responsive layouts: Flexbox can be used to create responsive designs by adjusting


the flex properties based on the available space.

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.

Provides grid-based alignment: Grid offers properties like justify-items , align-


items , justify-content , and align-content to align and distribute items within the grid

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

Difference between Flexbox and Grid 1


items within the grid.

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.

In summary, Flexbox is suitable for simpler one-dimensional layouts where elements


need to be flexibly aligned, while Grid is ideal for complex two-dimensional layouts with
precise control over item placement and sizing.
Both Flexbox and Grid can be used together in a complementary manner to
achieve versatile and responsive designs.

Difference between Flexbox and Grid 2


CSS Responsive Web Design
Responsive web design is an approach to designing and developing websites that
adapt and respond to various screen sizes and devices. It ensures that web pages look
and function well on different devices, including desktops, laptops, tablets, and
smartphones. CSS plays a crucial role in implementing responsive design principles.
Here are some key CSS techniques for creating responsive web designs:

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:

@media (max-width: 768px) {


/* CSS rules for screens up to 768px wide */
}

@media (min-width: 769px) and (max-width: 1024px) {


/* CSS rules for screens between 769px and 1024px wide */
}

@media (min-width: 1025px) {


/* CSS rules for screens wider than 1024px */
}

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.

CSS Responsive Web Design 1


2. Flexible Images: To ensure images scale and resize appropriately, use CSS
properties like max-width: 100% to make images responsive and prevent them from
overflowing their containers.

3. Responsive Typography: Use relative units like em , rem , or vw (viewport width)


for font sizes to ensure that text scales properly on different devices.

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.

6. Mobile-First Design: Adopting a mobile-first approach involves designing and


developing for mobile devices first, then progressively enhancing the layout and
features for larger screens. This approach helps ensure that your design works well
on smaller screens and gracefully expands for larger ones.

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.

CSS Responsive Web Design 2


CSS Media Queries
CSS media queries are a fundamental part of responsive web design. They allow you to
apply different CSS styles based on the characteristics of the device or viewport size.
By using media queries, you can create layouts and styles that adapt to different screen
sizes, orientations, resolutions, and other device features. Here's how to use media
queries in CSS:

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:

@media media-type and (condition) {


/* CSS rules for the specified condition */
}

CSS Media Queries 1


Examples
Here are some common media query examples:
Targeting different screen widths:

@media (max-width: 768px) {


/* CSS rules for screens up to 768px wide */
}

@media (min-width: 769px) and (max-width: 1024px) {


/* CSS rules for screens between 769px and 1024px wide */
}

@media (min-width: 1025px) {


/* CSS rules for screens wider than 1024px */
}

Targeting different device orientations:

@media (orientation: portrait) {


/* CSS rules for portrait orientation */
}

CSS Media Queries 2


@media (orientation: landscape) {
/* CSS rules for landscape orientation */
}

Targeting different device types:

@media (hover: hover) {


/* CSS rules for devices that support hover interactions */
}

@media (pointer: coarse) {


/* CSS rules for devices with touch screens */
}

Combining multiple conditions:

@media (min-width: 768px) and (orientation: landscape) {


/* CSS rules for screens wider than 768px and in landscape orientation */
}

CSS Media Queries 3


Usage Tips
Use min-width for designing from small screens up to larger ones, following the
mobile-first approach.

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

CSS Media Queries 4


optimize the layout and appearance of your website for different screens and devices,
providing a seamless and user-friendly experience.
Certainly! Here are a few additional details and tips to further enhance your
understanding of CSS media queries:

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:

all : Applies to all devices.

screen : Applies to screens and devices with visual output.

print : Applies when printing the web page.

speech : Applies to screen readers and speech synthesizers.

For example, you can target only screens with the following media query:

@media screen and (max-width: 768px) {


/* CSS rules for screens up to 768px wide */
}

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 */

@media (min-width: 768px) {


/* Tablet styles */
/* Styles applied to screens from 768px wide */
}

@media (min-width: 992px) {


/* Desktop styles */
/* Styles applied to screens from 992px wide */
}

CSS Media Queries 5


@media (min-width: 1200px) {
/* Large desktop styles */
/* Styles applied to screens from 1200px 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.

Testing and Debugging


When working with media queries, it's essential to test your design across different
devices and screen sizes to ensure that your styles are applied correctly. You can use
browser developer tools to simulate various screen sizes and orientations and inspect
how your styles respond to different conditions.
Additionally, be mindful of the order in which you write your media queries. Media
queries are processed in the order they appear in your CSS file, so make sure to write
more specific queries (e.g., targeting certain screen widths) before more general ones
(e.g., targeting all screens).

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.

Commonly used CSS media query tags and their descriptions:


Media Query Tag Description

CSS Media Queries 6


all Applies to all devices.
screen Applies to screens and devices with visual output.
print This applies when printing the web page.
speech This applies to screen readers and speech synthesizers.
min-width Specifies the minimum width of the viewport.
max-width Specifies the maximum width of the viewport.
min-height Specifies the minimum height of the viewport.
max-height Specifies the maximum height of the viewport.
orientation Target specific device orientations. Values can be portrait or landscape .
aspect-ratio Matches the aspect ratio of the viewport.
min-aspect-ratio Specifies the minimum aspect ratio of the viewport.
max-aspect-ratio Specifies the maximum aspect ratio of the viewport.
device-aspect-ratio Matches the aspect ratio of the output device.
min-device-aspect-
ratio
Specifies the minimum aspect ratio of the output device.
max-device-aspect-
ratio
Specifies the maximum aspect ratio of the output device.

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.

Matches devices based on the primary pointing device, such as a mouse or


pointer
touch screen.
any-pointer Matches devices that have any pointing device.
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

CSS Media Queries 7


responsive designs. You can combine these tags with various conditions and values to
precisely control how your styles are applied to different devices and viewport sizes.

CSS Media Queries 8


CSS Responsive Images
Responsive images are a crucial aspect of responsive web design, ensuring that
images adapt and scale appropriately on different devices and screen sizes. CSS
provides several techniques to make images responsive. Here are some common
approaches:

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.

CSS Responsive Images 1


<picture>
<source srcset="large-image.jpg" media="(min-width: 1024px)">
<source srcset="medium-image.jpg" media="(min-width: 768px)">
<img src="small-image.jpg" alt="Responsive Image">
</picture>

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.

CSS Responsive Images 2


CSS Fluid Layouts

CSS Fluid Layouts 1


Fluid layouts are a key component of responsive web design, allowing web pages to
adapt and scale fluidly across different screen sizes and devices. In a fluid layout,
elements proportionally adjust their width based on the available space, creating a
flexible and responsive design. CSS provides several techniques to create fluid layouts.
Here are some commonly used approaches:

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.

CSS Fluid Layouts 2


3. Using CSS Grid: CSS Grid is another CSS layout module that provides a grid-
based system for creating flexible and responsive layouts. It offers fine-grained
control over column and row placement and allows elements to automatically adjust
their size based on the available space. Here's an example:

.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;
}

CSS Fluid Layouts 3


In this case, the container element has a maximum width of 1200 pixels, and the
column elements can shrink and expand within the range of 200px to 400px, but they
won't exceed these limits.

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 Fluid Layouts 4


visually appealing, maintain proper readability, and offer a seamless user experience
across different devices.

CSS Fluid Layouts 5


CSS Transforms, Transitions,
and Animations

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:

translate() : Moves an element horizontally and/or vertically.

rotate() : Rotates an element by a specified angle.

scale() : Scales an element by a specified factor.

skew() : Skews an element along the X or Y axis.

CSS Transforms, Transitions, and Animations 1


For example, to rotate an element by 45 degrees, you can use the following CSS:

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

CSS Transforms, Transitions, and Animations 2


transition: background-color 0.3s ease;
}

.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

CSS Transforms, Transitions, and Animations 3


transform: translateZ(0) , to optimize rendering performance.
Experiment with different transform functions, transition durations and timing functions,
and keyframe animations to create stunning effects that enhance user experience and
bring life to your web designs.

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 combine multiple transform functions together to apply different


transformations simultaneously. For example: transform: rotate(45deg) scale(1.2) .

Transforms can be applied in a different order. The order matters, as applying


transformations in a different sequence can yield different results. This is known as
the "transform order of operations."

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

CSS Transforms, Transitions, and Animations 4


Skews an element along the X axis.
skewY() Skews an element along the Y axis.
matrix() Defines a 2D transformation matrix of six values.
matrix3d() Defines a 3D transformation matrix of 16 values.
perspective() Applies a 3D perspective transformation to an element.
rotateX() Rotates an element around the X axis in 3D space.
rotateY() Rotates an element around the Y axis in 3D space.
rotateZ() Rotates an element around the Z axis in 3D space.
rotate3d() Rotates an element in 3D space around a specified axis.
scale3d() Scales an element in 3D space along the X, Y, and Z axes.
translate3d() Moves an element in 3D space along the X, Y, and Z axes.
perspective-
origin
Specifies the origin point of the perspective property.

backface- Specifies whether or not the back face of an element is visible when it is facing
visibility
away from the viewer.

These transform properties can be used individually or combined together to create


various transformations and achieve desired visual effects on elements within your web
page.

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 .

You can specify multiple properties in the transition property, separated by


commas. This allows you to create transitions for multiple properties simultaneously.

Transitions can be triggered by various events, such as hover , focus , active , or by


dynamically adding/removing CSS classes through JavaScript.

Property Description Applicable Tags

CSS Transforms, Transitions, and Animations 5


transition
Specifies the CSS properties to transition, duration, All HTML tags
timing function, and delay for the transition.
transition-property Specifies the CSS properties to transition. All HTML tags
transition-duration Specifies the duration of the transition. All HTML tags
transition-timing-
function
Specifies the timing function for the transition. All HTML tags

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.

Multiple keyframes can be defined in an animation, allowing you to create smooth


transitions between different styles.

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.

Test your animations on various devices and browsers to ensure consistent


behavior. Consider using feature detection libraries or polyfills to provide fallbacks
for older browsers that do not support certain CSS animation features.

For more advanced animations and fine-grained control, you may need to use
JavaScript-based animation libraries like GSAP (GreenSock Animation Platform) or

CSS Transforms, Transitions, and Animations 6


anime.js, which offer additional features and customization options.

Remember to strike a balance between adding engaging animations and maintaining a


smooth and responsive user experience. Animations should enhance the user interface
and not distract or hinder usability.

CSS Transforms, Transitions, and Animations 7


bootstrap 5
Bootstrap 5 is a free and open-source CSS framework that is used for building
responsive and mobile-first websites. It was developed and maintained by Twitter, and it
is the latest version of the popular Bootstrap framework.
Bootstrap 5 comes with a lot of new and exciting features that make it even more
powerful and flexible than its predecessor, Bootstrap 4. Some of these features include:

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.

New component additions: Bootstrap 5 includes new components such as


accordions, badges, and spinners. These components make it easier to build
complex UI elements without having to write custom code.

jQuery dependency removed: Bootstrap 5 no longer depends on jQuery, which


means that it is now a pure JavaScript framework. This makes it more lightweight
and faster than previous versions of Bootstrap.

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:

Improved grid system


Bootstrap 5 comes with a new grid system that is more intuitive and easier to use. It
includes new classes that make it easier to create responsive layouts. The grid system
is now more flexible and powerful, allowing developers to create complex layouts with
ease.

New utility classes


Bootstrap 5 includes new utility classes that make it easier to customize the look and
feel of your website. These classes allow developers to change the typography,
spacing, and colors of their websites without having to write custom CSS. This makes it
easier to create a unique and personalized look for your website.

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.

jQuery dependency removed


Bootstrap 5 no longer depends on jQuery, which means that it is now a pure
JavaScript framework. This makes it more lightweight and faster than previous
versions of Bootstrap. This means that websites built using Bootstrap 5 will load faster
and be more efficient.

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.

Smaller file size


Another important feature of Bootstrap 5 is that it has a smaller file size compared to its
predecessor, Bootstrap 4. This makes it faster to load and more efficient, which is
crucial for websites that prioritize speed.

Improved customization options


Bootstrap 5 offers improved customization options, such as the ability to choose which
components and CSS styles to include in your website. This allows developers to create
more lightweight and optimized websites.
In summary, Bootstrap 5 is a powerful and flexible CSS framework that offers a wide
range of features and customization options. Its improved grid system, new
components, and smaller file size make it a great choice for developers who want to
build responsive and mobile-first websites.

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.

Browser Support − It is supported by all popular browsers.

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.

Responsive design − Bootstrap's responsive CSS adjusts to Desktops, Tablets,


and Mobiles.

Why Learn Bootstrap? 1


Provides a clean and uniform solution for building an interface for developers.

It contains beautiful and functional built-in components which are easy to customize.

It also provides web-based customization.

And best of all it is an open source.

Hello, World using Bootstrap.


Just to give you a little excitement about Bootstrap, I'm going to give you a small
Bootstrap Program. You can edit and try running this code using Edit & Run option.

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

<div class="container-fluid p-5 bg-primary text-white text-center">

Why Learn Bootstrap? 2


<h1>Bootstrap Demo Page</h1>
<p>Resize this page to see the effect!</p>
</div>

<div class="container mt-5">


<div class="row">
<div class="col-sm-6">
<h3>Column 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
<div class="col-sm-6">
<h3>Column 2</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
</div>
</div>

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

Why Learn Bootstrap? 3


Components − Bootstrap contains over a dozen reusable components built to
provide iconography, dropdowns, navigation, alerts, pop-overs, and much more.
This is covered in detail in the section Layout Components.

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.

Customize − You can customize Bootstrap's components, fewer variables, and


jQuery plugins to get your very own version.

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.

Why Learn Bootstrap? 4


Getting Started
Creating Your First Web Page with
Bootstrap
Now we're going to create a basic Bootstrap template by including the Bootstrap CSS
and JS files via CDN. Bootstrap requires a third-party library Popper.js for some of its
components like popovers and tooltips. You can either include it separately or simply
include Bootstrap JS bundled with Popper.
We recommend adding Bootstrap to your project via CDN (Content Delivery Network)
because CDN offers performance benefits by reducing the loading time since they are
hosting the files on multiple servers spread across the globe so that when a user
requests the file it will be served from the server nearest to them. We're also using the
CDN links in our examples:
Let's walk through the following steps. At the end of this tutorial, you'll have made a
simple Bootstrap-powered web page that displays a "Hello world" message in your web
browser.

Step 1: Create a Basic HTML file


Open up your favorite code editor and create a new HTML file. Start with an empty
window and type the following code and save it as "basic.html" on your desktop.
Example:

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

Step 2: Make this HTML File a Bootstrap Template


In order to make this plain HTML file a Bootstrap template, just include the Bootstrap
CSS and JS files using their CDN links. Also, you should include JavaScript files at the
bottom of the page, right before the closing </body> tag to improve the performance of
your web pages.
Example:

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

Step 3: Saving and Viewing the File


Now save the file on your desktop as "bootstrap-template.html".
To open this file in a web browser, navigate to it, then right-click on it, and select your
favorite web browser. Alternatively, you can open your browser and drag this file to it.
Note: It is important that the extension .html is specified, some text editors, such as
Notepad on Windows, will automatically save it as .txt otherwise.

Downloading the Bootstrap Files


Alternatively, you can also download Bootstrap's CSS and JS files from their official
website and include them in your project. There are two versions available for
download, compiled Bootstrap and Bootstrap source files. You can download
Bootstrap 5 files from here.
Compiled download contains compiled and minified versions of CSS and JavaScript
files for faster and easier web development. The compiled version also includes optional
JavaScript dependencies such as Popper bundled with Bootstrap JS
( bootstrap.bundle.* ). Whereas, the source download contains original source files for all
CSS and JavaScript, along with a local copy of the docs.
Download and unzip the compiled Bootstrap. Now if you look inside the folders you'll
find it contains the compiled CSS and JS files ( bootstrap.* ), as well as the compiled
and minified CSS and JS ( bootstrap.min.* ). Use
the bootstrap.min.css and bootstrap.bundle.min.js files.

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.

Bootstrap provides three different types of containers:

.container , which has a max-width at each responsive breakpoint.

.container-fluid , which has 100% width at all breakpoints.

.container-{breakpoint} , which has 100% width until the specified breakpoint.

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.

😅I know it's a little complex to read this 😅


XX-
ClassesBootstrap Grid System X-Small<576px Small≥576px Medium≥768px Large≥992px X-Large≥1200px
Large≥1400px
.container 100% 540px 720px 960px 1140px 1320px
.container-sm 100% 540px 720px 960px 1140px 1320px
.container-md 100% 100% 720px 960px 1140px 1320px
.container-lg 100% 100% 100% 960px 1140px 1320px
.container-xl 100% 100% 100% 100% 1140px 1320px
.container-xxl 100% 100% 100% 100% 100% 1320px
.container-fluid 100% 100% 100% 100% 100% 100%

Creating Responsive Fixed-width Containers


You can simply use the .container class to create a responsive, fixed-width container. The width of the container will change at
different breakpoints or screen sizes, as shown above.

Example

<div class="container">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>

Creating Fluid Containers


You can use the .container-fluid class to create a full-width container. The width of the fluid container will always be 100%
irrespective of the devices or screen sizes.

Example:

Bootstrap Containers 1
<div class="container-fluid">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>

Specify Responsive Breakpoints for Containers


Since Bootstrap v4.4, you can also create containers that is 100% wide until the specified breakpoint is reached, after which max-
width for each of the higher breakpoints will be applied.

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:

<div class="container-sm">100% wide until screen size less than 576px</div>


<div class="container-md">100% wide until screen size less than 768px</div>
<div class="container-lg">100% wide until screen size less than 992px</div>
<div class="container-xl">100% wide until screen size less than 1200px</div>

Adding Background and Borders to Containers


By default, container doesn't have any background-color or border . But if you need you can apply your own styles, or simply use the
Bootstrap background-color and border utility classes to add background-color or border on them, as shown in the following
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>

<!-- Container with light background -->


<div class="container bg-light">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>

<!-- Container with border -->


<div class="container border">
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</div>

Applying Paddings and Margins to Containers


By default, containers have padding of 12px on the left and right sides, and no padding on the top and bottom sides. To apply extra
padding and margins you can use the spacing utility classes.
Example:

<!-- Container with border, extra paddings and margins -->


<div class="container border py-3 my-3">
<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

Bootstrap Grid System 1


Here are a few examples of how the Bootstrap grid system can be used to create
responsive layouts:
1. A simple two-column layout:

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

Bootstrap Grid System 2


<div class="col-xs-12">
Content
</div>
</div>
</div>

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.

Creating Multi-Column Layouts with


Bootstrap
With the new Bootstrap mobile first flexbox grid system, you can easily control how your
website layout will render on different types of devices that have different screen or
viewport sizes like mobile phones, tablets, desktops, etc. Let's consider the following
illustration.

Bootstrap Grid System 3


In the above illustration there are total 12 content boxes in all devices, but its placement
varies according to the device screen size, like in mobile device the layout is rendered
as one column grid layout which has 1 column and 12 rows placed above one another,
whereas in tablet it is rendered as two column grid layout which has 2 columns and 6
rows.

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.

Bootstrap Grid System 4


Now it's time to customize our layout for other devices. Let's first start by customizing it
for medium devices like tablets (768px ≤ viewport width < 1200px). Since on tablet our
layout rendered as 2x6 grids (i.e. 2 columns and 6 rows). So, go ahead and add the
class .col-md-6 on every column.
Example

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

Bootstrap Grid System 5


<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 11</p></div>
<div class="col-xl-4 col-md-6 col-xxl-3"><p>Box 12</p></div>
</div>
</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.

Nesting of Grid Columns


The Bootstrap grid columns are also nestable, that means you can put rows and
columns inside an existing column. However, the formula for placing the columns will be
the same, i.e. the sum of column numbers should be equal to 12 or less within a single
row.
ExampleTry this code »

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

Creating Variable Width Columns


You can use the col-{breakpoint}-auto classes to size columns based on the natural
width of their content. Try out the following example to see how it works:

Bootstrap Grid System 6


Example

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

Alignment of Grid Columns


You can use the flexbox alignment utilities to vertically and horizontally align grid
columns inside a container. Try out the following examples to understand how it works:

Vertical Alignment of Grid Columns


You can use the classes .align-items-start , .align-items-center , and .align-items-end to
align the grid columns vertically at the top, middle and bottom of a container,
respectively.
ExampleTry this code »

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

Bootstrap Grid System 7


</div>
</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).

Horizontal Alignment of Grid Columns


You can use the classes .justify-content-start , .justify-content-center , and .justify-
content-end to align the grid columns horizontally at the left, center and right of a

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>

Bootstrap Grid System 8


Alternatively, you can use the class .justify-content-around to distribute grid columns
evenly with half-size spaces on either end, whereas you can use the class .justify-
content-between to distribute the grid columns evenly where the first column placed at the

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>

Reordering of Grid Columns


You can even change the visual order of your grid columns without changing their order
in actual markup. Use the class .order-last to order the column in last, whereas use the
class .order-first to order the column at first place. Let's checkout an example:
Example

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

Bootstrap Grid System 9


Example

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

Offsetting the Grid Columns


You can also move grid columns to the right for alignment purpose using the column
offset classes like .offset-sm-* , .offset-md-* , .offset-lg-* , and so on.
These classes offset the columns by simply increasing its left margin by specified
number of columns. For example, the class .offset-md-4 on column .col-md-8 moves it
to the right over four columns from its original position. Try out the following example to
see how it works:
Example

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

Bootstrap Grid System 10


</div>
<div class="row">
<div class="col-auto me-auto"></div>
<div class="col-auto"><!--Move this column away from previous column--></div>
</div>
</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.

Creating Compact Columns


You can remove the default gutters between columns to create compact layouts by
adding the class .g-0 on .row . This class removes the negative margins from row and
the horizontal padding from all immediate children columns. Here's an example:
Example

<div class="row g-0">


<div class="col-4">Column one</div>
<div class="col-4">Column two</div>
<div class="col-4">Column three</div>
</div>

Breaking Columns to a New Line


You can also create equal-width columns that span multiple rows by inserting
a <div> with .w-100 class where you want the columns to break to a new line.
Additionally, you can make these breaks responsive by combining the .w-100 class
with responsive display utility classes.
Example

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

Bootstrap Grid System 11


<div class="col">.col</div>
</div>
<!-- Break columns on all devices except extra large devices -->
<div class="row">
<div class="col">.col</div>
<div class="col">.col</div>
<div class="w-100 d-xl-none"></div>
<div class="col">.col</div>
<div class="col">.col</div>
</div>
</div>

We hope you've understood the basics of the new Bootstrap 5 grid system.

Bootstrap Grid System 12


Bootstrap Typography
Bootstrap provides a comprehensive set of typographic styles and utilities that allow you
to easily enhance and control the appearance of text on your website. These
typography classes are designed to create consistent and visually appealing text
elements throughout your web pages. In this section, we will explore the different
typography features offered by Bootstrap and provide examples of their usage.

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:

<h1 class="display-1">Display Heading 1</h1>


<h1 class="display-2">Display Heading 2</h1>
<h1 class="display-3">Display Heading 3</h1>
<h1 class="display-4">Display Heading 4</h1>

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-muted class can be used to dim or de-emphasize text.

The .text-primary , .text-secondary , , .text-danger , .text-warning ,


.text-success

.text-info , .text-light , .text-dark , .text-white , and .text-body classes can be

used to apply specific colors to the text.

The .text-uppercase class can be used to transform text to uppercase.

The .text-lowercase class can be used to transform text to lowercase.

The .text-capitalize class can be used to capitalize the first letter of each word in
the text.

Example usage:

<p class="text-muted">This text is muted and de-emphasized.</p>


<p class="text-primary">This text has a primary color.</p>
<p class="text-uppercase">This text is transformed to uppercase.</p>
<p class="text-capitalize">This text has each word capitalized.</p>

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.

See the tutorial on HTML tables to learn more about tables.

Creating a Simple Table with Bootstrap


You can create tables with basic styling that has horizontal dividers and small cell
padding (8px by default), by just adding the Bootstrap's class .table to
the <table> element.
Example

<!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:

Creating Accented Tables


Bootstrap even provides a handful of contextual classes such as .table-primary , .table-

secondary , .table-success , .table-danger , .table-warning , .table-info , .table-

light and .table-dark to color tables, table rows or individual cells.

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>

<table class="table table-secondary">


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

<table class="table table-success">


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

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>

<table class="table table-danger">


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

<table class="table table-warning">


<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>

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>

<table class="table table-info">


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

Bootstrap Tables 7
</table>

<table class="table table-light">


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

All About Bootstrap Tables

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.

Definition list — A list of terms with their associated descriptions.

See the tutorial on HTML lists, to learn more about the different lists types.

Unstyled Ordered and Unordered Lists


Sometimes you might need to remove the default styling form the list items. You can do
this by simply applying the class .list-unstyled to the
respective <ul> or <ol> elements.
Example

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

Placing Ordered and Unordered List Items


Inline
If you want to create a horizontal menu using the ordered or unordered list you need to
place all list items in a single line (i.e. side by side). You can do this simply by adding
the class .list-inline to the <ul> or <ol> , and the class .list-inline-item to the
child <li> elements.
Example

<!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:

Creating Horizontal Definition Lists


The terms and descriptions in a definition list can also be aligned horizontally side-by-
side using the Bootstrap grid system's predefined classes. Here's an example:
Example

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

Customization options to match the form's appearance to your website's design.

Now, let's move on to setting up Bootstrap and creating a basic form.

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.

Basic Form Structure:


The basic structure of a Bootstrap form consists of a <form> element and one or more
form controls. The <form> element acts as a container for the form controls and is used
to submit the form data to the server.
Here's an example of a basic Bootstrap form:

<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

utility) between form controls.


The btn and btn-primary classes are applied to the submit button to style it as a
primary button with the default Bootstrap primary color.

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.

Form Layout Options:


Bootstrap provides two main layout options for arranging form controls: inline forms and
horizontal forms.

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.

<form class="row g-3">


<div class="col-auto">
<label for="horizontalInput" class="form-label">Email</label>
<input type="email" class="form-control" id="horizontalInput" placeholder="Email">
</div>
<div class="col-auto">

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 .

Here's an example of a form control with validation states:

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

Form Validation with JavaScript:


Bootstrap also provides JavaScript components that can be used for more
advanced form validation scenarios. These components allow you to create custom
validation behaviors and provide dynamic 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.

Here's an example of a form with JavaScript-based validation:

<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');

// Loop over them and prevent submission


Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();

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.

Customizing Forms with Bootstrap:


Bootstrap Forms can be easily customized to match your website's design by overriding
the default Bootstrap styles or by using custom CSS classes. You can leverage the
extensive set of utility classes provided by Bootstrap or create your own styles.
Here's an example of customizing a form using Bootstrap utility classes:

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

More About Forms

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:

Pre-styled buttons with different styles, such as primary, secondary, success,


danger, etc.

Various button sizes, including small, large, and block buttons.

Button states and interactions, such as active, disabled, and toggling.

Button groups and toolbar options.

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:

<button class="btn btn-primary">Click me</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.

Alternatively, you can use an <a> element to create a button-like link:

<a href="#" class="btn btn-primary">Click me</a>

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:

<button class="btn btn-primary">Primary</button>

Bootstrap Buttons 2
Secondary Button:

<button class="btn btn-secondary">Secondary</button>

Success Button:

<button class="btn btn-success">Success</button>

Danger Button:

<button class="btn btn-danger">Danger</button>

Warning Button:

<button class="btn btn-warning">Warning</button>

Info Button:

<button class="btn btn-info">Info</button>

Light Button:

<button class="btn btn-light">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:

<button class="btn btn-primary btn-sm">Small Button</button>

Default Button:
(Default size buttons don't require any additional size class.)

<button class="btn btn-primary">Default Button</button>

Large Button:

<button class="btn btn-primary btn-lg">Large Button</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

class to a button to indicate the active state.

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.

<button class="btn btn-primary disabled" disabled>Disabled Button</button>

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.

Here's an example of a toggle button:

<button class="btn btn-primary" type="button" data-bs-toggle="button" autocomplete="off">


Toggle Button</button>

In this example, the data-bs-toggle="button" attribute enables the toggle functionality.


The autocomplete="off" attribute is added to prevent browser interference with the toggle
state.
7. Block Buttons and Button Groups:
Bootstrap Buttons can also be displayed as block-level elements, stretching across the
full width of their parent container. This is useful when you want buttons to occupy the
entire available width.
To create a block button, add the btn-block class to the button element:

<button class="btn btn-primary btn-block">Block Button</button>

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:

<div class="btn-group" role="group" aria-label="Button group">


<button class="btn btn-primary">Button 1</button>
<button class="btn btn-primary">Button 2</button>
<button class="btn btn-primary">Button 3</button>
</div>

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.

8. Customizing Buttons with Bootstrap:


Bootstrap Buttons can be customized further to match your website's design by
overriding the default Bootstrap styles or using custom CSS classes. You can leverage
the extensive set of utility classes provided by Bootstrap or create your own styles.
Here's an example of customizing a button using Bootstrap utility classes:

<button class="btn btn-primary btn-lg btn-rounded">Custom Button</button>

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:

<img src="path/to/image.jpg" alt="Image" class="img-fluid">

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:

<img src="path/to/image.jpg" alt="Thumbnail" class="img-thumbnail">

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:

<img src="path/to/image.jpg" alt="Image" class="rounded">

<img src="path/to/image.jpg" alt="Image" class="rounded-circle">

<img src="path/to/image.jpg" alt="Image" class="rounded-pill">

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:

<img src="path/to/image.jpg" alt="Image" class="float-start">

<img src="path/to/image.jpg" alt="Image" class="float-end">

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.

Image Thumbnails Grid


Bootstrap also offers a grid-based approach for displaying multiple images in a
thumbnail grid. You can use the row and col-* classes to create a responsive grid
layout. Here's an example:

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

More About Images

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.

Basic Card Structure

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.

Card Headers and Footers


Card headers and footers are optional components that can be used to provide
additional information or context to the card content. To add a header to a card, use the
card-header class:

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

Card Titles and Subtitles


You can add titles and subtitles to cards using the card-title and card-subtitle classes,
respectively. These classes are typically applied to heading elements ( <h*> ) within the
card content. Here's an example:

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

Card Text and Links


To add textual content to a card, use the card-text class. This class is typically applied
to a <p> element within the card content. Here's an example:

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

<div class="card bg-primary text-white">


<div class="card-body">
Card Content
</div>
</div>

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:

<div class="card border-primary">


<div class="card-body">
Card Content
</div>
</div>

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

More About Bootstrap Cards

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.

Basic Media Object Structure

Bootstrap Media Objects 1


A Bootstrap Media Object consists of an image or media component aligned to the left
or right, and text content placed alongside it. The basic structure of a media object
includes a container <div> with the class media . Inside the media container, you can
add an image or media component and the textual content. Here's an example of a
basic media object structure:

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

Media Object Alignment


Bootstrap allows you to align the media component either to the left or right of the text
content. By default, the media component is aligned to the left. To align it to the right,
you can add the class float-right to the media component. Here's an example:

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

Bootstrap Media Objects 2


Nested Media Objects
Bootstrap also allows you to nest media objects within each other, creating a
hierarchical structure. This is useful when you want to display multiple media objects
that are related or have a parent-child relationship. Here's an example of nested media
objects:

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

<!-- Nested media object -->


<div class="media mt-3">
<img src="path/to/image2.jpg" alt="Media Object 2" class="mr-3">
<div class="media-body">
<h5 class="mt-0">Media Object Title 2</h5>
<p>Media Object Text 2</p>
</div>
</div>
</div>
</div>

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.

Media Object Sizing


Bootstrap provides different sizing options for media objects. You can use the media
class along with the media-* classes to adjust the size of the media component. The
available sizes are sm , md , and lg . Here's an example:

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

Bootstrap Media Objects 3


In this example, the media-lg class is added to the <img> tag to set the media
component to the large size.

Media Object Alignment Classes


Bootstrap provides alignment classes to control the vertical alignment of the media
component within the media object. The available classes are align-self-start , align-

self-center , and align-self-end . Here's an example:

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

More About Bootstrap Media Objects

Bootstrap Media Objects 4


Bootstrap Icons
Bootstrap Icons is a popular icon library that provides a wide range of scalable vector
icons that can be easily integrated into your web projects. These icons are designed to
be used with Bootstrap components but can also be used independently. In this
explanation, we'll explore the features and options available for working with Bootstrap
Icons.

Adding Bootstrap Icons


To use Bootstrap Icons in your project, you need to include the Bootstrap Icons library in
your HTML file. You have two options: hosting the library locally or using a Content
Delivery Network (CDN). Here's an example of including the Bootstrap Icons library
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-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.

Using Bootstrap Icons


Once you have included the Bootstrap Icons library, you can start using the icons in
your project. Bootstrap Icons can be added to your HTML markup using the <i> tag.
Here's an example of adding a heart icon:

<i class="bi bi-heart"></i>

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:

<i class="bi bi-heart bi-sm"></i> <!-- Small size -->


<i class="bi bi-heart bi-lg"></i> <!-- Large size -->
<i class="bi bi-heart bi-2x"></i> <!-- 2x size -->

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:

<i class="bi bi-heart text-primary"></i> <!-- Primary color -->


<i class="bi bi-heart text-danger"></i> <!-- Danger color -->

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.

Additional Icon Classes


Bootstrap Icons provide additional classes to customize the icon's appearance and
behavior. Some commonly used classes include:

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 .

bi-spin : Adds a spinning animation to the icon.

Here's an example that demonstrates the usage of these classes:

<i class="bi bi-heart bi-rotate-90 bi-flip-horizontal bi-spin"></i>

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:

<i class="bi bi-heart" aria-label="Heart"></i>

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.

All About Bootstrap Icons

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.

Basic Navbar Structure


The basic structure of a Bootstrap Navbar consists of a container <nav> element with
the class navbar . Inside the navbar, you can add a logo or brand, navigation links, and

Bootstrap Navbar 1
other components. Here's an example of a basic navbar structure:

<nav class="navbar navbar-expand-lg navbar-light bg-light">


<a class="navbar-brand" href="#">Logo</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#
navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>

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:

<nav class="navbar navbar-expand-lg navbar-light bg-light">


<a class="navbar-brand" href="#">Logo</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#
navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" dat
a-bs-toggle="dropdown" aria-expanded="false">
Services
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Service 1</a></li>
<li><a class="dropdown-item" href="#">Service 2</a></li>
<li><a class="dropdown-item" href="#">Service 3</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</nav>

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

the data-bs-target attribute is not required for dropdown menus.


The dropdown menu itself is defined using a nested <ul> element with the dropdown-
menu class. Each dropdown menu item is represented by an <li> element with the <a>

tag inside.

Navbar Color Schemes

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:

navbar-light : Sets the navbar background to a light color.

navbar-dark : Sets the navbar background to a dark color.

bg-primary, bg-success , bg-info , bg-warning , bg-danger : Sets the navbar background


to a specific Bootstrap color.

You can combine these classes to create various color schemes for your navbar. For
example:

<nav class="navbar navbar-expand-lg navbar-light bg-light">


<!-- Navbar content -->
</nav>

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:

navbar-expand-sm : Collapse the navbar at the small ( sm ) breakpoint.

navbar-expand-md : Collapse the navbar at the medium ( md ) breakpoint.

navbar-expand-lg : Collapse the navbar at the large ( lg ) breakpoint.

navbar-expand-xl : Collapse the navbar at the extra-large ( xl ) breakpoint.

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>

Additional Navbar Features


Bootstrap Navbar provides many additional features and options to enhance your
navigation menu. Here are a few notable ones:

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.

More About Bootstrap Navbar

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.

Basic Modal Structure


The basic structure of a Bootstrap Modal consists of a trigger element and a modal
container. The trigger element, such as a button or a link, is used to open the modal
when clicked. The modal container holds the content that is displayed within the modal.
Here's an example of a basic modal structure:

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myM


odal">
Open Modal
</button>

<div class="modal" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hid


den="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal Title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Clos
e"></button>
</div>
<div class="modal-body">
<p>Modal content goes here...</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</but
ton>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

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

data-bs-target attribute is used to specify the ID of the modal container.

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.

Modal Options and Events


Bootstrap Modals offer various options and events that allow you to customize and
control the behavior of the modals. Here are a few notable ones:

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-

dialog-centered , modal-dialog-sm , modal-dialog-lg , or modal-dialog-xl .

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.

data-bs-backdrop="static" : The modal will not close when the backdrop is


clicked.

data-bs-backdrop="false" : The backdrop is disabled, and clicking outside the


modal will not close it.

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.

show.bs.modal : This event is fired immediately when the modal is about to be


shown.

shown.bs.modal : This event is fired when the modal is fully shown (after CSS
transitions have completed).

hide.bs.modal : This event is fired immediately when the modal is about to be


hidden.

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.

Modal Content and Components


Bootstrap Modals can contain various types of content and components, allowing you to
create interactive and engaging user interfaces. Here are a few examples:

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.

More About Bootstrap Modals

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.

Basic Dropdown Structure


The basic structure of a Bootstrap Dropdown consists of a trigger element and a
dropdown menu. The trigger element, such as a button or a link, is used to toggle the
visibility of the dropdown menu. The dropdown menu contains a list of items or actions
that are displayed when the dropdown is opened. Here's an example of a basic
dropdown structure:

<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 Options and Variations


Bootstrap Dropdowns offer various options and variations that allow you to customize
their appearance and behavior. Here are a few notable ones:

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.

Dropdown Triggers and Behaviors


Bootstrap Dropdowns can be triggered by different events and have different behaviors.
The data-bs-toggle attribute specifies the trigger event, and the data-bs-target attribute
specifies the ID of the dropdown menu.

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:

<nav class="navbar navbar-expand-lg navbar-light bg-light">


<div class="container">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target
="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label
="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="b
utton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
</ul>
</div>
</div>
</nav>

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.

More About Bootstrap Dropdowns

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.

Basic Alert Structure


The basic structure of a Bootstrap Alert consists of a container element and a close
button. The container element holds the content and styling of the alert. The close
button allows users to dismiss or hide the alert. Here's an example of a basic alert
structure:

<div class="alert alert-primary" role="alert">


This is a primary alert.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></but
ton>
</div>

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.

Alert Colors and Variations


Bootstrap Alerts come with several color variations that can be used to differentiate the
type or urgency of the message being displayed. Here are some commonly used color

Bootstrap Alerts 1
classes:

alert-primary : Blue color for general information.

alert-secondary : Gray color for less important information.

alert-success : Green color for success messages.

alert-danger : Red color for error or danger messages.

alert-warning : Yellow color for warning messages.

alert-info : Light blue color for informational messages.

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:

var alertElement = document.querySelector('.alert');


alertElement.alert('close');

Additional Alert Options


Bootstrap Alerts provide additional options and variations to enhance their appearance
and functionality. Here are a few notable ones:

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.

All About Bootstrap Alerts

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.

Basic Carousel Structure


The basic structure of a Bootstrap Carousel consists of a container element, slide items,
and navigation controls. The container element holds the carousel components and
provides the necessary styling. The slide items represent the individual slides or items
that will be displayed in the carousel. The navigation controls allow users to navigate
between the slides. Here's an example of a basic carousel structure:

<div id="myCarousel" class="carousel slide" data-bs-ride="carousel">


<div class="carousel-inner">
<div class="carousel-item active">
<img src="image1.jpg" alt="Slide 1">
<div class="carousel-caption">
<h3>Slide 1</h3>
<p>Slide 1 Description</p>
</div>
</div>
<div class="carousel-item">
<img src="image2.jpg" alt="Slide 2">
<div class="carousel-caption">
<h3>Slide 2</h3>
<p>Slide 2 Description</p>
</div>
</div>
<div class="carousel-item">
<img src="image3.jpg" alt="Slide 3">
<div class="carousel-caption">
<h3>Slide 3</h3>
<p>Slide 3 Description</p>
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#myCarousel" data-bs
-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#myCarousel" data-bs

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.

Carousel Options and Variations


Bootstrap Carousel provides various options and variations to customize its behavior
and appearance. Here are a few notable ones:

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

the index of each slide.

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.

Customizing Carousel Styles


You can customize the appearance of the Bootstrap Carousel by overriding or adding
CSS classes. Bootstrap provides a set of CSS classes that you can use to modify the
default styles. For example, you can change the size, colors, margins, or add custom
animations to the carousel.
You can also apply your own custom CSS styles to the carousel elements by targeting
their respective classes or IDs. This allows you to fully customize the look and feel of
the carousel to match your design requirements.

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

More About Bootstrap Carousel

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 auto layout columns for all devices

Bootstrap columns sizing based on the width of their content

Bootstrap multi column grid layout for all devices

Bootstrap nested grid columns layout

Bootstrap vertical alignment of columns within a row

Bootstrap vertical alignment of individual columns within a row

Bootstrap reordering of grid columns within a row

Bootstrap offsetting grid columns

Bootstrap compact grid columns

Bootstrap fixed layout

Bootstrap fluid layout

Bootstrap responsive layout

Bootstrap Typography
Bootstrap headings

Bootstrap headings with secondary text

Bootstrap display headings

Bootstrap normal and lead paragraphs

Bootstrap text alignment

Bootstrap text formatting

Bootstrap 5 Examples 1
Bootstrap text transformation

Bootstrap text emphasis classes

Bootstrap blockquotes formatting

Bootstrap truncating long text

Bootstrap handling text overflow

Bootstrap breaking long words

Bootstrap Tables
Creating simple tables with Bootstrap

Creating dark tables with Bootstrap

Creating accented tables with Bootstrap

Bootstrap table with accented rows

Bootstrap table with striped rows

Bootstrap table with borders

Creating borderless table with Bootstrap

Enable hover state on table rows

Bootstrap small or compact table

Setting light background for table head with Bootstrap

Setting dark background for table head with Bootstrap

Bootstrap responsive tables

Bootstrap Lists
Creating lists with Bootstrap

Bootstrap unstyled ordered and unordered list

Placing ordered and unordered list items inline

Creating horizontal definition lists with Bootstrap

Bootstrap 5 Examples 2
Bootstrap list groups

Bootstrap list group with disabled and active items

Bootstrap edge-to-edge list groups

Bootstrap numbered list groups

Bootstrap list group with checkboxes

Bootstrap list group with radio buttons

Bootstrap list group with linked items

Bootstrap linked list group with custom content

Bootstrap list groups with emphasis classes

Bootstrap linked list groups with emphasis classes

Bootstrap Forms
Creating vertical form layouts with Bootstrap

Creating horizontal form layouts with Bootstrap

Creating inline form layouts with Bootstrap

Creating responsive form layouts with Bootstrap

Bootstrap static form controls

Placing checkboxes inline with Bootstrap

Placing radio buttons inline with Bootstrap

Height sizing of Inputs and select boxes with Bootstrap

Grid sizing of form controls with Bootstrap

Disabling form controls with Bootstrap

Disabling all form controls at once with Bootstrap

Creating readonly inputs with Bootstrap

Placing block help text around form controls

Placing inline help text around form controls

Bootstrap 5 Examples 3
Bootstrap form validation

Displaying Bootstrap validation feedback in tooltip style

Supported form controls in Bootstrap

Bootstrap Custom Forms


Creating custom checkboxes with Bootstrap

Creating custom radio buttons with Bootstrap

Disabling custom checkboxes and radio buttons in Bootstrap

Creating toggle switch with Bootstrap

Creating custom select menu with Bootstrap

Height sizing of Bootstrap custom select menu

Creating custom range input with Bootstrap

Specifying min, max and step attributes for Bootstrap custom range

Bootstrap Input Groups


Prepend and append inputs with Bootstrap

Prepend and append select box and textarea with Bootstrap

Creating input groups with checkbox and radio buttons in Bootstrap

Placing multiple inputs within an input group in Bootstrap

Placing multiple addons within an input group in Bootstrap

Placing buttons within an input group in Bootstrap

Placing button dropdowns within an input group in Bootstrap

Placing segmented dropdown button groups within an input group in Bootstrap

Height sizing of Bootstrap input groups

Bootstrap Buttons

Bootstrap 5 Examples 4
Creating buttons with Bootstrap

Creating outline buttons styles in Bootstrap

Creating large buttons with Bootstrap

Creating small buttons with Bootstrap

Creating block buttons with Bootstrap

Creating disabled Bootstrap buttons using the input and button element

Creating disabled Bootstrap buttons using the anchor element

Enable active state on buttons in Bootstrap

Creating spinner buttons in Bootstrap

Bootstrap Button Groups


Creating button groups with Bootstrap

Creating outline button groups with Bootstrap

Creating mixed styles button groups with Bootstrap

Creating button toolbar with Bootstrap

Height sizing of Bootstrap button groups

Creating nested button groups in Bootstrap

Creating vertically stacked button groups in Bootstrap

Creating justified button groups with Bootstrap

Creating toggle button in Bootstrap

Creating checkbox button groups with Bootstrap

Creating radio button groups with Bootstrap

Bootstrap Images
Making thumbnails, rounded corner and circular images with Bootstrap

Making responsive images with Bootstrap

Bootstrap 5 Examples 5
Making responsive videos with Bootstrap

Horizontal alignment of images with Bootstrap

Creating media objects with Bootstrap

Creating rounded media objects with Bootstrap

Creating nested media objects with Bootstrap

Horizontal alignment of media objects in Bootstrap

Vertical alignment of media objects in Bootstrap

Bootstrap Cards
Creating cards with Bootstrap

Creating body only cards with Bootstrap

Creating Bootstrap cards with titles text and links

Adding header and footer to a card in Bootstrap

Placing list group inside Bootstrap card

Creating a card with multiple content types in Bootstrap

Customizing the card background in Bootstrap

Customizing the card border and text in Bootstrap

Creating cards group with Bootstrap

Creating cards grid with Bootstrap

Creating horizontal cards with Bootstrap

Creating cards having image in the background in Bootstrap

Aligning text inside the card in Bootstrap

Setting the size for cards in Bootstrap

Making the whole card clickable in Bootstrap

Bootstrap Icons

Bootstrap 5 Examples 6
Including Bootstrap icons in a web page

Including font-awesome icons in Bootstrap

Placing icons inside buttons in Bootstrap

Using icons inside tabs in Bootstrap

Using icons inside pills nav in Bootstrap

Using icons inside list groups in Bootstrap

Using icons inside input groups in Bootstrap

Bootstrap Navs
Creating basic nav with Bootstrap

Center alignment of Bootstrap nav

Right alignment of Bootstrap nav

Creating vertically stacked Bootstrap nav

Creating basic tabs with Bootstrap

Adding icons to tabs in Bootstrap

Creating basic pills nav with Bootstrap

Adding icons to pills nav in Bootstrap

Creating vertically stacked pills nav with Bootstrap

Adding dropdown menus to tabs in Bootstrap

Adding dropdown menus to pills nav in Bootstrap

Creating fill nav with Bootstrap

Creating justified nav with Bootstrap

Bootstrap Navbar
Creating navbar with Bootstrap

Adding logo image to navbar in Bootstrap

Bootstrap 5 Examples 7
Adding dropdown menus to navbar in Bootstrap

Placing search form inside navbar in Bootstrap

Changing the color scheme of Bootstrap navbar

Creating Bootstrap navbar fixed to top

Creating Bootstrap navbar fixed to bottom

Creating sticky top navbar with Bootstrap

Bootstrap Accordion
Creating accordion with Bootstrap

Creating accordion with plus minus icons in Bootstrap

Creating edge-to-edge accordion with Bootstrap

Creating accordion with independent collapsible panels in Bootstrap

Bootstrap Breadcrumbs and Pagination


Creating breadcrumbs with Bootstrap

Changing breadcrumbs separator in Bootstrap

Creating pagination with Bootstrap

Bootstrap pagination with disabled and active states

Using span element for disabled link in Bootstrap pagination

Changing the sizes of Bootstrap pagination

Center alignment of Bootstrap pagination

Right alignment of Bootstrap pagination

Bootstrap Badges
Creating badges with Bootstrap

Creating colored badges with Bootstrap

Bootstrap 5 Examples 8
Creating pill badges with Bootstrap

Showing counter with Bootstrap badges

Positioning of Bootstrap badges

Bootstrap Progress Bars


Creating progress bars with Bootstrap

Adding label to a progress bar in Bootstrap

Changing the height of a progress bar in Bootstrap

Creating stripped progress bars with Bootstrap

Creating animated progress bars with Bootstrap

Changing the value of a Bootstrap progress bar dynamically

Creating stacked progress bars with Bootstrap

Creating multi-color progress bars in Bootstrap

Creating multi-color striped progress bars in Bootstrap

Bootstrap Spinners
Creating border spinners with Bootstrap

Creating colored spinners with Bootstrap

Creating growing spinners with Bootstrap

Creating colored growing spinners with Bootstrap

Creating small size spinners with Bootstrap

Customizing the size of Bootstrap spinners with CSS

Placing spinners inside buttons in Bootstrap

Changing the alignment of spinners in Bootstrap

Bootstrap Jumbotron

Bootstrap 5 Examples 9
Creating jumbotron to showcase content in Bootstrap

Creating full width jumbotron in Bootstrap

Bootstrap Modals
Creating modals with Bootstrap

Launching Bootstrap modal box via data attributes

Launching Bootstrap modal box via JavaScript

Changing the size of modals in Bootstrap

Changing the Bootstrap modal content based on the trigger button via JavaScript

Vertically centering the Bootstrap modal

Creating row and columns inside Bootstrap modal

Loading content in Bootstrap modal via Ajax using 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

Bootstrap toggle() modal method

Bootstrap show() modal method

Bootstrap hide() modal method

Bootstrap handleUpdate() modal method

Bootstrap dispose() modal method

Bootstrap getInstance() modal method

Bootstrap getOrCreateInstance() modal method

Display a message when Bootstrap modal window has been completely closed

Display a message on click outside the Bootstrap modal window

Bootstrap Dropdowns

Bootstrap 5 Examples 10
Creating dropdown menu in Bootstrap

Adding dropdowns to Bootstrap navbar

Adding dropdowns to Bootstrap navs

Adding dropdowns to Bootstrap buttons

Adding dropdowns to Bootstrap split buttons

Adding dropdowns to Bootstrap button groups

Adding dropdowns within Bootstrap vertically stacked button groups

Creating dropup, dropleft and dropright menus in Bootstrap

Creating right aligned dropdown menus in Bootstrap

Adding headers to dropdown items in Bootstrap

Disabling items inside a dropdown menu in Bootstrap

Adding dropdown to an element via JavaScript

Bootstrap toggle() dropdown method

Bootstrap show() dropdown method

Bootstrap hide() dropdown method

Bootstrap update() dropdown method

Bootstrap dispose() dropdown method

Bootstrap getInstance() dropdown method

Bootstrap getOrCreateInstance() dropdown method

Get the text content of dropdown link on click in Bootstrap

Bootstrap Tabs
Creating a basic tabs with Bootstrap

Creating dynamic tabs in Bootstrap via data attributes

Creating dynamic tabs in Bootstrap via JavaScript

Activate individual Bootstrap tabs via JavaScript

Bootstrap 5 Examples 11
Bootstrap show() tab method

Bootstrap dispose() tab method

Bootstrap getInstance() tab method

Bootstrap getOrCreateInstance() tab method

Get the names of active tab and previous tab in Bootstrap via JavaScript

Bootstrap Tooltips
Creating tooltips with Bootstrap

Setting the position of Bootstrap tooltips via data attributes

Setting the position of Bootstrap tooltips via JavaScript

Setting the title text for Bootstrap tooltips via JavaScript

Inserting HTML content inside the Bootstrap tooltips via JavaScript

Setting the show hide timing of Bootstrap tooltips via JavaScript

Creating the custom template for Bootstrap tooltips via JavaScript

Setting the container element for Bootstrap tooltips via JavaScript

Bootstrap show() tooltip method

Bootstrap hide() tooltip method

Bootstrap toggle() tooltip method

Bootstrap dispose() tooltip method

Bootstrap enable() tooltip method

Bootstrap disable() tooltip method

Bootstrap toggleEnabled() tooltip method

Bootstrap update() tooltip method

Bootstrap getInstance() tooltip method

Bootstrap getOrCreateInstance() tooltip method

Display a message when Bootstrap tooltip fade out transition has been completed

Bootstrap 5 Examples 12
Bootstrap Popovers
Creating popovers with Bootstrap

Setting the position of Bootstrap popovers via data attributes

Setting the position of Bootstrap popovers via JavaScript

Dismiss Bootstrap popovers on next click

Setting the title text for Bootstrap popovers via JavaScript

Inserting HTML content inside the Bootstrap popovers via JavaScript

Setting the show hide timing of Bootstrap popovers via JavaScript

Creating the custom template for Bootstrap popovers via JavaScript

Setting the container element for Bootstrap popovers via JavaScript

Bootstrap show() popover method

Bootstrap hide() popover method

Bootstrap toggle() popover method

Bootstrap dispose() popover method

Bootstrap enable() popover method

Bootstrap disable() popover method

Bootstrap toggleEnabled() popover method

Bootstrap update() popover method

Bootstrap getInstance() popover method

Bootstrap getOrCreateInstance() popover method

Display a message when Bootstrap popover fade out transition has been completed

Bootstrap Alerts Messages


Creating success, error, warning and info alert messages with Bootstrap

Creating primary, secondary, dark, and light alert messages with Bootstrap

Bootstrap 5 Examples 13
Adding icons to Bootstrap alerts

Placing additional content inside Bootstrap alerts

Matching links color inside Bootstrap alerts

Dismissal of Bootstrap alerts via data attributes

Dismissal of Bootstrap alerts via JavaScript

Bootstrap close() alert method

Bootstrap dispose() alert method

Bootstrap getInstance() alert method

Bootstrap getOrCreateInstance() alert method

Display a message when Bootstrap alert has been completely closed

Bootstrap Collapse
Expanding and collapsing elements via data attributes

Expanding and collapsing elements via JavaScript

Bootstrap .collapse(options) method

Bootstrap .collapse('toggle') method

Bootstrap .collapse('show') method

Bootstrap .collapse('hide') method

Display a message when collapsible element has been completely closed

Bootstrap Carousel
Creating carousels with Bootstrap

Adding captions to Bootstrap carousel items

Creating dark variant of Bootstrap carousel

Activate Bootstrap carousels via data attributes

Activate Bootstrap carousels via JavaScript

Bootstrap 5 Examples 14
Removing auto-sliding from Bootstrap carousel via JavaScript

Bootstrap cycle() carousel method

Bootstrap pause() carousel method

Bootstrap prev() carousel method

Bootstrap next() carousel method

Bootstrap nextWhenVisible() carousel method

Bootstrap to() carousel method

Bootstrap dispose() carousel method

Bootstrap getInstance() carousel method

Bootstrap getOrCreateInstance() carousel method

Display a message when sliding of a Bootstrap carousel item has been completed

Bootstrap Typeahead
Creating Twitter typeahead with local dataset

Creating Twitter typeahead with external dataset

Bootstrap ScrollSpy
Creating scrollspy with Bootstrap

Adding scrollspy to Bootstrap navbar via data attributes

Adding scrollspy to Bootstrap navbar via JavaScript

Adding offset to Bootstrap scrollspy via JavaScript

Bootstrap refresh() scrollspy method

Bootstrap dispose() scrollspy method

Bootstrap getInstance() scrollspy method

Bootstrap getOrCreateInstance() scrollspy method

Display the name of menu items when it is highlighted by the scrollspy

Bootstrap 5 Examples 15
Get the nav item currently highlighted by Bootstrap scrollspy via JavaScript

Bootstrap Toasts
Creating toasts with Bootstrap

Stacking toasts vertically in Bootstrap

Placing Bootstrap toasts on screen with CSS

Stop hiding Bootstrap toasts automatically via data attributes

Disable Bootstrap toasts autohide via JavaScript

Increasing Bootstrap toasts autohide time via JavaScript

Bootstrap show() toast method

Bootstrap hide() toast method

Bootstrap dispose() toast method

Bootstrap getInstance() toast method

Bootstrap getOrCreateInstance() toast method

Display a message when Bootstrap toast has been completely closed

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:

ECMAScript provides the core functionality.

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.

Client-side vs. Server-side JavaScript


When JavaScript is used on a web page, it is executed in web browsers. In this case,
JavaScript works as a client-side language.
JavaScript can run on both web browsers and servers. A popular JavaScript server-side
environment is Node.js. Unlike client-side JavaScript, server-side JavaScript executes
on the server that allows you to access databases, file systems, etc.

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 in Netscape Navigator

JScript in Internet Explorer.

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 call the add() function, you use the following syntax:

let result = add(x, y);

To log the result into the console window of the web browser, you use
the console.log() :

console.log(result);

Now, you should see 30 in the console window.

JavaScript 3
JavaScript provides you with condition statements such as if-

else and switch statements. For example:

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:

let items = [];

To declare an array with some initial elements, you specify the elements in the square
brackets:

let items = [1, 2, 3];

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:

for(let i = 0; i < items.length; i++) {


console.log(items[i]);
}

JavaScript 4
Or use the for...of loop in ES6:

for(let item of items) {


console.log(item);
}

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:

<script>console.log('Hello, dev tools!');

// the following code causes an error let greeting = msg;


</script>

Second, press F12 on Windows or Cmd+Opt+J if you are on Mac.

The dev tools will open the Console tab by default. It will look like this:

Web Development Tools 1


The first message is 'Hello, DevTools!' which is the output of the following command:

console.log('Hello, DevTools!');

To output the value of the variable, you use the following console.log() method. For
example:

let message = 'Good Morning!';


console.log(message);

The second message that appears on the Console tab is an error.

Uncaught ReferenceError: msg is not defined

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.

Firefox and Edge


Typically, you open the Console tab of the devtools in Firefox and Edge using F12 . They
have similar user interfaces.

Safari
If you are using Safari browser on Mac, you need to enable the Developer Menu first:

Web Development Tools 2


Web Development Tools 3
And then press Cmd+Opt+C to toggle the Console window

Web Development Tools 4


JavaScript Hello World
To insert JavaScript into an HTML page, you use the <script> element. There are two
ways to use the <script> element in an HTML page:

Embed JavaScript code directly into the HTML page.

Reference an external JavaScript code file.

Embed JavaScript code on an HTML page


Placing JavaScript code inside the <script> element directly is not recommended and
should be used only for proof of concept or testing purposes.
The JavaScript code in the <script> element is interpreted from top to bottom. For
example:

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

In the element, we use the


<script> alert() function to display the Hello,

World! message.

Include an external JavaScript file


To include a JavaScript from an external file:

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.

JavaScript Hello World 1


Then, use the URL to the JavasScript source code file in the src attribute of
the <script> element.

The following shows the contents of the app.js file:

alert('Hello, World!');

And the following shows the helloworld.html file:

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

JavaScript Hello World 2


For the page that includes many external JavaScript files, the blank page is shown
during the page rendering phase.
To avoid this, you include the JavaScript file just before the </body> tag as shown in this
example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Hello World Example</title>
</head>
<body>

<!-- end of page content here-->


<script src="js/service.js"></script>
<script src="js/app.js"></script>
</body>
</html>

The async and defer attributes


To change how the browser load and execute JavaScript files, you use one of two
attributes of the <script> element async and defer .
These attributes take effect only on the external script files. The async attribute instructs
the web browser to execute the JavaScript file asynchronously. The async attribute
does not guarantee the script files to execute in the order they appear. For example:

<script async src="service.js"></script>


<script async src="app.js"></script>

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

JavaScript Hello World 3


<title>JavaScript defer demonstration</title>
<script defer src="defer-script.js"></script>
</head>
<body>
</body>
</html>

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.

JavaScript Hello World 4


JavaScript Syntax
Whitespace
Whitespace refers to characters that provide space between other characters.
JavaScript has the following whitespace:

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:

let formatted = true; if (formatted) {console.log('The code is easy to read');}

It is equivalent to the following code that uses whitespace. Hence, this code is much
easy to read:

let formatted = true;

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:

let message = "Welcome to JavaScript";


console.log(message);

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:

/* This is a block comment


that can span multiple lines */

Expressions
An expression is a piece of code that evaluates to a value. For example:

2 + 1

The above expression returns three.

Keywords & Reserved words


JavaScript defines a list of reserved keywords that have specific uses. Therefore, you
cannot use the reserved keywords as identifiers or property names by rules.
The following table shows the JavaScript reserved words defined in ECMA-262:

break case catch

continue debugger default

else export extends

function if import

new return super

throw try null

void while with

class delete finally

in switch typeof

JavaScript Syntax 3
yield const do

for instanceof this

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:

enum implements let

protected private public

await interface package

implements public

Summary
Use whitespace including carriage return, space, newline, and tab to format the
code. The JavaScript engine ignores the whiespace.

Use a semicolon ( ; ) to terminate a simple statement.

Use the curly braces ( {} ) to form a block that groups one or more simple
statements.

A single-line comment starts with // followed by a text. A block comment begins


with /* and ends with / . The JavaScript engine also ignores the comments.

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

Variable names cannot use reserved words.

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:

let variableName = value;

For example, the following statement declares the message variable and initializes it with
the literal string "Hello" :

let message = "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:

let message = "Hello",


counter = 100;

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:

let message = 'Hello';


message = 100;

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 = "Hello";


message = 'Bye';

Undefined vs. undeclared variables


It’s important to distinguish between undefined and undeclared variables.
An undefined variable is a variable that has been declared but has not been initialized
with a 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;

Once defining a constant, you cannot change its value.


The following example attempts to change the value of the workday constant to 4 and
causes an error:

workday = 2;

Error:

Uncaught TypeError: Assignment to constant variable.

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.

Use the let keyword to declare a variable.

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.

Use the const keyword to define a read-only reference to a value.

JavaScript Variables 4
JavaScript Data Types
JavaScript has the primitive data types:

1. null

2. undefined

3. boolean

4. number

5. string

6. symbol – available from ES2015

7. bigint – available from ES2020

and a complex data-type object .

JavaScript Data Types 1


JavaScript Data Types

Primitive Complex

null object

undefined

boolean

number

bigint

string

symbol

JavaScript is a dynamically typed language. It means that a variable doesn’t associate


with a type. In other words, a variable can hold a value of different types. For example:

let counter = 120;// counter is a number


counter = false;// counter is now a boolean
counter = "foo";// counter is now a string

To get the current type of the value that the variable stores, you use
the typeof operator:

JavaScript Data Types 2


let counter = 120;
console.log(typeof(counter));// "number"

counter = false;
console.log(typeof(counter));// "boolean"

counter = "Hi";
console.log(typeof(counter));// "string"

Output:

"number"
"boolean"
"string"

The undefined type


The undefined type is a primitive type that has only one value undefined . By default,
when a variable is declared but not initialized, it is assigned the value of undefined .
Consider the following example:

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 null type


The null type is the second primitive data type that also has only one value null . For
example:

JavaScript Data Types 3


let obj = null;
console.log(typeof obj);
// object

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

The number type


JavaScript uses the number type to represent both integer and floating-point numbers.
The following statement declares a variable and initializes its value with an integer:

let num = 100;

To represent a floating-point number, you include a decimal point followed by at least


one number. For example:

let price= 12.5;


let discount = 0.05;

Note that JavaScript automatically converts a floating-point number into an integer


number if the number appears to be a whole number.
The reason is that Javascript always wants to use less memory since a floating-point
value uses twice as much memory as an integer value. For example:

let price = 200.00;


// interpreted as an integer 200

JavaScript Data Types 4


To get the range of the number type, you use Number.MIN_VALUE and Number.MAX_VALUE . For
example:

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

number. For example, the division of a string by a number returns NaN :.

console.log('a'/2);
// NaN;

The NaN has two special characteristics:

Any operation with NaN returns NaN .

The NaN does not equal any value, including itself.

Here are some examples:

console.log(NaN/2);
// NaN
console.log(NaN == NaN);
// false

The string type

JavaScript Data Types 5


In JavaScript, a string is a sequence of zero or more characters. A string literal begins
and ends with either a single quote( ' ) or a double quote ( " ).
A string that begins with a double quote must end with a double quote. Likewise, a
string that begins with a single quote must also end with a single quote:

let greeting = 'Hi';


let message = "Bye";

If you want to single quotes or double quotes in a literal string, you need to use the
backslash to escape it. For example:

let message = 'I\'m also a valid string';


// use \ to escape the single quote (')

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:

let str = 'JavaScript';


str = str + ' String';

In this example:

First, declare the str variable and initialize it to a string of 'JavaScript' .

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)

The output is:

JavaScript Data Types 6


'JavaScript'

But not:

'javaScript'

The boolean type


The boolean type has two literal values: true and false in lowercase. The following
example declares two variables that hold the boolean values.

let inProgress = true;


let completed = false;

console.log(typeof completed);
// boolean

JavaScript allows values of other types to be converted into boolean values


of true or false .
To convert a value of another data type into a boolean value, you use
the Boolean() function. The following table shows the conversion rules:

Type true false

string non-empty string empty string

number non-zero number and Infinity 0, NaN

object non-null object null

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

JavaScript Data Types 7


console.log(Boolean({foo: 100})); // true on non-empty object
console.log(Boolean(null));// false

The symbol type


JavaScript added a primitive type in ES6: the symbol . Different from other primitive
types, the symbol type does not have a literal form.
To create a symbol, you call the Symbol function as follows:

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.

The bigint type


The bigint type represents the whole numbers that are larger than 253 – 1. To form
a bigint literal number, you append the letter n at the end of the number:

let pageView = 9007199254740991n;


console.log(typeof(pageView));
// 'bigint'

The object type


In JavaScript, an object is a collection of properties, where each property is defined as a
key-value pair.
The following example defines an empty object using the object literal syntax:

let emptyObject = {};

JavaScript Data Types 8


The following example defines the person object with two
properties: firstName and lastName .

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

The dot notation ( . )

The array-like notation ( [] ).

The following example uses the dot notation ( . ) to access


the firstName and lastName properties of the contact object.

JavaScript Data Types 9


console.log(contact.firstName);
console.log(contact.lastName);

If you reference a property that does not exist, you’ll get an undefined value. For
example:

console.log(contact.age);
// undefined

The following example uses the array-like notation to access


the email and phone properties of the contact object.

console.log(contact['phone']);
// '(408)-555-9999'
console.log(contact['email']);
// 'john.doe@example.com'

JavaScript Data Types 10


JavaScript Numbers
Introduction to the JavaScript Number
JavaScript uses the number type to represent both integers and floating-point values.
Technically, the JavaScript number type uses the IEEE-754 format.

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:

let counter = 100;

Integers can be represented in the following formats:

Octal (base 8)

Hexadecimal (based 16)

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:

let num = 071;


console.log(num);

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:

let num = 080;


console.log(num);

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:

let num = 0o71;


console.log(num);

Output:

57

If you have an invalid number after 0o , JavaScript will issue a syntax error like this:

let num = 0o80;


console.log(num);

Output:

let num = 0o80;


^^
SyntaxError: Invalid or unexpected token

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:

let num = 0x1a;


console.log(num);

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:

let price = 9.99;


let tax = 0.08;
let discount = .05; // valid but not recommended

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:

let amount = 3.14e7;


console.log(amount);

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:

let amount = 5e-7;


console.log(amount);

JavaScript Numbers 3
Output:

0.0000005Code language: CSS (css)

The 5e-7 notation means that take 5 and divide it by 10,000,000.


Also, JavaScript automatically converts any floating-point number with at least six zeros
after the decimal point into e-notation. For example:

let amount = 0.0000005;


console.log(amount);

Output:

5e-7

Floating-point numbers are accurate up to 17 decimal places. When you perform


arithmetic operations on floating-point numbers, you often get the approximate result.
For example:

let amount = 0.2 + 0.1;


console.log(amount);

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:

const budget = 1000000000;

Is this a billion or a hundred million?

The numeric separator fixes this readability issue as follows:

const budget = 1_000_000_000;

As you can see, the number is now very easy to interpret.


JavaScript allows you to use numeric separators for both integer and floating-
point numbers. For example:

let amount = 120_201_123.05;


// 120201123.05
let expense = 123_450;
// 123450
let fee = 12345_00;
// 1234500

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:

let amount = 0.000_001; // 1 millionth

JavaScript Numeric Separator 1


It’s important to notice that you can use the numeric separator for bigint literal, binary
literal, octal literal, and hex literal. For example:

// BigIntconst max = 9_223_372_036_854_775_807n;

// binarylet nibbles = 0b1011_0101_0101;

// octallet val = 0o1234_5670;

// hexlet message = 0xD0_E0_F0;

Summary
Use underscores ( _ ) as the numeric separators to create a visual separation
between groups of digits.

JavaScript Numeric Separator 2


Quick Look at Octal and Binary
Literals in ES6
ES5 provided numeric literals in octal (prefix 0 ), decimal (no prefix), and hexadecimal
( 0x ). ES6 added support for binary literals and changed how it represents octal literals.

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:

let b = 058;// invalid octal


console.log(b);// 58

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);

Here is the error message:

SyntaxError: Decimals with leading zeros are not allowed in strict mode.

Quick Look at Octal and Binary Literals in ES6 1


ES6 allows you to specify the octal literal by using the prefix 0o followed by a sequence
of octal digits from 0 through 7. Here is an example:

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.

Binary literals start with 0b followed by a sequence of numbers 0 and 1.

Quick Look at Octal and Binary Literals in ES6 2


JavaScript Boolean type
Introduction to the JavaScript boolean type
The JavaScript boolean primitive type has two literal values: true and false .
The following example declares two variables and initializes their values
to true and false :

let completed = true;


let running = false;

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:

let error = 'An error occurred;


let hasError = Boolean(error);

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.

Third, output the value of the hasError variable to the console.

Because the error variable holds a non-empty string, the Boolean() function casts its
value to true .

JavaScript Boolean type 1


The following table shows how the Boolean() function casts the values of other types to
boolean values:

Data Type Values converted to true Value Converted to false

string Any non-empty string “” (empty string)

number Any Non-zero number 0 , NaN

object Any object null

undefined (not relevant) undefined

This table is important because some statements automatically cast a non-boolean


value to a boolean value using the Boolean() function.
For example, the if statement executes a block if a condition is true . If you use a non-
boolean value, it’ll use the Boolean() function to implicitly cast that value to a boolean
value.
Note that you’ll learn about the if statement in the if tutorial.
See the following example:

let error = 'An error occurred;

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 :

let error = '';


if (error) {

JavaScript Boolean type 2


console.log(error);
}

Summary
JavaScript boolean type has two literal values true and false .

Use the Boolean() function to cast a non-boolean value to a boolean value.

Some statements implicitly cast a non-boolean value into a boolean value.

JavaScript Boolean type 3


JavaScript string
Introduction to the JavaScript strings
JavaScript strings are primitive values. Also, strings are immutable. It means that if you
modify a string, you will always get a new string. The original string doesn’t change.

To create literal strings, you use either single quotes ( ' ) or double quotes ( " ) like this:

let str = 'Hi';


let greeting = "Hello";

ES6 introduced template literals that allow you to define a string backtick (`) characters:

let name = `John`';

The template literals allow you to use the single quotes and double quotes inside a
string without the need of escaping them. For example:

let message = `"I'm good". She said";

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:

let name = 'John';


let message = `Hi, I'm ${name}.`;

console.log(message);

Output:

Hi, I'm John.

JavaScript string 1
In this example, JavaScript replaces the name variable with its value inside the template
literal.

Escaping special characters


To escape special characters, you use the backslash \ character. For example:

Windows line break: '\r\n'

Unix line break: '\n'

Tab: '\t'

Backslash '\'

The following example uses the backslash character to escape the single quote
character in a string:

let str = 'I\'m a string!';

Getting the length of the string


The length property returns the length of a string:

let str = "Good Morning!";


console.log(str.length);// 13

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:

let str = "Hello";


console.log(str[0]);// "H"

JavaScript string 2
To access the last character of the string, you use the length - 1 index:

let str = "Hello";


console.log(str[str.length -1]);// "o"

Concatenating strings via the + operator


To concatenate two or more strings, you use the + operator:

let name = 'John';


let str = 'Hello ' + name;

console.log(str);// "Hello John"

If you want to assemble a string piece by piece, you can use the += operator:

let className = 'btn';


className += ' btn-primary'
className += ' none';

console.log(className);

Output:

btn btn-primary none

Converting values to string


To convert a non-string value to a string, you use one of the following:

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:

let result = 'a' < 'b';


console.log(result);
// true

However:

let result = 'a' < 'B';


console.log(result);
// false

Summary
JavaScript strings are primitive values and immutable.

JavaScript string 4
Literal strings are delimited by single quotes ( ' ), double quotes ( " ), or backticks
(`).

The length property returns the length of the string.

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:

let empty = {};

To create an object with properties, you use the key:value within the curly braces. For
example, the following creates a new person object:

let person = {
firstName: 'John',
lastName: 'Doe'
};

The person object has two properties firstName and lastName with the corresponding
values 'John' and 'Doe' .
When an object has multiple properties, you use a comma ( , ) to separate them like 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.

1) The dot notation (.)


The following illustrates how to use the dot notation to access a property of an object:

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'];

If you use the dot notation, you’ll get an error:

address.' building no';

Error:

SyntaxError: Unexpected string

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

Modifying the value of a property


To change the value of a property, you use the assignment operator ( = ). For example:

let person = {
firstName: 'John',

JavaScript Objects 3
lastName: 'Doe'
};

person.firstName = 'Jane';

console.log(person);

Output:

{ firstName: 'Jane', lastName: 'Doe' }

In this example, we changed the value of the firstName property of the person object
from 'John' to 'Jane' .

Adding a new property to an object


Unlike objects in other programming languages such as Java and C#, you can add a
property to an object after object creation.
The following statement adds the age property to the person object and assigns 25 to it:

person.age = 25;

Deleting a property of an object


To delete a property of an object, you use the delete operator:

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.

Checking if a property exists

JavaScript Objects 4
To check if a property exists in an object, you use the in operator:

propertyName in objectName

The in operator returns true if the propertyName exists in the objectName .


The following example creates an employee object and uses the in operator to check if
the ssn and employeeId properties exist in the object:

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.

Use the dot notation ( . ) or array-like notation ( [] ) to access a property of an


object.

The delete operator removes a property from an object.

The in operator check if a property exists in an object.

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.

Stack and heap memory


When you declare variables, the JavaScript engine allocates the memory for them on
two memory locations: stack and heap.
Static data is the data whose size is fixed at compile time. Static data includes:

Primitive values (null, undefined, boolean, number, string, symbol, and BigInt)

Reference values that refer to objects.

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:

let name = 'John';


let age = 25;

Because name and age are primitive values, the JavaScript engine stores these
variables on the stack as shown in the following picture:

JavaScript Primitive vs. Reference Values 1


Stack

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 name = 'John';


let age = 25;

let person = {
name: 'John',
age: 25,
};

Internally, the JavaScript engine allocates the memory as shown in the following picture:

JavaScript Primitive vs. Reference Values 2


Stack Heap

{ 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,
};

// add the ssn property


person.ssn = '123-45-6789';

//Change the name


person.name = 'John Doe';

// delete the age propertydelete person.age;

console.log(person);

Output:

JavaScript Primitive vs. Reference Values 3


{ name: 'John Doe', ssn: '123-45-6789' }

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:

let name = 'John';


name.alias = 'Knight';

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:

let age = 25;


let newAge = age;

In this example:

First, declare a new variable age and initialize its value with 25 .

Second, declare another variable newAge , and assign the age to


the newAge variable.

Behind the scene, the JavaScript engine creates a copy of the primitive value 25 and
assign it to the newAge variable.

JavaScript Primitive vs. Reference Values 4


The following picture illustrates the stack memory after the assignment:

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:

let age = 25;


let newAge = age;

newAge = newAge + 1;
console.log(age, newAge);

Stack

newAge=26

age=25

JavaScript Primitive vs. Reference Values 5


When you assign a reference value from one variable to another, the JavaScript engine
creates a reference so that both variables refer to the same object on the heap memory.
This means that if you change one variable, it’ll affect the other.
For example:

let person = {
name: 'John',
age: 25,
};

let member = person;

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:

JavaScript Primitive vs. Reference Values 6


Stack Heap

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

JavaScript Primitive vs. Reference Values 7


JavaScript Arrays
Introduction to JavaScript arrays
In JavaScript, an array is an ordered list of values. Each value is called
an element specified by an index:

Index 0 1 2 3 4

1 2 "Three" true null

Element

A JavaScript array has the following characteristics:

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.

Creating JavaScript arrays


JavaScript provides you with two ways to create an array. The first one is to use
the Array constructor as follows:

let scores = new Array();

The scores array is empty, which does hold any elements.


If you know the number of elements that the array will hold, you can create an array with
an initial size as shown in the following example:

let scores = Array(10);

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):

let scores = new Array(9,10,8,7,6);

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:

let athletes = new Array(3); // creates an array with initial size 3


let scores = new Array(1, 2, 3); // create an array with three numbers 1,2 3
let signs = new Array('Red'); // creates an array with one element 'Red'

JavaScript allows you to omit the new operator when you use the Array() constructor.
For example, the following statement creates the artists array.

let artists = Array()

In practice, you’ll rarely use the Array() constructor to create an array.


The more preferred way to create an array is to use the array literal notation:

let arrayName = [element1, element2, element3, ...];

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:

let colors = ['red', 'green', 'blue'];

JavaScript Arrays 2
To create an empty array, you use square brackets without specifying any element like
this:

let emptyArray = [];

Accessing JavaScript array elements


JavaScript arrays are zero-based indexes. In other words, the first element of an array
starts at index 0, the second element starts at index 1, and so on.
To access an element in an array, you specify an index in the square brackets [] :

arrayName[index]

The following shows how to access the elements of the mountains array:

let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];

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:

let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];


mountains[2] = 'K2';

console.log(mountains);

Output:

[ 'Everest', 'Fuji', 'K2' ]

Getting the array size

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 mountains = ['Everest', 'Fuji', 'Nanga Parbat'];


console.log(mountains.length);// 3

Basic operations on arrays


The following explains some basic operations on arrays. And you’ll learn advanced
operations such as map() , filter() , and reduce() in the next tutorials.

1) Adding an element to the end of an array


To add an element to the end of an array, you use the push() method:

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' ]

2) Adding an element to the beginning of an array


To add an element to the beginning of an array, you use the unshift() method:

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

4) Removing an element from the beginning of an array


To remove an element from the beginning of an array, you use the shift() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
const firstElement = seas.shift();

console.log(firstElement);

Output:

Black Sea

5) Finding an index of an element in the array


To find the index of an element, you use the indexOf() method:

let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea'];
let index = seas.indexOf('North Sea');

console.log(index);// 2

6) Check if a value is an array


To check if a value is an array, you use Array.isArray() method:

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.

An array can hold values of mixed types.

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 /

An arithmetic operator accepts numerical values as operands and returns a single


numerical value. The numerical values can be literals or variables.

Addition operator (+)


The addition operator returns the sum of two values. For example, the following uses
the addition operator to calculate the sum of two numbers:

let sum = 10 + 20;


console.log(sum);// 30

Also, you can use the addition operator with two variables. For example:

let netPrice = 9.99,


shippingFee = 1.99;
let grossPrice = netPrice + shippingFee;

console.log(grossPrice);

Output:

11.98

JavaScript Arithmetic Operators 1


If either value is a string, the addition operator uses the following rules:

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:

let result = 10 + '20';

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:

First Value Second Value Result Explanation

NaN NaN If either value is NaN, the result is NaN

JavaScript Arithmetic Operators 2


Infinity Infinity Infinity Infinity + Infinity = Infinity
-Infinity -Infinity -Infinity -Infinity + ( -Infinity) = – Infinity

Infinity -Infinity NaN Infinity + -Infinity = NaN

+0 +0 +0 +0 + (+0) = +0

-0 +0 +0 -0 + (+0) = +0

-0 -0 -0 -0 + (-0) = -0

Subtraction operator (-)


The subtraction operator ( - ) subtracts one number from another. For example:

let result = 30 - 10;


console.log(result);// 20

If a value is a string, a boolean, null, or undefined, the JavaScript engine will:

First, convert the value to a number using the Number() function.

Second, perform the subtraction.

The following table shows how to use the subtraction operator with special values:

First Value Second Value Result Explanation

NaN NaN If either value is NaN, the result is NaN

Infinity Infinity NaN Infinity – Infinity = NaN

-Infinity -Infinity -Infinity -Infinity – ( -Infinity) = NaN

Infinity -Infinity Infinity Infinity

+0 +0 +0 +0 – (+0) = 0

+0 -0 -0 +0 – (-0) = 0

-0 -0 +0 -0 – (-0) = 0

Multiplication operator (*)


JavaScript uses the asterisk (*) to represent the multiplication operator. The
multiplication operator multiplies two numbers and returns a single value. For example:

JavaScript Arithmetic Operators 3


let result = 2 * 3;
console.log(result);

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:

let result = '5' * 2;

console.log(result);

Output:

10

The following table shows how the multiply operator behaves with special values:

First Value Second Value Result Explanation

NaN NaN If either value is NaN, the result is NaN

Infinity 0 NaN Infinity * 0 = NaN

Infinity Positive number Infinity -Infinity * 100 = -Infinity

Negative
Infinity -Infinity Infinity * (-100) = -Infinity
number
Infinity Infinity Infinity Infinity * Infinity = Infinity

Divide operator (/)


Javascript uses the slash ( / ) character to represent the divide operator. The divide
operator divides the first value by the second one. For example:

JavaScript Arithmetic Operators 4


let result = 20 / 10;

console.log(result);// 2

If either value is not a number, the JavaScript engine converts it into a number for
division. For example:

let result = '20' / 2;


console.log(result);// 10;

The following table shows the divide operators’ behavior when applying to special
values:

First Value Second Value Result Explanation

NaN NaN If either value is NaN, the result is NaN

A number 0 Infinity 1/0 = Infinity

Infinity Infinity NaN Infinity / Infinity = NaN

0 0 NaN 0/0 = NaN

A positive
Infinity Infinity Infinity / 2 = Infinity
number
A negative
Infinity -Infinity Infinity / -2 = -Infinity
number

Using JavaScript arithmetic operators with objects


If a value is an object, the JavaScript engine will call the valueOf() method of the object
to get the value for calculation. For example:

let energy = {
valueOf() {
return 100;
},
};

let currentEnergy = energy - 10;


console.log(currentEnergy);

currentEnergy = energy + 100;

JavaScript Arithmetic Operators 5


console.log(currentEnergy);

currentEnergy = energy / 2;
console.log(currentEnergy);

currentEnergy = energy * 1.5;


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;
},
};

let currentEnergy = energy - 10;


console.log(currentEnergy);

currentEnergy = energy + 100;


console.log(currentEnergy);

currentEnergy = energy / 2;
console.log(currentEnergy);

currentEnergy = energy * 1.5;


console.log(currentEnergy);

Output:

40
150
25
75

JavaScript Arithmetic Operators 6


Summary
Use the JavaScript arithmetic operators including addition ( + ), subtraction ( ),
multiply ( ), and divide ( / ) to perform arithmetic operations.

JavaScript Arithmetic Operators 7


JavaScript Remainder Operator
Introduction to the JavaScript remainder operator
JavaScript uses the % to represent the remainder operator. The remainder operator
returns the remainder left over when one value is divided by another value.

Here’s the syntax of the remainder operator:

dividend % divisor

The following shows the equation for the remainder:

dividend = divisor * quotient + remainder


where |remainder| < |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 .

JavaScript remainder operator examples


Let’s take some examples of using the JavaScript remainder operator.

1) Using the remainder operator with a positive dividend example


The following example shows how to use the remainder operator with a positive
dividend:

let remainder = 5 % -2;


console.log(remainder); // 1

remainder = 5 % 2;
console.log(remainder); // 1

2) Using the remainder operator with a negative dividend example

JavaScript Remainder Operator 1


The following example uses the remainder operator with a negative dividend:

let remainder = -5 % 3;
console.log(remainder); // -2

remainder = -5 % -3;
console.log(remainder); // -2

3) Using the remainder operator special values


If a dividend is an Infinity and a divisor is a finite number, the remainder is NaN . For
example:

let remainder = Infinity % 2;


console.log(remainder); // NaN

If a dividend is a finite number and a divisor is zero, the remainder is NaN :

let remainder = 10 % 0;
console.log(remainder); // NaN

If both dividend and divisor are Infinity , the remainder is NaN :

let remainder = Infinity % Infinity;


console.log(remainder); // NaN

If a dividend is a finite number and the divisor is an Infinity , the remainder is the
dividend. For example:

let remainder = 10 % Infinity;


console.log(remainder); // 10

If the dividend is zero and the divisor is non-zero, the remainder is zero:

let remainder = 0 % 10;


console.log(remainder); // 0

JavaScript Remainder Operator 2


If either dividend or divisor is not a number, it’s converted to a number using
the Number() function and applied the above rules. For example:

let remainder = '10' % 3;


console.log(remainder);// 1

Using the remainder operator to check if a number is


an odd number
To check if a number is an odd number, you use the remainder operator ( % ) like the
following example:

let num = 13;


let isOdd = num % 2;

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 using an arrow function in ES6:

const isOdd = (num) => num % 2;

Remainder vs Modulo operator


In JavaScript, the remainder operator (%) is not the modulo operator.
If you have been working with Python, you may find the % represents the modulo
operator in this language. However, it is not the case in JavaScript.

JavaScript Remainder Operator 3


To get a modulo in JavaScript, you use the following expression:

((dividend % divisor) + divisor) % divisor

Or wrap it in a function:

const mod = (dividend, divisor) => ((dividend % divisor) + divisor) % divisor;

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:

const mod = (dividend, divisor) => ((dividend % divisor) + divisor) % divisor;

// dividen and divisor have the same sign


console.log('remainder:', 5 % 3);// 2
console.log('modulo:', mod(5, 3));// 2
// dividen and divisor have the different signs
console.log('remainder:', -5 % 3);// -2
console.log('modulo:', mod(-5, 3));// 1

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.

JavaScript Remainder Operator 4


JavaScript Assignment
Operators
Introduction to JavaScript assignment operators
An assignment operator ( = ) assigns a value to a variable. The syntax of the
assignment operator is as follows:

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.

JavaScript Assignment Operators 1


The following table illustrates assignment operators that are shorthand for another
operator and the assignment:

Operator Meaning Description


a = b a = b Assigns the value of b to a .
a += b a = a + b Assigns the result of a plus b to a .
a -= b a = a - b Assigns the result of a minus b to a .
a *= b a = a * b Assigns the result of a times b to a .
a /= b a = a / b Assigns the result of a divided by b to a .
a %= b a = a % b Assigns the result of a modulo b to a .
a &=b a = a & b Assigns the result of a AND b to a .
a |=b a = a | b Assigns the result of a OR b to a .
a ^=b a = a ^ b Assigns the result of a XOR b to a .
a <<= b a = a << b Assigns the result of a shifted left by b to a .

Assigns the result of a shifted right (sign preserved)


a >>= b a = a >> b
by b to a .
a >>>= b a = a >>> b Assigns the result of a shifted right by b to a .

Chaining JavaScript assignment operators


If you want to assign a single value to multiple variables, you can chain the assignment
operators. For example:

let a = 10, b = 20, c = 30;


a = b = c;// all variables are 30

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

let a = 10, b = 20, c = 30;

b = c;// b is 30
a = b;// a is also 30

Summary

JavaScript Assignment Operators 2


Use the assignment operator ( = ) to assign a value to a variable.

Chain the assignment operators if you want to assign a single value to multiple
variables.

JavaScript Assignment Operators 3


JavaScript Unary Operators
Explained
Introduction to the JavaScript unary operators
Unary operators work on one value. The following table shows the unary operators and
their meanings:

Unary
Name Meaning
Operators
+x Unary Plus Convert a value into a number

-x Unary Minus Convert a value into a number and negate it

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)

Unary plus (+)


The unary plus operator is a simple plus sign ( + ). If you place the unary plus before a
numeric value, it does nothing. For example

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

JavaScript Unary Operators Explained 1


boolean false to 0 , true to 1

string Convert the string value based on a set of specific rules

Call the valueOf() and/or toString() method to get the


object
value to convert into a number

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

JavaScript Unary Operators Explained 2


In this example, we apply the unary plus operator ( + ) on the person object that has
the toString() method, JavaScript engine calls toString() method to get the value
( '25' ) and convert it into a number. The following adds the valueOf() method to
the person object:

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.

Unary minus (-)


The unary minus operator is a single minus sign ( - ). If you apply the unary minus
operator to a number, it negates the number. For example:

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.

JavaScript Unary Operators Explained 3


Increment / Decrement operators
The increment operator has two plus signs ( ++ ) while the decrement operator has two
minus signs ( -- ).
Both increment and decrement operators have two versions: prefix and postfix. And you
place the prefix and postfix versions of the increment or decrement operators before
and after the variable to which they apply.
The following example uses the prefix increment operator to add one to a variable:

let age = 25;


++age;

console.log(age);// 26

It’s equivalent to the following:

let age = 25;


age = age + 1;
console.log(age);// 26

The following example uses the prefix decrement operator to subtract one from a
variable:

let weight = 90;


--weight;

console.log(weight);// 89

It is equivalent to the following:

let weight = 90;


weight = weight - 1;

console.log(weight);// 89

When you apply the prefix increment or decrement, JavaScript changes the variable
before evaluating the statement. For example:

JavaScript Unary Operators Explained 4


let weight = 90;
weight = ++weight + 5;

console.log(weight);// 96

In this example:

First, increase the weight on the right-hand side so ++weight is 91

Second, add five to the ++weight that returns 96

Third, assign the result to the weight on the left-hand side.

Likewise, the following example uses a prefix decrement operator:

let weight = 90;


weight = --weight + 5;

console.log(weight);// 94

In this example:

First, subtract one from the weight, –weight returns 89

Second, add five to the –weight that returns 94

Third, assign the result to the weight on the left-hand side.

The postfix increment or decrement operator changes the value after the statement is
evaluated. For example:

let weight = 90;


let newWeight = weight++ + 5;

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.

JavaScript Unary Operators Explained 5


Third, output both newWeight and weight to the console.

When applying the increment/decrement operator to a non-numeric value, it performs


the following steps :

First, convert the value into a number using the same rules as the unary plus (+)
operator.

Then, add one to or subtract one from the value.

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.

JavaScript Unary Operators Explained 6


JavaScript Comparison
Operators
Introduction to JavaScript comparison operators
To compare two values, you use a comparison operator. The following table shows the
comparison operators in JavaScript:

Operator Meaning

< less than

> greater than

<= less than or equal to

>= greater than or equal to

== equal to

!= not equal to

A comparison operator returns a Boolean value indicating whether the comparison is


true or not. See the following example:

let r1 = 20 > 10;// true


let r2 = 20 < 10;// false
let r3 = 10 == 10;// true

JavaScript Comparison Operators 1


A comparison operator takes two values. If the types of values are not comparable, the
comparison operator converts them into values of comparable types according to
specific rules.

Compare numbers
If values are numbers, the comparison operators perform a numeric comparison. For
example:

let a = 10,
b = 20;

console.log(a >= b);// false


console.log(a == 10);// true

This example is straightforward. The variable a is 10 , and b is 20 . The expression a

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

JavaScript Comparison Operators 2


let name1 = 'alice',
name2 = 'bob';

let result = name1 < name2;


console.log(result);// true
console.log(name1 == 'alice');// true

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

Second, compare the converted values

For example:

let f1 = 'apple',
f2 = 'Banana';

let result = f2.toLowerCase() < f1.toLowerCase();


console.log(result);// false

Note that the toLowerCase() is a method of the String object that converts the string to
lowercase.

Compare a number with a value of another type


If one value is a number and the other is not, the comparison operator will convert the
non-numeric value into a number and compare them numerically. For example:

console.log(10 < '20');// true

JavaScript Comparison Operators 3


In this example, the comparison operator converts the string '20' into the
number 20 and compares it with the number 10. Here is an example:

console.log(10 == '10');// true

In this example, the comparison operator converts the string '10' into the
number 10 and compares them numerically.

Compare an object with a non-object


If a value is an object, the valueOf() method of that object is called to return the value
for comparison. If the object doesn’t have the valueOf() method, the toString() method
is called instead. For example:

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.

Compare a Boolean with another value


If a value is a Boolean value, JavaScript converts it to a number and compares the
converted value with the other value; true is converted to 1 , and false is converted
to 0 . For example:

JavaScript Comparison Operators 4


console.log(true > 0);// true
console.log(false < 1);// true
console.log(true > false);// true
console.log(false > true);// false
console.log(true >= true);// true
console.log(true <= true);// true
console.log(false <= false);// true
console.log(false >= false);// true

In addition to the above rules, the equal ( == ) and not-equal( != ) operators also have
the following rules.

Compare null and undefined

In JavaScript, null equals undefined . It means that the following expression


returns true .

console.log(null == undefined);// true

Compare NaN with other values


If either value is NaN , then the equal operator( == ) returns false .

console.log(NaN == 1);// false

Even

console.log(NaN == NaN);// false

The not-equal ( != ) operator returns true when comparing the NaN with another value:

console.log(NaN != 1);// true

And also

console.log(NaN != NaN);// true

JavaScript Comparison Operators 5


Strict equal ( === ) and not strict equal ( !== )
Besides the comparison operators above, JavaScript provides the strict equal ( === )
and not strict equal ( !== ) operators.

Operator Meaning

=== strict equal

!== not strict equal

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:

console.log("10" == 10);// true


console.log("10" === 10);// false

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.

JavaScript Comparison Operators 6


JavaScript Logical Operators
The logical operators are important in JavaScript because they allow you to
compare variables and do something based on the result of that comparison.
For example, if the result of the comparison is true , you can run a block of code; if
it’s false , you can execute another code block.
JavaScript provides three logical operators:

! (Logical NOT)

|| (Logical OR)

&& (Logical AND)

1) The Logical NOT operator (!)


JavaScript uses an exclamation point ! to represent the logical NOT operator.
The ! operator can be applied to a single value of any type, not just a Boolean value.
When you apply the ! operator to a boolean value, the ! returns true if the value
is false and vice versa. For example:

let eligible = false,


required = true;

JavaScript Logical Operators 1


console.log(!eligible);
console.log(!required);

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

The logical ! operator works based on the following rules:

If a is undefined , the result is true .

If a is null , the result is true .

If a is a number other than 0 , the result is false .

If a is NaN , the result is true .

If a is an object, the result is false.

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

JavaScript Logical Operators 2


console.log(!'OK');//false
console.log(!false);//true
console.log(!true);//false

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:

let counter = 10;


console.log(!!counter);// true

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.

2) The Logical AND operator ( && )


JavaScript uses the double ampersand ( && ) to represent the logical AND operator. The
following expression uses the && operator:

let result = a && b;

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

true true true

true false false

false true false

false false false

JavaScript Logical Operators 3


The result of the && operator is true only if both values are true , otherwise, it is false .
For example:

let eligible = false,


required = true;

console.log(eligible && required);// false

In this example, the eligible is false , therefore, the value of the expression eligible &&

required is false .

See the following example:

let eligible = true,


required = true;

console.log(eligible && required);// true

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

JavaScript Logical Operators 4


The result is Infinity which is the result of the expression ( 1/0 ). However:

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.

The chain of && operators


The following expression uses multiple && operators:

let result = value1 && value2 && value3;

The && operator carries the following:

Evaluates values from left to right.

For each value, converts it to a boolean. If the result is false , stops and returns the
original value.

If all values are truthy values, returns the last 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.

3) The Logical OR operator ( || )


JavaScript uses the double pipe || to represent the logical OR operator. You can apply
the || operator to two values of any type:

JavaScript Logical Operators 5


let result = a || b;

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

true true true

true false true

false true true

false false false

The || operator returns false if both values evaluate to false . In case either value
is true , the || operator returns true . For example:

let eligible = true,


required = false;

console.log(eligible || required); // true

See another example:

let eligible = false,


required = false;

console.log(eligible || required);// false

In this example, the expression eligible || required returns false because both values
are false .

The || operator is also short-circuited


Similar to the && operator, the || operator is short-circuited. It means that if the first
value evaluates to true , the && operator doesn’t evaluate the second one.

JavaScript Logical Operators 6


The chain of || operators
The following example shows how to use multiple || operators in an expression:

let result = value1 || value2 || value3;

The || operator does the following:

Evaluates values from left to right.

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.

Logical operator precedence


When you mix logical operators in an expression, the JavaScript engine evaluates the
operators based on a specified order. And this order is called the operator precedence.
In other words, the operator precedence is the order of evaluation of logical operators in
an expression.
The precedence of the logical operator is in the following order from the highest to the
lowest:

1. Logical NOT (!)

2. Logical AND (&&)

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.

JavaScript Logical Operators 7


The OR operator ( || ) is applied to two Boolean values and returns true if one of
the operands is 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 || .

JavaScript Logical Operators 8


JavaScript Logical Assignment
Operators
ES2021 introduces three logical assignment operators including:

Logical OR assignment operator ( ||= )

Logical AND assignment operator ( &&= )

Nullish coalescing assignment operator ( ??= )

The following table shows the equivalent of the logical assignments operator:

Logical Assignment Operators Logical Operators

x ||= y x || (x = y)

x &&= y x && (x = y)

x ??= y x ?? (x = y);

The Logical OR assignment operator


The logical OR assignment operator ( ||= ) accepts two operands and assigns the right
operand to the left operand if the left operand is falsy:

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

JavaScript Logical Assignment Operators 1


In this example, the title variable is undefined , therefore, it’s falsy. Since the title is
falsy, the operator ||= assigns the 'untitled' to the title . The output shows
the untitled as expected.
See another example:

let title = 'JavaScript Awesome';


title ||= '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

is equivalent to the following statement that uses the logical OR operator:

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:

document.querySelector('.search-result').textContent ||= 'Sorry! No result found';

JavaScript Logical Assignment Operators 2


The Logical AND assignment operator
The logical AND assignment operator only assigns y to x if x is truthy:

x &&= y;

The logical AND assignment operator also short-circuits. It means that

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',
};

person.lastName &&= 'Smith';

console.log(person);

Output:

{firstName: 'Jane', lastName: 'Smith'}

The nullish coalescing assignment operator


The nullish coalescing assignment operator only
assigns y to x if x is null or undefined :

x ??= y;

JavaScript Logical Assignment Operators 3


It’s equivalent to the following statement that uses the nullish coalescing operator:

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:

{username: 'Satoshi', nickname:'anonymous'}

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.

The logical AND assignment ( x &&= y ) operator only assigns y to x if x is truthy.

The nullish coalescing assignment ( x ??= y ) operator only assigns y to x if x is


nullish.

JavaScript Logical Assignment Operators 4


JavaScript Nullish Coalescing
Operator
ES2020 introduced the nullish coalescing operator denoted by the double question
marks ( ?? ). The nullish coalescing operator is a logical operator that accepts two
values:

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:

const result = value1;


if(result === null || result === undefined) {
result = value2;
}

A nullish value is a value that is either null or undefined .


The following example uses the nullish coalescing operator ( ?? ) to return the
string 'John' because the first value is null :

const name = null ?? 'John';


console.log(name);// 'John'

And this example returns 28 because the first value is undefined :

const age = undefined ?? 28;


console.log(age);

Why nullish coalescing operator

JavaScript Nullish Coalescing Operator 1


When assigning a default value to a variable, you often use the logical OR
operator ( || ). For example:

let count;
let result = count || 1 ;
console.log(result);// 1

In this example, the count variable is undefined , it is coerced to false . Therefore,


the result is 1 .
However, the logical OR operator ( || ) sometimes is confusing if you consider 0 or
empty strings '' as a valid value like this:

let count = 0;
let result = count || 1;

The result is 1, not 0, which you may not expect.


The nullish coalescing operator helps you to avoid this pitfall. It only returns the second
value when the first one is either null or undefined .

The nullish coalescing operator is short-circuited


Similar to the logical OR and AND operators, the nullish coalescing operator does not
evaluate the second value if the first operand is neither undefined nor null .
For example:

let result = 1 ?? console.log('Hi');

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 :

let result = undefined ?? console.log('Hi');

JavaScript Nullish Coalescing Operator 2


Output:

'Hi'

Chaining with the AND or OR operator


A SyntaxError will occur if you combine the logical AND or OR operator directly with the
nullish coalescing operator like this:

const result = null || undefined ?? 'OK'; // SyntaxError

However, you can avoid this error by wrapping the expression on the left of
the ?? operator in parentheses to explicitly specify the operator precedences:

const result = (null || undefined) ?? 'OK';


console.log(result); // 'OK'

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.

JavaScript Nullish Coalescing Operator 3


JavaScript Exponentiation
Operator
To raise a number to the power of an exponent, you often use the static
method Math.pow() with the following syntax:

Math.pow(base, exponent)

For example:

let result = Math.pow(2,2);


console.log(result);// 4

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

The operator ** raises the x to the power of an exponent n .


Note that some languages use the caret symbol ^ for exponentiation. However,
JavaScript already uses that symbol for the bitwise logical XOR operator.
The following example illustrates how to use the exponentiation operator ( ** ):

let result = 2 ** 2;
console.log(result);// 4

result = 2 ** 3;
console.log(result);// 8

JavaScript Exponentiation Operator 1


The Math.pow() accepts a value and converts it to a value of the number type for
calculation. Similarly, the operator ** accepts values of the number type. In addition, the
operator ** accepts a value of the bigint type. For example:

let result = 2n ** 3n;


console.log(result);// 8n

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:

let result = -2**3;

Error:

Uncaught SyntaxError: Unary operator used immediately before exponentiation expression. Pa


renthesis must be used to disambiguate operator precedence

To fix this, you use parentheses like this:

let result = (-2)**3;


console.log(result);// -8

Summary
The exponentiation operator * raises a number to the power of an exponent.

The exponentiation operator * accepts values of the type number or bigint .

JavaScript Exponentiation Operator 2


JavaScript if
Introduction to the JavaScript if statement
The if statement executes the block if a condition is true . The following shows the
syntax of the if statement:

if( condition )
statement;

The condition can be a value or an expression. Typically, the condition evaluates to


a Boolean value, which is true or false .
If the condition evaluates to true , the if statement executes the statement .
Otherwise, the if statement passes the control to the next statement after it.
The following flowchart illustrates how the if statement works:

Start

false
Condition

true

If block

End

If the condition evaluates to a non-Boolean value, JavaScript implicitly converts its


result to a Boolean value by calling the Boolean() function.

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.

JavaScript if statement examples


The following example uses the if statement to check if the age is equal to or greater
than 18 :

let age = 18;


if (age >= 18) {
console.log('You can sign up');
}

Output:

You can sign up

How it works.
First, declare and initialize the variable age to 18 :

let age = 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:

if (age >= 18) {


console.log('You can sign up');
}

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:

let age = 16;


if (age >= 18) {
console.log('You can sign up');
}

Nested if statement
It’s possible to use an if statement inside another if statement. For example:

let age = 16;


let state = 'CA';

if (state == 'CA') {
if (age >= 16) {
console.log('You can drive.');
}
}

Output:

You can drive.

How it works.
First, declare and initialize the age and state variables:

let age = 16;


let state = 'CA';

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:

let age = 16;


let state = 'CA';

if (state == 'CA' && age == 16) {


console.log('You can drive.');
}

Summary
Use the JavaScript if statement to execute a statement if a condition is true .

Avoid using nested if statements as much as possible.

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

If block Else block

End

JavaScript if…else statement examples


The following example uses the if...else statement to check if the age is greater than
or equal to 18:

let age = 18;

if (age >= 18) {


console.log('You can sign up.');
} else {
console.log('You must be at least 18 to sign up.');
}

In this example, the age is 18 . Therefore, the expression age >= 18 is true . Hence,
you’ll see the following message in the console:

You can sign up.

The following example is the same as above except that the age is 18 instead of 16 :

JavaScript if else 2
let age = 16;

if (age >= 18) {


console.log('You can sign up.');
} else {
console.log('You must be at least 18 to sign up.');
}

Output:

You must be at least 18 to sign up.

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:

let age = 16;


let country = 'USA';

if (age >= 16 && country === 'USA') {


console.log('You can get a driving license.');
} else {
console.log('You are not eligible to get a driving license.');
}

Because the age is 16 and the country is the USA, the following expression
returns true .

age >= 16 && country === 'USA'Code language: JavaScript (javascript)

And you see the following output:

You can get a driving license.

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

JavaScript if else if examples


Let’s take some examples of using the if...else...if statement.

1) A simple JavaScript if…else…if statement example


The following example uses the if...else...if statement to get the month name from a
month number:

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.

2) Using JavaScript if…else…if statement to calculate the body


mass index

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 weight = 70; // kg


let height = 1.72; // meter

//Calculate the body mass index (BMI)

let bmi = weight / (height * height);

let weightStatus;

if (bmi < 18.5) {


weightStatus = 'Underweight';
} else if (bmi >= 18.5 && bmi <= 24.9) {
weightStatus = 'Healthy Weight';
} else if (bmi >= 25 && bmi <= 29.9) {
weightStatus = 'Overweight';
} else {
weightStatus = 'Obesity';
}

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.

Third, determine the weight status based on the BMI using


the if...else..if statement.

Finally, output the weight status to the console.

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:

let age = 18;


let message;

if (age >= 16) {


message = 'You can drive.';
} else {
message = 'You cannot drive.';
}

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:

let age = 18;


let message;

age >= 16 ? (message = 'You can drive.') : (message = 'You cannot drive.');

console.log(message);

Or you can use the ternary operator in an expression as follows:

let age = 18;


let message;

message = age >= 16 ? 'You can drive.' : 'You cannot drive.';

console.log(message);

Here’s the syntax of the ternary operator:

JavaScript Ternary Operator 1


condition ? expressionIfTrue : expressionIfFalse;

In this syntax, the condition is an expression that evaluates to a Boolean value,


either true or false .
If the condition is true , the first expression ( expresionIfTrue ) executes. If it is false, the
second expression ( expressionIfFalse ) executes.
The following shows the syntax of the ternary operator used in an expression:

let variableName = condition ? expressionIfTrue : expressionIfFalse;

In this syntax, if the condition is true , the variableNamewill take the result of the first
expression ( expressionIfTrue ) or expressionIfFalse otherwise.

JavaScript ternary operator examples


Let’s take some examples of using the ternary operator.

1) Using the JavaScript ternary operator to perform multiple


statements
The following example uses the ternary operator to perform multiple operations, where
each operation is separated by a comma. For example:

let authenticated = true;


let nextURL = authenticated
? (alert('You will redirect to admin area'), '/admin')
: (alert('Access denied'), '/403');

// redirect to nextURL hereconsole.log(nextURL); // '/admin'

In this example, the returned value of the ternary operator is the last value in the
comma-separated list.

2) Simplifying ternary operator example


See the following example:

JavaScript Ternary Operator 2


let locked = 1;
let canChange = locked != 1 ? true : false;

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;

3) Using multiple JavaScript ternary operators example


The following example shows how to use two ternary operators in the same expression:

let speed = 90;


let message = speed >= 120 ? 'Too Fast' : speed >= 80 ? 'Fast' : 'OK';

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.

JavaScript Ternary Operator 3


JavaScript Object Spread
Introduction to the JavaScript object spread Operator
In ES6, you use the spread operator ( ... ) to unpack elements of an array. The spread
operator can be very useful to clone an array. For example:

let colors = ['red', 'green', 'blue'];


let rgb = [...colors];
console.log(rgb);

Output:

[ 'red', 'green', 'blue' ]

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:

let rgb = [ 'red', 'green', 'blue' ];


let cmyk = ['cyan', 'magenta', 'yellow', 'black'];
let merge = [...rgb, ...cmyk];
console.log(merge);

Output:

[ 'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black' ]

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
};

JavaScript Object Spread 1


The following example uses the spread operator ( ... ) to create an coloredCircle object
that has all properties of the circle object and an additional property color :

const coloredCircle = {
...circle,
color: 'black'
};

console.log(coloredCircle);
Output:

{
radius: 10,
color: 'black'
}

JavaScript Object spread operator use cases


1) clone an object
You can use the spread operator to clone the own enumerable properties of an object:

const circle = {
radius: 10
};

const clonedCircle = {...circle};

console.log(clonedCircle);

Output:

{ radius: 10 }

Note that cloning is always shallow. For example:

const circle = {
radius: 10,

JavaScript Object Spread 2


style: {
color: 'blue'
}
};

const clonedCircle = {
...circle
};

clonedCircle.style = 'red';

console.log(clonedCircle);

Output:

{ radius: 10, style: 'red' }

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:

{ radius: 10, backgroundColor: 'red' }

Spread operator vs. Object.assign()

JavaScript Object Spread 3


The spread operator ( ... ) defines new properties in the target object while
the Object.assign() method assigns them. It has two side effects.

1) Target objects with setters


The Object.assign() invokes setters on the target object while the spread operator
doesn’t. The following illustrates how to clone an object using both Object.assign() and
spread operator ( ... ). However, only the Object.assign() method triggers the setters:

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 circle = new Circle(100);

let cloneCircle1 = Object.assign(circle, {


diameter: 200
});

let cloneCircle2 = {
...circle
};

Output:

SET 200

2) Target objects with read-only properties


If a target object has a read-only property, you cannot use Object.assign() method to
assign a new value to that property. However, the spread operator ( ... ) can define a
new property. Suppose you have an object called blueSquare whose the color property
is readonly:

JavaScript Object Spread 4


const blueSquare = {
length: 100,
color: 'blue'
};

Object.defineProperty(blueSquare, 'color', {
value: 'blue',
enumerable: true,
writable: false

});

console.log(blueSquare);

Output:

{ length: 100, color: 'blue' }

The following uses the spread operator ( ... ) to merge


the style and blueSquare objects:

// merge style and blueSquare objects:const style = {


color: 'green'
};

const greenSquare = {
...blueSquare,
...style
};

console.log(greenSquare);

Output:

{ length: 100, color: 'green' }

However, if you use the Object.assign() method, you will get an error:

// merge style and redSquare objects: ERRORconst redSquare = Object.assign(blueSquare, {


color: 'red'
});

JavaScript Object Spread 5


Error:

TypeError: Cannot assign to read only property 'color' of object '#<Object>'

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.

JavaScript Object Spread 6


JavaScript switch case
Introduction to the JavaScript switch case statement
The switch statement evaluates an expression , compares its result with case values,
and executes the statement associated with the matching case value.

The following illustrates the syntax of the switch statement:

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.

JavaScript switch case 1


The following flowchart illustrates the switch statement:

Start

Evaluate expressi...

true
value1 statement1

false

true
value2 statement2

false

true
value3 statement3

default statement

End

In practice, you often use a switch statement to replace a


complex if...else...if statement to make the code more readable.
Technically, the switch statement is equivalent to the following
if...else...if statement:

JavaScript switch case 2


if (expression === value1) {
statement1;
} else if (expression === value2) {
statement2;
} else if (expression === value3) {
statement3;
} else {
statement;
}

JavaScript switch case examples


Let’s take some examples of using the JavaScript switch statement.

1) Using JavaScript switch statement to get the day of the week


The following example uses the switch statement to get the day of the week based on a
day number:

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';
}

JavaScript switch case 3


console.log(dayName);// Tuesday

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.

2) Using the JavaScript switch statement to get the day count


based of a month
The following example uses the switch statement to get the day count of a month:

let year = 2016;


let month = 2;
let dayCount;

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) {

JavaScript switch case 4


dayCount = 29;
} else {
dayCount = 28;
}
break;
default:
dayCount = -1;// invalid month
}

console.log(dayCount);// 29

In this example, we have four cases:

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 4, 6, 9, or 11, the number of days in that month is 30.

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.

Use the switch statement to rather than a complex if...else...if statement to


make the code more readable.

The switch statement uses the strict comparison ( === ) to compare


the expression with the case values.

JavaScript switch case 5


JavaScript while Loop
Introduction to the JavaScript while loop statement
The JavaScript while statement creates a loop that executes a block as long as a
condition evaluates to true .

The following illustrates the syntax of the while statement:

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:

JavaScript while Loop 1


Start

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.

JavaScript while loop example


The following example uses the while statement to output the odd numbers between 1
and 10 to the console:

let count = 1;
while (count < 10) {
console.log(count);
count +=2;
}

Output:

1
3
5
7
9

JavaScript while Loop 2


How the script works

First, declare and initialize the count variable to 1 .

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 <

10 is false , the loop exits.

Summary
Use a while loop statement to create a loop that executes a block as long as
a condition evaluates to true .

JavaScript while Loop 3


JavaScript do…while Loop
Introduction to the JavaScript do…while statement
The do...while loop statement creates a loop that executes a block until a condition
evaluates to false . The following statement illustrates the syntax of the do...while loop:

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)

The following flowchart illustrates the do-while loop statement:

JavaScript do…while Loop 1


Start

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.

JavaScript do while statement examples


Let’s take some examples of using the do...while statement.

1) Simple JavaScript do while statement example


The following example uses the do...while statement to output five numbers from 0 to 4
to the console:

let count = 0;
do {
console.log(count);
count++;
} while (count < 5)

Output:

0
1
2

JavaScript do…while Loop 2


3
4

In this example:

First, declare and initialize the count variable to zero.

Second, show the count and increase its value by one in each iteration until its
value is greater or equal to 5.

2) Using the JavaScript do while statement to make a simple


number guessing game
The following example uses the do...while statement to generate a number guessing
game.
The script generates a random integer between 1 and 10. And you have to make a
number of guesses until your number matches the random number.

// generate a secret number between 1 and 10const MIN = 1;


const MAX = 10;

let secretNumber = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;

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);

// get the integer


number = parseInt(input);

//Increase the number of guesses


guesses++;

//Check the input number with the secret number and provide a hint if needed

if (number > secretNumber) {


hint = ', and less than ' + number;
} else if (number < secretNumber) {
hint = ', and greater than ' + number;
} else if (number == secretNumber) {
alert(`Bravo! you're correct after ${guesses} guess(es).`);
}
} while (number != secretNumber);

JavaScript do…while Loop 3


How it works.
First, declare the MIN and MAX constants and initialize their values to 1 and 10:

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:

Math.random() * (MAX - MIN + 1)

However, the result is a floating-point number. Therefore, you need to use


the Math.floor() function to convert it to an integer:

Math.floor(Math.random() * (MAX - MIN + 1))

To generate a random number between min and max, you use the following expression:

let secretNumber = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;

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);

JavaScript do…while Loop 4


Note that the input() function only works on web browsers. If you run the code in
another environment such as node.js, please check the corresponding function.
The input() function returns a string, therefore, you need to use the parseInt() function
to convert it to an integer:

number = parseInt(input);

Fifth, increase the number of guesses in each iteration:

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:

if (number > secretNumber) {


hint = ', and less than ' + number;
} else if (number < secretNumber) {
hint = ', and greater than ' + number;
} else if (number == secretNumber) {
alert(`Bravo! you're correct after ${guesses} guess(es).`);
}

Seventh, perform the next iteration until the number matches the secret number.

while (number != secretNumber);

Summary
Use the do…while statement to create a loop that executes a code block until a
condition is false .

JavaScript do…while Loop 5


JavaScript for Loop
Introduction to the JavaScript for loop statement
The for loop statement creates a loop with three optional expressions. The following
illustrates the syntax of the for loop statement:

for (initializer; condition; iterator) {


// statements
}

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:

JavaScript for Loop 1


Start

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
}

JavaScript for loop examples


Let’s take some examples of using the for loop statement.

1) A simple JavaScript for loop example


The following example uses the for loop statement to show numbers from 1 to 4 to the
console:

for (let i = 1; i < 5; i++) {


console.log(i);
}

JavaScript for Loop 2


Output:

1
2
3
4

How it works.

First, declare a variable counter and initialize it to 1.

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.

2) Using the JavaScript for loop without the initializer example


The following example uses a for loop that has no initializer expression:

let j = 1;
for (; j < 10; j += 2) {
console.log(j);
}

Output:

1
3
5
7
9

3) Using the JavaScript for loop without the condition example


Similar to the initializer expression, the condition expression is optional. If you omit
the condition expression, you need to use a break statement to terminate the loop.

for (let j = 1; ; j += 2) {
console.log(j);
if (j > 10) {
break;

JavaScript for Loop 3


}
}

Output:

1
3
5
7
9
11

3) Using the JavaScript for loop statement without any expression


example
All three expressions of the for loop statements are optional. Therefore, you can omit
all of them. For example:

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.

JavaScript for Loop 4


For example, the following uses a for loop to calculate the sum of 10 numbers from 1 to
10:

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.

JavaScript for Loop 5


JavaScript break
The label statement
In JavaScript, you can label a statement for later use. Here’s the syntax of
the label statement:

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:

outer: for (let i = 0; i < 5; i++) {


console.log(i);
}

Once defining a label, you can reference it in the break or continue statement.

Introduction to JavaScript break statement


The break statement prematurely terminates a loop such as for , do...while ,
and while loop, a switch , or a label statement. Here’s the syntax of
the break 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.

Using JavaScript break statement in a for loop


The following for loop statement outputs five numbers from 0 to 4 :

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:

for (let i = 0; i < 5; i++) {


console.log(i);
if (i == 2) {
break;
}
}

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

Using the break statement to terminate a nested loop


A nested loop has one loop inside another. For example, the following uses a
nested for loop to output a pair of numbers from 1 to 3 :

for (let i = 1; i <= 3; i++) {


for (let j = 1; j <= 3; j++) {
console.log(i, j);
}
}

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:

for (let i = 1; i <= 3; i++) {


for (let j = 1; j <= 3; j++) {
if (i + j == 4) {
break;
}
console.log(i, j);
}
}

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:

outer: for (let i = 1; i <= 3; i++) {


for (let j = 1; j <= 3; j++) {
if (i + j == 4) {
break outer;
}
console.log(i, j);
}
}

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 .

Using JavaScript break statement in a while loop


The following output five numbers from 1 to 5 to the console using a while loop:

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

Using JavaScript break statement in a do…while loop

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.

Using the continue statement in a for loop


When using the continue statement in a for loop, it doesn’t terminate the loop entirely.
Instead, it jumps to the iterator expression.

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:

for (let i = 0; i < 10; i++) {


if (i % 2 === 0) {
continue;
}
console.log(i);
}

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.

Using the continue statement in a while loop


When using the continue statement in a while loop, it doesn’t terminate the execution
of the loop entirely. Instead, it jumps back to the condition.
The following flowchart show hows the continue statement works in a while loop
statement:

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

Using the continue statement with a label example


The continue statement can include an optional label like this:

continue label;

The following nested loop displays pairs of numbers from 1 to 2:

for (let i = 1; i < 3; i++) {


for (let j = 1; j < 3; j++) {
console.log(i, j);
}
}

Output:

1 1
1 2
2 1
2 2

The following shows how to use the continue statement with a label:

outer: for (let i = 1; i < 4; i++) {


for (let j = 1; j < 4; j++) {
if (i + j == 3) continue outer;
console.log(i, j);
}
}

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:

let result = (10, 10 + 20);


console.log(result);

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

JavaScript Comma Operator 1


In this example, we increase the value of x by one ( x++ ), add one to x ( x+1 ) and
assign x to y . Therefore, x is 11 , and y is 12 after the statement.
However, to make the code more explicit, you can use two statements rather than one
statement with a comma operator like this:

let x = 10;
x++;
let y = x + 1;

console.log(x, y);

This code is more explicit.


In practice, you might want to use the comma operator inside a for loop to update
multiple variables each time through the loop.
The following example uses the comma operator in a for loop to display an array of nine
elements as a matrix of 3 rows and three columns:

let board = [1, 2, 3, 4, 5, 6, 7, 8, 9];

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.

JavaScript Comma Operator 2


Use the comma operator ( , ) inside a for loop to update multiple variables once.

Use two statements rather than the comma operator elsewhere to make the code
more explicit and easier to understand.

JavaScript Comma Operator 3


JavaScript Functions
Introduction to JavaScript functions
When developing an application, you often need to perform the same action in many
places. For example, you may want to show a message whenever an error occurs.

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.

Parameters vs. Arguments


The terms parameters and arguments are often used interchangeably. However, they
are essentially different.

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);
}

let result = say('Hello');


console.log('Result:', result);

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;
}

The following shows how to call the add() function:

let sum = add(10, 20);


console.log('Sum:', sum);

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;
}

The compare() function compares two values. It returns:

1 if the first argument is greater than the second one.

1 if the first argument is less than the second one.

0 if the first argument equals the second one.

The function immediately stops executing immediately when it reaches


the return statement. Therefore, you can use the return statement without a value to
exit the function prematurely, like this:

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.

The arguments object


Inside a function, you can access an object called arguments that represents the named
arguments of the function.
The arguments object behaves like an array though it is not an instance of
the Array type.
For example, you can use the square bracket [] to access the
arguments: arguments[0] returns the first argument, arguments[1] returns the second
one, and so on.
Also, you can use the length property of the arguments object to determine the number
of arguments.
The following example implements a generic add() function that calculates the sum of
any number of arguments.

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:

showMe(); // a hoisting example

JavaScript Functions 5
function showMe(){
console.log('an hoisting example');
}

This feature is called hoisting.


Function hoisting is a mechanism that the JavaScript engine physically moves function
declarations to the top of the code before executing them.
The following shows the version of the code before the JavaScript engine executes it:

function showMe(){
console.log('a hoisting example');
}

showMe();// a hoisting example

Summary
Use the function keyword to declare a function.

Use the functionName() to call a function.

All functions implicitly return undefined if they don’t explicitly return a value.

Use the return statement to return a value from a function explicitly.

The arguments variable is an array-like object inside a function, representing function


arguments.

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;
}

let sum = add;

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:

let result = add(10, 20);

Alternatively, we can all the add() function via the sum variable like this:

let result = sum(10,20);

Passing a function to another function


Because functions are values, you can pass a function as an argument into another
function.

JavaScript Functions are First-Class Citizens 1


The following declares the average() function that takes three arguments. The third
argument is a function:

function average(a, b, fn) {


return fn(a, b) / 2;
}

Now, you can pass the sum function to the average() function as follows:

let result = average(10, 20, sum);

Put it all together:

function add(a, b) {
return a + b;
}

let sum = add;

function average(a, b, fn) {


return fn(a, b) / 2;
}

let result = average(10, 20, sum);

console.log(result);

Output:

15

Returning functions from functions


Since functions are values, you can return a function from another function.
The following compareBy() function returns a function that compares two objects by a
property:

JavaScript Functions are First-Class Citizens 2


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;
}
};
}

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.log('Products sorted by name:');


products.sort(compareBy('name'));

console.table(products);

Output:

JavaScript Functions are First-Class Citizens 3


Products sorted by name:
┌─────────┬──────────────────┬───────┐
│ (index) │ name │ price │
├─────────┼──────────────────┼───────┤
│ 0 │ 'Samsung Galaxy' │ 850 │
│ 1 │ 'Sony Xperia' │ 700 │
│ 2 │ 'iPhone' │ 900 │
└─────────┴──────────────────┴───────┘

Similarly, you can sort the product objects by prices:

// sort products by prices


console.log('Products sorted by price:');
products.sort(compareBy('price'));
console.table(products);

Output:

Products sorted by price:


┌─────────┬──────────────────┬───────┐
│ (index) │ name │ price │
├─────────┼──────────────────┼───────┤
│ 0 │ 'Sony Xperia' │ 700 │
│ 1 │ 'Samsung Galaxy' │ 850 │
│ 2 │ 'iPhone' │ 900 │
└─────────┴──────────────────┴───────┘

Put it all together.

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 = [

JavaScript Functions are First-Class Citizens 4


{ name: 'iPhone', price: 900 },
{ name: 'Samsung Galaxy', price: 850 },
{ name: 'Sony Xperia', price: 700 },
];

// sort products by name


console.log('Products sorted by name:');
products.sort(compareBy('name'));

console.table(products);

// sort products by price


console.log('Products sorted by price:');
products.sort(compareBy('price'));
console.table(products);

More JavaScript Functions are First-Class Citizens


example
The following example defines two functions that convert a length in centimeters to
inches and vice versa:

function cmToIn(length) {
return length / 2.54;
}

function inToCm(length) {
return length * 2.54;
}

JavaScript Functions are First-Class Citizens 5


The following convert() function has two parameters. The first parameter is a function
and the second one is the length that will be converted based on the first argument:

function convert(fn, length) {


return fn(length);
}

To convert cm to in , you can call the convert() function and pass the cmToIn function
into the convert() function as the first argument:

let inches = convert(cmToIn, 10);


console.log(inches);

Output:

3.937007874015748

Similarly, to convert a length from inches to centimeters, you can pass


the inToCm function into the convert() function, like this:

let cm = convert(inToCm, 10);


console.log(cm);

Output:

25.4

Put it all together.

function cmToIn(length) {
return length / 2.54;
}

function inToCm(length) {
return length * 2.54;
}

JavaScript Functions are First-Class Citizens 6


function convert(fn, length) {
return fn(length);
}

let inches = convert(cmToIn, 10);


console.log(inches);

let cm = convert(inToCm, 10);


console.log(cm);

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.

JavaScript Functions are First-Class Citizens 7


JavaScript Anonymous
Functions
Introduction to JavaScript anonymous functions
An anonymous function is a function without a name. The following shows how to define
an anonymous function:

(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:

let show = function() {


console.log('Anonymous function');
};

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

JavaScript Anonymous Functions 1


Using anonymous functions as arguments
In practice, you often pass anonymous functions as arguments to other functions. For
example:

setTimeout(function() {
console.log('Execute later after 1 second')
}, 1000);

In this example, we pass an anonymous function into the setTimeout() function.


The setTimeout() function executes this anonymous function one second later.
Note that functions are first-class citizens in JavaScript. Therefore, you can pass a
function to another function as an argument.

Immediately invoked function execution


If you want to create a function and execute it immediately after the declaration, you can
declare an anonymous function like this:

(function() {
console.log('IIFE');
})();

How it works.
First, define a function expression:

(function () {
console.log('Immediately invoked function execution');
})

This expression returns a function.


Second, call the function by adding the trailing parentheses () :

(function () {
console.log('Immediately invoked function execution');
})();

JavaScript Anonymous Functions 2


and sometimes, you may want to pass arguments into it, like this:

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:

let show = function () {


console.log('Anonymous function');
};

… can be shortened using the following arrow function:

let show = () => console.log('Anonymous function');

Similarly, the following anonymous function:

let add = function (a, b) {


return a + b;
};

… is functionally equivalent to the following arrow function:

let add = (a, b) => a + b;

Summary

JavaScript Anonymous Functions 3


Anonymous functions are functions without names.

Anonymous functions can be used as an argument to other functions or as an


immediately invoked function execution.

JavaScript Anonymous Functions 4


Understanding JavaScript Pass-
By-Value
Before going forward with this tutorial, you should have good knowledge of the primitive
and reference values, and the differences between them.

JavaScript pass-by-value or pass-by-reference


In JavaScript, all function arguments are always passed by value. It means
that JavaScript copies the values of the variables into the function arguments.
Any changes that you make to the arguments inside the function do not reflect the
passing variables outside of the function. In other words, the changes made to the
arguments are not reflected outside of the function.
If function arguments are passed by reference, the changes of variables that you pass
into the function will be reflected outside the function. This is not possible in JavaScript.

Pass-by-value of primitives values


Let’s take a look at the following example.

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

How the script works.


First, define a square() function that accepts an argument x . The function assigns the
square of x to the x argument.
Next, declare the variable y and initialize its value to 10 :

Understanding JavaScript Pass-By-Value 1


Stack

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.

Understanding JavaScript Pass-By-Value 2


Stack

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.

Understanding JavaScript Pass-By-Value 3


Stack

x = 100

y = 10

Finally, the value of the y variable does not change after the square() function
completes.

Stack

result = 100

y = 10

Understanding JavaScript Pass-By-Value 4


If JavaScript used the pass-by-reference, the variable y would change to 100 after
calling the function.

Pass-by-value of reference values


It’s not obvious to see that reference values are also passed by values. For example:

let person = {
name: 'John',
age: 25,
};

function increaseAge(obj) {
obj.age += 1;
}

increaseAge(person);

console.log(person);

How the script works:


First, define the person variable that references an object with two
properties name and age :

Understanding JavaScript Pass-By-Value 5


Stack Heap

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

Understanding JavaScript Pass-By-Value 6


After that, increase the age property by one inside the increaseAge() function via
the obj variable

Stack Heap

{ name: "John",
obj
age: 26 }

person

Finally, accessing the object via the person reference:

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:

Understanding JavaScript Pass-By-Value 7


let person = {
name: 'John',
age: 25,
};

function increaseAge(obj) {
obj.age += 1;

// reference another object


obj = { name: 'Jane', age: 22 };
}

increaseAge(person);

console.log(person);

Output:

{ name: 'John', age: 26 }

In this example, the increaseAage() function changes the age property via
the obj argument:

Stack Heap

{ name: "John",
obj
age: 26 }

person

and makes the obj reference another object:

Understanding JavaScript Pass-By-Value 8


Stack Heap

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

Function arguments are local variables in JavaScript.

Understanding JavaScript Pass-By-Value 9


JavaScript Recursive Function
Introduction to the JavaScript recursive functions
A recursive function is a function that calls itself until it doesn’t. And this technique is
called recursion.

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.

JavaScript recursive function examples


Let’s take some examples of using recursive functions.

1) A simple JavaScript recursive function example


Suppose that you need to develop a function that counts down from a specified number
to 1. For example, to count down from 3 to 1:

JavaScript Recursive Function 1


3
2
1

The following shows the countDown() function:

function countDown(fromNumber) {
console.log(fromNumber);
}

countDown(3);

This countDown(3) shows only the number 3.


To count down from the number 3 to 1, you can:

1. show the number 3.

2. and call the countDown(2) that shows the number 2.

3. and call the countDown(1) that shows the number 1.

The following changes the countDown() to a recursive function:

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:

Uncaught RangeError: Maximum call stack size exceeded.

… because it doesn’t have the condition to stop calling itself.


The count down will stop when the next number is zero. Therefore, you add an if
condition as follows:

JavaScript Recursive Function 2


function countDown(fromNumber) {
console.log(fromNumber);

let nextNumber = fromNumber - 1;

if (nextNumber > 0) {
countDown(nextNumber);
}
}
countDown(3);

Output:

3
2
1

The countDown() seems to work as expected.


However, as mentioned in the Function type tutorial, the function’s name is a reference
to the actual function object.
If the function name is set to null somewhere in the code, the recursive function will
stop working.
For example, the following code will result in an error:

let newYearCountDown = countDown;


// somewhere in the code
countDown = null;
// the following function call will cause an error
newYearCountDown(10);

Error:

Uncaught TypeError: countDown is not a function

How the script works:

First, assign the countDown function name to the variable newYearCountDown .

JavaScript Recursive Function 3


Second, set the countDown function reference to null .

Third, call the newYearCountDown function.

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.

To fix it, you can use a named function expression as follows:

let countDown = function f(fromNumber) {


console.log(fromNumber);

let nextNumber = fromNumber - 1;

if (nextNumber > 0) {
f(nextNumber);
}
}

let newYearCountDown = countDown;


countDown = null;
newYearCountDown(10);

2) Calculate the sum of n natural numbers example


Suppose you need to calculate the sum of natural numbers from 1 to n using the
recursion technique. To do that, you need to define the sum() recursively as follows:

sum(n) = n + sum(n-1)
sum(n-1) = n - 1 + sum(n-2)
...
sum(1) = 1

The following illustrates the sum() recursive function:

function sum(n) {
if (n <= 1) {
return n;
}
return n + sum(n - 1);
}

JavaScript Recursive Function 4


Summary
A recursive function is a function that calls itself until it doesn’t

A recursive function always has a condition that stops the function from calling itself.

JavaScript Recursive Function 5


JavaScript Default Parameters
you will learn how to handle JavaScript default parameters in ES6.

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.

Arguments vs. Parameters


Sometimes, you can use the terms argument and parameter interchangeably. However,
by definition, parameters are what you specify in the function declaration whereas the
arguments are what you pass into the function.
Consider the following add() 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.

Setting JavaScript default parameters for a function

JavaScript Default Parameters 1


In JavaScript, a parameter has a default value of undefined. It means that if you don’t
pass the arguments into the function, its parameters will have the default values
of undefined .
See the following example:

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:

function fn(param1=default1, param2=default2,..) {


}

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:

JavaScript Default Parameters 2


function say(message='Hi') {
console.log(message);
}

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.

More JavaScript default parameter examples


Let’s look at some more examples to learn some available options for setting default
values of the function parameters.

1) Passing undefined arguments


The following createDiv() function creates a new <div> element in the document with a
specific height, width, and border-style:

function createDiv(height = '100px', width = '100px', border = 'solid 1px red') {


let div = document.createElement('div');
div.style.height = height;
div.style.width = width;
div.style.border = border;
document.body.appendChild(div);
return div;
}

The following doesn’t pass any arguments to the function so the createDiv() function
uses the default values for the parameters.

JavaScript Default Parameters 3


createDiv();

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:

createDiv(undefined,undefined,'solid 5px blue');

2) Evaluating default parameters


JavaScript engine evaluates the default arguments at the time you call the function. See
the following example:

function put(toy, toyBox = []) {


toyBox.push(toy);
return toyBox;
}

console.log(put('Toy Car'));
// -> ['Toy Car']
console.log(put('Teddy Bear'));
// -> ['Teddy Bear'], not ['Toy Car','Teddy Bear']

The parameter can take a default value which is a result of a function.


Consider the following example:

function date(d = today()) {


console.log(d);
}
function today() {
return (new Date()).toLocaleDateString("en-US");
}
date();

JavaScript Default Parameters 4


The date() function takes one parameter whose default value is the returned value of
the today() function. The today() function returns today’s date in a specified string
format.
When we declared the date() function, the today() function has not yet evaluated until
we called the date() function.
We can use this feature to make arguments mandatory. If the caller doesn’t pass any
argument, we throw an error as follows:

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

3) Using other parameters in default values


You can assign a parameter a default value that references other default parameters as
shown in the following example:

function add(x = 1, y = x, z = x + y) {
return x + y + z;
}

console.log(add()); // 4

In the add() function:

The default value of the y is set to x parameter.

The default value of the z is the sum of x and y

The add() function returns the sum of x , y , and z .

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:

JavaScript Default Parameters 5


function subtract( x = y, y = 1 ) {
return x - y;
}
subtract(10);

Error message:

Uncaught ReferenceError: Cannot access 'y' before initialization

Using functions
You can use a return value of a function as a default value for a parameter. For
example:

let taxRate = () => 0.1;


let getPrice = function( price, tax = price * taxRate() ) {
return price + tax;
}

let fullPrice = getPrice(100);


console.log(fullPrice); // 110

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.

The arguments object


The value of the arguments object inside the function is the number of actual arguments
that you pass to the function. For example:

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

JavaScript Default Parameters 6


Now, you should understand the JavaScript default function parameters and how to use
them effectively.

JavaScript Default Parameters 7


JavaScript Object Methods
Introduction to the JavaScript object methods
An object is a collection of key/value pairs or properties. When the value is a function,
the property becomes a method. Typically, you use methods to describe the object
behaviors.
For example, the following adds the greet method to the person object:

let person = {
firstName: 'John',
lastName: 'Doe'
};

person.greet = function () {
console.log('Hello!');
}

person.greet();

Output:

Hello!

In this example:

First, use a function expression to define a function and assign it to


the greet property of the person object.

Then, call the method greet() method.

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

JavaScript Object Methods 1


console.log('Hello, World!');
}

person.greet = greet;

person.greet();

In this example:

First, define the greet() function as a regular function.

Second, assign the function name to the the greet property of the person object.

Third, call the greet() method.

Object method shorthand


JavaScript allows you to define methods of an object using the object literal syntax as
shown in the following example:

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 syntax looks much cleaner and less verbose.

JavaScript Object Methods 2


The this value
Typically, methods need to access other properties of the object.
For example, you may want to define a method that returns the full name of the person
object by concatenating the first name and last name.
Inside a method, the this value references the object that invokes the method.
Therefore, you can access a property using the this value as follows:

this.propertyName

The following example uses this value in the getFullName() method:

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

When a function is a property of an object, it becomes a method.

JavaScript Object Methods 3


JavaScript Constructor Function
Introduction to JavaScript constructor functions
In the JavaScript objects tutorial, you learned how to use the object literal syntax to
create a new object.

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.

A constructor function should be called only with the new operator.

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.

The following example defines a constructor function called Person :

function Person(firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

JavaScript Constructor Function 1


In this example, the Person is the same as a regular function except that its name starts
with the capital letter P .
To create a new instance of the Person , you use the new operator:

let person = new Person('John','Doe');

Basically, the new operator does the following:

Create a new empty object and assign it to the this variable.

Assign the arguments 'John' and 'Doe' to the firstName and lastName properties of
the object.

Return the this value.

It’s functionally equivalent to the following:

function Person(firstName, lastName) {


// this = {};// add properties to thisthis.firstName = firstName;
this.lastName = lastName;

// return this;
}

Therefore, the following statement:

let person = new Person('John','Doe');

… returns the same result as the following statement:

let person = {
firstName: 'John',
lastName: 'Doe'
};

However, the constructor function Person allows you to create multiple similar objects.
For example:

JavaScript Constructor Function 2


let person1 = new Person('Jane','Doe')
let person2 = new Person('James','Smith')

Adding methods to JavaScript constructor functions


An object may have methods that manipulate its data. To add a method to an object
created via the constructor function, you can use the this keyword. For example:

function Person(firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;

this.getFullName = function () {
return this.firstName + " " + this.lastName;
};
}

Now, you can create a new Person object and invoke the getFullName() method:

let person = new Person("John", "Doe");


console.log(person.getFullName());

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.

Returning from constructor functions


Typically, a constructor function implicitly returns this that set to the newly created
object. But if it has a return statement, then here’s are the rules:

JavaScript Constructor Function 3


If return is called with an object, the constructor function returns that object instead
of this .

If return is called with a value other than an object, it is ignored.

Calling a constructor function without the new keyword


Technically, you can call a constructor function like a regular function without using
the new keyword like this:

let person = Person('John','Doe');

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:

TypeError: Cannot read property 'firstName' of undefined

Similarly, you cannot access the getFullName() method since it’s bound to the global
object.

person.getFullName();

Error:

TypeError: Cannot read property 'getFullName' of undefined

To prevent a constructor function to be invoked without the new keyword, ES6


introduced the new.target property.

JavaScript Constructor Function 4


If a constructor function is called with the new keyword, the new.target returns a
reference of the function. Otherwise, it returns undefined .
The following adds a statement inside the Person function to show the new.target to the
console:

function Person(firstName, lastName) {


console.log(new.target);

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:

let person = Person("John", "Doe");

Output:

undefined

However, the following returns a reference to the Person function because it’s called
with the new keyword:

let person = new Person("John", "Doe");

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:

JavaScript Constructor Function 5


function Person(firstName, lastName) {
if (!new.target) {
throw Error("Cannot be called without the new keyword");
}

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:

function Person(firstName, lastName) {


if (!new.target) {
return new Person(firstName, lastName);
}

this.firstName = firstName;
this.lastName = lastName;
}

let person = Person("John", "Doe");

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.

JavaScript Constructor Function 6


JavaScript this Keyword
If you have been working with other programming languages such as Java, C#, or PHP,
you’re already familiar with the this keyword.
In these languages, the this keyword represents the current instance of the class. And
it is only relevant within the class.
JavaScript also has this keyword. However, the this keyword in JavaScript behaves
differently from other programming languages.
In JavaScript, you can use the this keyword in the global and function contexts.
Moreover, the behavior of the this keyword changes between strict and non-strict
modes.

What is this keyword


In general, the this references the object of which the function is a property. In other
words, the this references the object that is currently calling the function.
Suppose you have an object called counter that has a method next() . When you call
the next() method, you can access the this object.

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.

JavaScript this Keyword 1


Global context
In the global context, the this references the global object, which is the window object
on the web browser or global object on Node.js.
This behavior is consistent in both strict and non-strict modes. Here’s the output on the
web browser:

console.log(this === window);// true

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.

1) Simple function invocation


In the non-strict mode, the this references the global object when the function is called
as follows:

function show() {
console.log(this === window);// true
}

show();

JavaScript this Keyword 2


When you call the show() function, the this references the global object, which is
the window on the web browser and global on Node.js.
Calling the show() function is the same as:

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

JavaScript this Keyword 3


In the display() inner function, the this also set to undefined as shown in the console.

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.

let brand = car.getBrand;

And then call the method via the 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 brand = car.getBrand.bind(car);


console.log(brand());// Honda

JavaScript this Keyword 4


In this example, when you call the brand() method, the this keyword is bound to
the car object. For example:

let car = {
brand: 'Honda',
getBrand: function () {
return this.brand;
}
}

let bike = {
brand: 'Harley Davidson'
}

let brand = car.getBrand.bind(bike);


console.log(brand());

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;
}

let car = new Car('Honda');


console.log(car.getBrand());

The expression new Car('Honda') is a constructor invocation of the Car function.

JavaScript this Keyword 5


JavaScript creates a new object and sets this to the newly created object. This pattern
works great with only one potential problem.
Now, you can invoke the Car() as a function or as a constructor. If you omit
the new keyword as follows:

var bmw = Car('BMW');


console.log(bmw.brand);
// => TypeError: Cannot read property 'brand' of undefined

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.

JavaScript this Keyword 6


The Function type has two methods: call() and apply() . These methods allow you to
set the this value when calling a function. For example:

function getBrand(prefix) {
console.log(prefix + this.brand);
}

let honda = {
brand: 'Honda'
};
let audi = {
brand: 'Audi'
};

getBrand.call(honda, "It's a ");


getBrand.call(audi, "It's an ");

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.

getBrand.apply(honda, ["It's a "]); // "It's a Honda"


getBrand.apply(audi, ["It's an "]); // "It's a Audi"

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:

JavaScript this Keyword 7


let getThis = () => this;
console.log(getThis() === window); // true

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;
};

var car = new Car();


console.log(car.getSpeed()); // undefined

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 .

JavaScript this Keyword 8


JavaScript globalThis
Introduction to the JavaScript globalThis object
ES2020 introduced the globalThis object that provides a standard way to access the
global object across environments.

Historically, JavaScript had a global object with different names in different


environments.
In web browsers, the global object is window or frames .
However, the Web Workers API doesn’t have the window object because it has no
browsing context. Hence, the Web Workers API uses self as a global object.
Node.js, on the other hand, uses the global keyword to reference the global object.

Environment Global

Web Browsers this

Web Workers self

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:

const canFetch = typeof globalThis.fetch === 'function';

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

Objects have two types of properties: data and accessor properties.

1) Data properties
A data property contains a single location for a data value. A data property has four
attributes:

[[Configurarable]] – determines whether a property can be redefined or removed


via delete operator.

[[Enumerable]] – indicates if a property can be returned in the for...in loop.

[[Writable]] – specifies that the value of a property can be changed.

[[Value]] – contains the actual value of a property.

By default, the [[Configurable]] , [[Enumerable]] And [[Writable]] attributes set


to true for all properties defined directly on an object. The default value of
the [[Value]] attribute is undefined .
The following example creates a person object with two
properties firstName and lastName with the configurable, enumerable, and writable
attributes set to true . And their values are set to 'John' and 'Doe' respectively:

let person = {
firstName: 'John',
lastName: 'Doe'
};

To change any attribute of a property, you use the Object.defineProperty() method.


The Object.defineProperty() method accepts three arguments:

An object.

JavaScript Object Properties 1


A property name of the object.

A property descriptor object that has four


properties: configurable , enumerable , writable , and value .

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:

let person = {};


person.age = 25;

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';

let person = {};

Object.defineProperty(person, 'ssn', {
configurable: false,
value: '012-38-9119'
});

delete person.ssn;

Output:

JavaScript Object Properties 2


TypeError: Cannot delete property 'ssn' of#<Object>

In this example, the configurable attribute is set to false . herefore, deleting


the ssn property causes an error.
Also, once you define a property as non-configurable, you cannot change it to
configurable.
If you use the Object.defineProperty() method to change any attribute other than the
writable, you’ll get an error. or example:

'use strict';

let person = {};

Object.defineProperty(person, 'ssn', {
configurable: false,
value: '012-38-9119'
});

Object.defineProperty(person, 'ssn', {
configurable: true
});

Output:

TypeError: Cannot redefine property: ssn

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:

let person = {};


person.age = 25;
person.ssn = '012-38-9119';

for (let property in person) {


console.log(property);
}

JavaScript Object Properties 3


Output:

age
ssn

The following makes the ssn property non-enumerable by setting


the enumerable attribute to false .

let person = {};


person.age = 25;
person.ssn = '012-38-9119';

Object.defineProperty(person, 'ssn', {
enumerable: false
});

for (let prop in person) {


console.log(prop);
}

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:

JavaScript Object Properties 4


let person = {
firstName: 'John',
lastName: 'Doe'
}

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.

In the fullname accessor property:

The [[Get]] returns the full name that is the result


of concatenating of firstName , space , and lastName .

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.

Define multiple properties: Object.defineProperties()

JavaScript Object Properties 5


In ES5, you can define multiple properties in a single statement using
the Object.defineProperties() method. or example:

var product = {};

Object.defineProperties(product, {
name: {
value: 'Smartphone'
},
price: {
value: 799
},
tax: {
value: 0.1
},
netPrice: {
get: function () {
return this.price * (1 + this.tax);
}
}
});

console.log('The net price of a ' + product.name + ' is ' + product.netPrice.toFixed(2) +


' USD');

Output:

The net price of a Smartphone is 878.90 USD

In this example, we defined three data properties: name , price , and tax , and one
accessor property netPrice for the product object.

JavaScript object property descriptor


The Object.getOwnPropertyDescriptor() method allows you to get the descriptor object of
a property. The Object.getOwnPropertyDescriptor() method takes two arguments:

1. An object

2. A property of the object

It returns a descriptor object that describes a property. The descriptor object has four
properties: configurable, enumerable, writable, and value.

JavaScript Object Properties 6


The following example gets the descriptor object of the name property of
the product object in the prior example.

let person = {
firstName: 'John',
lastName: 'Doe'
};

let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');

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.

JavaScript uses internal attributes denoted by [[...]] to describe the


characteristics of properties such as [[Configurable]] , [[Enumerable]] , [[Writable]] ,
and [[Value]] , [[Get]] , and [[Set]] .

The method Object.getOwnPropertyDescriptor() return a property descriptor of a


property in an object.

A property can be defined directly on an object or indirectly via


the Object.defineProperty() or Object.defineProperties() methods. These methods
can be used to change the attributes of a property.

JavaScript Object Properties 7


JavaScript for…in Loop
Introduction to JavaScript for...in loop
The for...in loop over the enumerable properties that are keyed by strings of
an object. Note that a property can be keyed by a string or a symbol.

A property is enumerable when its internal enumerable flag is set to true .


The enumerable flag defaults to true when a property is created via a simple assignment
or via a property initializer:

object.propertyName = value;

or

let obj = {
propertyName: value,
...
};

The following shows the syntax of the for...in loop:

for(const propertyName in object) {


// ...
}

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'
};

for(var prop in person) {


console.log(prop + ':' + person[prop]);
}

JavaScript for…in Loop 1


Output:

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];

The for...in loop & Inheritance


When you loop over the properties of an object that inherits from another object,
the for...in statement goes up in the prototype chain and enumerates over inherited
properties. Consider the following example:

var decoration = {
color: 'red'
};

var circle = Object.create(decoration);


circle.radius = 10;

for(const prop in circle) {


console.log(prop);
}

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.

JavaScript for…in Loop 2


If you want to enumerate only the own properties of an object, you use
the hasOwnProperty() method:

for(const prop in circle) {


if(circle.hasOwnProperty(prop)) {
console.log(prop);
}
}

Output:

radius

The for...in loop and Array


It’s good practice to not use the for...in to iterate over an array, especially when the
order of the array elements is important.
The following example works flawlessly:

const items = [10 , 20, 30];


let total = 0;

for(const item in items) {


total += items[item];
}
console.log(total);

However, someone may set a property of the built-in Array type in their libraries as
follows:

Array.prototype.foo = 100;

Hence, the for...in will not work correctly. For example:

// somewhere elseArray.prototype.foo = 100;

const items = [10, 20, 30];

JavaScript for…in Loop 3


let total = 0;

for (var prop in items) {


console.log({ prop, value: items[prop] });
total += items[prop];
}
console.log(total);

Output:

{ prop: '0', value: 10 }


{ prop: '1', value: 20 }
{ prop: '2', value: 30 }
{ prop: 'foo', value: 100 }
160

Or another example:

var arr = [];


// set the third element to 3, other elements are `undefined`
arr[2] = 3;

for (let i = 0; i < arr.length; i++) {


console.log(arr[i]);
}

The output shows three elements of the array, which is correct:

undefined
undefined
3

However, the for...in loop ignores the first two elements:

for (const key in arr) {


console.log(arr[key]);
}

Output:

JavaScript for…in Loop 4


3

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.

JavaScript for…in Loop 5


JavaScript Object.values()
Prior to ES2017, you use a for...in loop and Object.hasOwnProperty() method to access
values of own enumerable properties of an object. For example:

const person = {
firstName: 'John',
lastName: 'Doe',
age: 25
};

for (const key in person) {


if (person.hasOwnProperty(key)) {
const value = person[key];
console.log(value);

}
}

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
};

const profile = Object.values(person);

console.log(profile);

Output:

[ 'John', 'Doe', 25 ]

Object.values() vs. for...in


The Object.values() returns own enumerable properties while the for...in loop iterates
properties in the prototype chain.
Technically, if you use the for...in loop with the Object.hasOwnProperty() method, you
will get the same set of values as the Object.values() .

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.

Here is the syntax of the Object.entries() method:

Object.entries()

See the following example:

const ssn = Symbol('ssn');


const person = {
firstName: 'John',
lastName: 'Doe',
age: 25,
[ssn]: '123-345-789'
};

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.

Using JavaScript Object.assign() to clone an object


The following example uses the Object.assign() method to clone an object.

let widget = {
color: 'red'
};

let clonedWidget = Object.assign({}, widget);

console.log(clonedWidget);

Output

{ color: 'red' }

Note that the Object.assign() only carries a shallow clone, not a deep clone.

Using JavaScript Object.assign() to merge objects


The Object.assign() can merge source objects into a target object which has properties
consisting of all the properties of the source objects. For example:

let box = {
height: 10,

JavaScript Object.assign() 1
width: 20
};

let style = {
color: 'Red',
borderStyle: 'solid'
};

let styleBox = Object.assign({}, box, style);

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'
};

let styleBox = Object.assign({}, box, style);

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.

Object.assign() can be used to clone an object or merge objects.

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:

let amount = +0,


volume = -0;
console.log(volume === amount);

Output:

true

However, the Object.is() treats +0 and -0 as different values. For example:

let amount = +0,


volume = -0;
console.log(Object.is(amount, volume));

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

However, Object.is() treats NaN as the same value:

let quantity = NaN;

console.log(Object.is(quantity, quantity));

Output:

true

See the following sameness comparison table for reference:

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.

Object property initializer shorthand


Prior to ES6, an object literal is a collection of name-value pairs. For example:

function createMachine(name, status) {


return {
name: name,
status: status
};
}

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:

function createMachine(name, status) {


return {
name,
status
};
}

Object Literal Syntax Extensions in ES6 1


Internally, when a property of an object literal only has a name, the JavaScript engine
searches for a variable with the same name in the surrounding scope. If the JavaScript
engine can find one, it assigns the property the value of the variable.
In this example, the JavaScript engine assigns the name and status property values of
the name and status arguments.
Similarly, you can construct an object literal from local variables as shown in the
following example:

let name = 'Computer',


status = 'On';

let machine = {
name,
status
};

Computed property name


Prior to ES6, you could use the square brackets( [] ) to enable the computed
property names for the properties on objects.
The square brackets allow you to use the string literals and variables as the property
names.
See the following example:

let name = 'machine name';


let machine = {
[name]: 'server',
'machine hours': 10000
};

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.

Object Literal Syntax Extensions in ES6 2


In ES6, the computed property name is a part of the object literal syntax, and it uses the
square bracket notation.
When a property name is placed inside the square brackets, the JavaScript engine
evaluates it as a string. It means that you can use an expression as a property name.
For example:

let prefix = 'machine';


let machine = {
[prefix + ' name']: 'server',
[prefix + ' hours']: 10000
};

console.log(machine['machine name']); // server


console.log(machine['machine hours']); // 10000

The machine object’s properties evaluate to 'machine name' and 'machine hours' ,
therefore you can reference them as the properties of the machine object.

Concise method syntax


Prior to ES6, when defining a method for an object literal, you need to specify the name
and full function definition as shown in the following example:

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...");
}
};

Object Literal Syntax Extensions in ES6 3


This shorthand syntax is also known as the concise method syntax. It’s valid to have
spaces in the property name. For example:

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']();

Object Literal Syntax Extensions in ES6 4


JavaScript Class
A JavaScript class is a blueprint for creating objects. A class encapsulates data and
functions that manipulate data.
Unlike other programming languages such as Java and C#, JavaScript classes are
syntactic sugar over the prototypal inheritance. In other words, ES6 classes are just
special functions.

Classes prior to ES6 revisited


Prior to ES6, JavaScript had no concept of classes. To mimic a class, you often use
the constructor/prototype pattern as shown in the following example:

function Person(name) {
this.name = name;
}

Person.prototype.getName = function () {
return this.name;
};

var john = new Person("John Doe");


console.log(john.getName());

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:

console.log(john instanceof Person);// true


console.log(john instanceof Object);// true

ES6 class declaration


ES6 introduced a new syntax for declaring a class as shown in this example:

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:

let john = new Person("John Doe");

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.

console.log(typeof Person);// function

It returns function as expected.


The john object is also an instance of the Person and Object types:

console.log(john instanceof Person);// true


console.log(john instanceof Object);// true

Class vs. Custom type


Despite the similarities between a class and a custom type defined via a constructor
function, there are some important differences.
First, class declarations are not hoisted like function declarations.
For example, if you place the following code above the Person class declaration section,
you will get a ReferenceError .

let john = new Person("John Doe");

Error:

Uncaught ReferenceError: Person is not defined

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.

let john = Person("John Doe");

Error:

Uncaught TypeError: Class constructor Person cannot be invoked without 'new'

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.

A class declaration is a syntactic sugar over prototypal inheritance with additional


enhancements.

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;
}
}

let person = new Person("John");


console.log(person.name);// John

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;
}
}

let person = new Person('Jane Doe');

JavaScript Getters and Setters 1


console.log(person);// Jane Doe

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.

JavaScript Getters and Setters 2


First, the name property is changed to _name to avoid the name collision with the getter
and setter.
Second, the getter uses the get keyword followed by the method name:

get name() {
return this._name;
}

To call the getter, you use the following syntax:

let name = person.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:

person.name = 'Jane Smith';

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:

JavaScript Getters and Setters 3


class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}

let person = new Person("Jane Doe");


console.log(person.name);

// attempt to change the name, but cannot


person.name = 'Jane Smith';
console.log(person.name);// Jane Doe

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.

Using getter in an object literal


The following example defines a getter called latest to return the latest attendee of
the meeting object:

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:

JavaScript Getters and Setters 4


John joined a meeting.
Jane joined a meeting.
Peter joined a meeting.
The latest attendee is Peter.

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.

JavaScript Getters and Setters 5


JavaScript Class Expressions
Introduction to JavaScript class expressions
Similar to functions, classes have expression forms. A class expression provides you
with an alternative way to define a new class.

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:

let Person = class {


constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}

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.

let person = new Person('John Doe');

Like a class declaration, the type of a class expression is also a function:

JavaScript Class Expressions 1


console.log(typeof Person); // function

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();
}

let greeting = factory(class {


sayHi() { console.log('Hi'); }
});

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:

let greeting = factory(class {


sayHi() { console.log('Hi'); }
});

JavaScript Class Expressions 2


The class expression has a method called sayHi() . And the greeting variable is an
instance of the class expression.
Third, call the sayHi() method on the greeting object:

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:

let app = new class {


constructor(name) {
this.name = name;
}
start() {
console.log(`Starting the ${this.name}...`);
}
}('Awesome App');

app.start(); // Starting the Awesome App...

How it works.
The following is an unnamed class expresion:

new class {
constructor(name) {
this.name = name;
}
start() {
console.log(`Starting the ${this.name}...`);
}
}

JavaScript Class Expressions 3


The class has a constructor() that accepts an argument. It aslo has a method
called start() .
The class expression evaluates to a class. Therefore, you can call its constructor
immediately by placing parentheses after the expression:

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:

app.start(); // Starting the Awesome App...

Summary
ES6 provides you with an alternative way to defining a new class using a class
expression.

Class expressions can be named or unnamed.

The class expression can be used to create a singleton object.

JavaScript Class Expressions 4


JavaScript Computed Property
Introduction to JavaScript Computed Property
ES6 allows you to use an expression in brackets [] . It’ll then use the result of the
expression as the property name of an object. For example:

let propName = 'c';

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:

let name = 'fullName';

class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get [name]() {
return `${this.firstName} ${this.lastName}`;
}
}

let person = new Person('John', 'Doe');


console.log(person.fullName);

Output:

JavaScript Computed Property 1


John Doe

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.

JavaScript Computed Property 2


JavaScript Inheritance Using
extends & super
Implementing JavaScript inheritance
using extends and super
Prior to ES6, implementing a proper inheritance required multiple steps. One of the
most commonly used strategies is prototypal inheritance.
The following illustrates how the Bird inherits properties from the Animal using the
prototypal inheritance technique:

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');
}

var pigeon = new Bird(2);


pigeon.walk();// walking on 2 legs
pigeon.fly();// 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.

JavaScript Inheritance Using extends & super 1


class Animal {
constructor(legs) {
this.legs = legs;
}
walk() {
console.log('walking on ' + this.legs + ' legs');
}
}

class Bird extends Animal {


constructor(legs) {
super(legs);
}
fly() {
console.log('flying');
}
}

let bird = new Bird(2);

bird.walk();
bird.fly();

How it works.
First, use the extends keyword to make the Bird class inheriting from the Animal class:

class Bird extends Animal {


// ...
}

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);

JavaScript Inheritance Using extends & super 2


If the Bird class doesn’t have a constructor, you can don’t need to do anything else:

class Bird extends Animal {


fly() {
console.log('flying');
}
}

It is equivalent to the following class:

class Bird extends Animal {


constructor(...args) {
super(...args);
}
fly() {
console.log('flying');
}
}

However, the child class has a constructor, it needs to call super() . For example, the
following code results in an error:

class Bird extends Animal {


constructor(legs) {
}
fly() {
console.log('flying');
}
}

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.

JavaScript Inheritance Using extends & super 3


For example, if you want to initialize the color property of the Bird class, you can do it
as follows:

class Bird extends Animal {


constructor(legs, color) {
super(legs);
this.color = color;
}
fly() {
console.log("flying");
}
getColor() {
return this.color;
}
}

let pegion = new Bird(2, "white");


console.log(pegion.getColor());

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:

class Dog extends Animal {


constructor() {
super(4);
}
walk() {
console.log(`go walking`);
}
}

let bingo = new Dog();


bingo.walk();// go walking

To call the method of the parent class in the child class, you
use super.method(arguments) like this:

JavaScript Inheritance Using extends & super 4


class Dog extends Animal {
constructor() {
super(4);
}
walk() {
super.walk();
console.log(`go walking`);
}
}

let bingo = new Dog();


bingo.walk();
// walking on 4 legs// go walking

Inheriting static members


Besides the properties and methods, the child class also inherits all static properties
and methods of the parent class. For example:

class Animal {
constructor(legs) {
this.legs = legs;
}
walk() {
console.log('walking on ' + this.legs + ' legs');
}
static helloWorld() {
console.log('Hello World');
}
}

class Bird extends Animal {


fly() {
console.log('flying');
}
}

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:

Bird.helloWorld(); // Hello World

JavaScript Inheritance Using extends & super 5


Inheriting from built-in types
JavaScript allows you to extend a built-in type such as Array, String, Map,
and Set through inheritance.
The following Queue class extends the Array reference type. The syntax is much
cleaner than the Queue implemented using the constructor/prototype pattern.

class Queue extends Array {


enqueue(e) {
super.push(e);
}
dequeue() {
return super.shift();
}
peek() {
return !this.empty() ? this[0] : undefined;
}
empty() {
return this.length === 0;
}
}

var customers = new Queue();


customers.enqueue('A');
customers.enqueue('B');
customers.enqueue('C');

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.

JavaScript Inheritance Using extends & super 6


JavaScript new.target
Metaproperty
Introduction to JavaScript new.target
ES6 provides a metaproperty named new.target that allows you to detect whether
a function or constructor was called using the new operator.
The new.target consists of the new keyword, a dot, and target property.
The new.target is available in all functions.
However, in arrow functions, the new.targe t is the one that belongs to the surrounding
function.

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.

JavaScript new.target in functions


Let’s see the following Person constructor function:

function Person(name) {
this.name = name;
}

You can create a new object from the Person function by using the new operator as
follows:

let john = new Person('John');


console.log(john.name);// john

Or you can call the Person as a function:

Person('Lily');

JavaScript new.target Metaproperty 1


Because the this is set to the global object i.e., the window object when you run
JavaScript in the web browser, the name property is added to the window object as
follows:

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.

JavaScript new.target in constructors


In a class constructor, the new.target refers to the constructor that was invoked directly
by the new operator. It is true if the constructor is in the parent class and was
delegated from the constructor of the child class:

class Person {
constructor(name) {
this.name = name;
console.log(new.target.name);
}
}

class Employee extends Person {


constructor(name, title) {
super(name);

JavaScript new.target Metaproperty 2


this.title = title;
}
}

let john = new Person('John Doe'); // Person


let lily = new Employee('Lily Bush', 'Programmer'); // Employee

In this example, new.target.name is the human-friendly name of the constructor reference


of new.target
In this tutorial, you have learned how to use the JavaScript new.target metaproperty to
detect whether a function or constructor was called using the new operator.

JavaScript new.target Metaproperty 3


JavaScript Static Methods
Introduction to the JavaScript static methods
By definition, static methods are bound to a class, not the instances of that class.
Therefore, static methods are useful for defining helper or utility methods.

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:

Person.createAnonymous = function (gender) {


let name = gender == "male" ? "John Doe" : "Jane Doe";
return new Person(name);
};

The createAnonymous() method is considered a static method because it doesn’t depend


on any instance of the Person type for its property values.
To call the createAnonymous() method, you use the Person type instead of its instances:

var anonymous = Person.createAnonymous();

JavaScript static methods in ES6


In ES6, you define static methods using the static keyword. The following example
defines a static method called createAnonymous() for the Person class:

JavaScript Static Methods 1


class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
static createAnonymous(gender) {
let name = gender == "male" ? "John Doe" : "Jane Doe";
return new Person(name);
}
}

To invoke the static method, you use the following syntax:

let anonymous = Person.createAnonymous("male");

If you attempt to call the static method from an instance of the class, you’ll get an error.
For example:

let person = new Person('James Doe');


let anonymous = person.createAnonymous("male");

Error:

TypeError: person.createAnonymous is not a function

Calling a static method from the class constructor or an


instance method
To call a static method from a class constructor or an instance method, you use the
class name, followed by the . and the static method:

className.staticMethodName();

Alternatively, you can use the following syntax:

JavaScript Static Methods 2


this.constructor.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.

Use the className.staticMethodName() or this.constructor.staticMethodName() to call a


static method in a class constructor or an instance method.

JavaScript Static Methods 3


JavaScript Static Properties
Introduction to the JavaScript static properties
Like a static method, a static property is shared by all instances of a class. To define
static property, you use the static keyword followed by the property name like this:

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;

JavaScript Static Properties 1


The following example increases the count static property in the class constructor:

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:

// Item class ...let pen = new Item("Pen", 5);


let notebook = new Item("notebook", 10);

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

JavaScript Static Properties 2


return Item.count;
}
}

let pen = new Item('Pen', 5);


let notebook = new Item('notebook', 10);

console.log(Item.getCount());// 2

Summary
A static property of a class is shared by all instances of that class.

Use the static keyword to define a static property.

Use the className.staticPropertyName to access the static property in a static method.

Use the this.constructor.staticPropertyName or className.staticPropertyName to access


the static property in a constructor.

JavaScript Static Properties 3


JavaScript Private Fields
Introduction to the JavaScript private fields
ES2022 allows you to define private fields for a class. To define a private field, you
prefix the field name with the # sign.

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:

First, define the private field #radius in the class body.

Second, initialize the #radius field in the constructor with an argument.

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:

let circle = new Circle(10);


console.log(circle.area);// 314.1592653589793

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.

Using getter and setter to access private fields


The following redefines the Circle class by adding the radius getter and setter to
provide access to the #radius private field:

JavaScript Private Fields 1


class Circle {
#radius = 0;
constructor(radius) {
this.radius = radius;// calling setter
}
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;
}
}

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.

The constructor calls the radius setter to assign the argument to


the #radius private field.

Private fields and subclasses


Private fields are only accessible inside the class where they’re defined. Also, they’re
not accessible from the subclasses. For example, the following defines
the Cylinder class that extends the Circle class:

class Cylinder extends Circle {


#height;
constructor(radius, height) {
super(radius);
this.#height = height;

// cannot access the #radius of the Circle class here


}
}

JavaScript Private Fields 2


If you attempt to access the #radius private field in the Cylinder class, you’ll get
a SyntaxError .

The in operator: check private fields exist


To check if an object has a private field inside a class, you use the in operator:

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;
}
}

let circle = new Circle(10);

console.log(Circle.hasRadius(circle));

Output:

true

JavaScript Private Fields 3


Static private fields
The following example shows how to use use a static private field:

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;
}
}

let circles = [new Circle(10), new Circle(20), new Circle(30)];

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;

Second, increase the #count by one in the constructor:

Circle.#count++;

JavaScript Private Fields 4


Third, define a static method that returns the value of the #count private static field:

static getCount() {
return Circle.#count;
}

Finally, create three instances of the Circle class and output the count value to the
console:

let circles = [new Circle(10), new Circle(20), new Circle(30)];


console.log(Circle.getCount());

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.

Use the in operator to check if an object has a private field.

JavaScript Private Fields 5


JavaScript Function Type
Introduction to the JavaScript Function type
In JavaScript, all functions are objects. They are the instances of the Function type.
Because functions are objects, they have properties and methods like other objects.

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.

The prototype property references the actual function object.

See the following example:

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:

let result = add(10,20);


console.log(result);// 30

Also, you can call a function with new keyword as a constructor:

let obj = new add(10,20);

JavaScript Function Type 1


ES6 introduced the new.target pseudo-property that allows you to detect whether a
function or constructor was called using the new operator.
If a function is called normally, the new.target is undefined . However, if the function is
called using the new keyword as a constructor, the new.target return a reference to the
constructor.
For example:

function add(x, y) {
console.log(new.target);
return x + y;
}

let result = add(10, 20);


let obj = new add(10, 20);

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;
}

let obj = new add(10, 20);


console.log(obj);

Function methods: apply, call, and bind


A function object has three important methods: apply() , call() and bind() .

JavaScript Function Type 2


The apply() and call() methods
The apply() and call() methods call a function with a given this value and
arguments.
The difference between the apply() and call() is that you need to pass the arguments
to the apply() method as an array-like object, whereas you pass the arguments to
the call() function individually. For example:

let cat = { type: 'Cat', sound: 'Meow' };


let dog = { type: 'Dog', sound: 'Woof' };

const say = function (message) {


console.log(message);
console.log(this.type + ' says ' + this.sound);
};

say.apply(cat, ['What does a cat say?']);


say.apply(dog, ['What does a dog say?']);

Output:

What does a cat sound?


Cat says Meow
What does a dog sound?
Dog says Woof

In this example:
First, declare two objects cat and dog with two properties:

let cat = { type: 'Cat', sound: 'Meow' };


let dog = { type: 'Dog', sound: 'Woof' };

Second, define the say() function that accepts one argument:

const say = function (message) {


console.log(message);
console.log(this.type + ' says ' + this.sound);
};

JavaScript Function Type 3


Third, call the say() function via the apply() method:

say.apply(cat, ['What does a cat say?']);

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:

say.apply(dog, ['What does a dog say?']);

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:

say.call(cat, 'What does a cat say?');


say.call(dog, 'What does a dog say?');

The bind() method


The bind() method creates a new function instance whose this value is bound to the
object that you provide. For example:
First, define an object named car :

let car = {
speed: 5,
start: function() {
console.log('Start with ' + this.speed + ' km/h');
}
};

Then, define another object named aircraft :

let aircraft = {
speed: 10,
fly: function() {
console.log('Flying');

JavaScript Function Type 4


}
};

The aircraft has no start() method. To start an aircraft, you can use the bind() method
of the start() method of the car object:

let taxiing = car.start.bind(aircraft);

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

It will show the following message:

Start with 10 km/h

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

JavaScript Function Type 5


All functions are instances of the Function type, which are the objects that have
properties and methods.

A function has two important properties: length and prototype .

A function also has three important methods: call() , apply() , and bind() .

JavaScript Function Type 6


JavaScript Closures
Introduction to JavaScript closures
In JavaScript, a closure is a function that references variables in the outer scope from
its inner scope. The closure preserves the outer scope inside its inner scope.

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:

let name = 'John';

function greeting() {
let message = 'Hi';
console.log(message + ' '+ name);
}

In this example:

The variable name is a global variable. It is accessible from anywhere including


within the greeting() function.

The variable message is a local variable that is accessible only within


the greeting() function.

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.

More JavaScript Closure example


The following example illustrates a more practical example of closure.

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 in a loop

JavaScript Closures 3
Consider the following example:

for (var index = 1; index <= 3; index++) {


setTimeout(function () {
console.log('after ' + index + ' second(s):' + index);
}, index * 1000);
}

Output

after 4 second(s):4
after 4 second(s):4
after 4 second(s):4

The code shows the same message.


What we wanted to do in the loop is to copy the value of i in each iteration at the time
of iteration to display a message after 1, 2, and 3 seconds.
The reason you see the same message after 4 seconds is that the callback passed to
the setTimeout() a closure. It remembers the value of i from the last iteration of the
loop, which is 4.
In addition, all three closures created by the for-loop share the same global scope
access the same value of i .
To fix this issue, you need to create a new closure scope in each iteration of the loop.
There are two popular solutions: IIFE & let keyword.

1) Using the IIFE solution


In this solution, you use an immediately invoked function expression (a.k.a IIFE)
because an IIFE creates a new scope by declaring a function and immediately execute
it.

for (var index = 1; index <= 3; index++) {


(function (index) {
setTimeout(function () {
console.log('after ' + index + ' second(s):' + index);
}, index * 1000);
})(index);
}

JavaScript Closures 4
Output

after 1 second(s):1
after 2 second(s):2
after 3 second(s):3

2) Using let keyword in ES6


In ES6, you can use the let keyword to declare a variable that is block-scoped.
If you use the let keyword in the for-loop, it will create a new lexical scope in each
iteration. In other words, you will have a new index variable in each iteration.
In addition, the new lexical scope is chained up to the previous scope so that the
previous value of the index is copied from the previous scope to the new one.

for (let index = 1; index <= 3; index++) {


setTimeout(function () {
console.log('after ' + index + ' second(s):' + index);
}, index * 1000);
}

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.

A closure is a combination of a function and its ability to remember variables in the


outer scope.

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:

let add = function (x, y) {


return x + y;
};

console.log(add(10, 20));// 30

The following example is equivalent to the above add() function expression but use an
arrow function instead:

let add = (x, y) => x + y;

console.log(add(10, 20));// 30;

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:

let add = (x, y) => { return x + y; };

The typeof operator returns function indicating the type of arrow function.

console.log(typeof add);// function

The arrow function is also an instance of the Function type as shown in the following
example:

JavaScript Arrow Functions 1


console.log(add instanceof Function);// true

JavaScript arrow functions with multiple parameters


If an arrow function has two or more parameters, you use the following syntax:

(p1, p2, ..., pn) => expression;

The following expression:

=> expression

is equivalent to the following expression:

=> { return expression; }

For example, to sort an array of numbers in the descending order, you use
the sort() method of the array object as follows:

let numbers = [4,2,6];


numbers.sort(function(a,b){
return b - a;
});
console.log(numbers);// [6,4,2]

The code is more concise with the arrow function syntax:

let numbers = [4,2,6];


numbers.sort((a,b) => b - a);
console.log(numbers);// [6,4,2]

JavaScript arrow functions with a single parameter


If an arrow function takes a single parameter, you use the following syntax:

JavaScript Arrow Functions 2


(p1) => { statements }

Note that you can omit the parentheses 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.

let names = ['John', 'Mac', 'Peter'];


let lengths = names.map(name => name.length);

console.log(lengths);

Output:

[ 4, 3, 5 ]

JavaScript arrow functions with no parameter


If the arrow function has no parameter, you need to use parentheses, like this:

() => { statements }

For example:

let logDoc = () => console.log(window.document);


logDoc();

Line break between parameter definition and arrow


JavaScript doesn’t allow you to have a line break between the parameter definition and
the arrow ( => ) in an arrow function.
For example, the following code causes a SyntaxError :

JavaScript Arrow Functions 3


let multiply = (x,y)
=> x * y;

However, the following code works perfectly fine:

let multiply = (x,y) =>


x * y;

JavaScript allows you to have line breaks between parameters as shown in the
following example:

let multiply = (
x,
y
) =>
x * y;

Statements & expressions in the arrow function body


In JavaScript, an expression evaluates to a value as shown in the following example.

10 + 20;

A statement does a specific task such as:

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.

let square = x => x * x;

JavaScript Arrow Functions 4


However, if you use a statement, you must wrap it inside a pair of curly braces as in the
following example:

let except = msg => {


throw msg;
};

JavaScript arrow functions and object literal


Consider the following example:

let setColor = function (color) {


return {value: color}
};

let backgroundColor = setColor('Red');


console.log(backgroundColor.value);// "Red"

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}

For example, the following code causes an error.

let setColor = color => {value: color };

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:

let setColor = color => ({value: color });

JavaScript Arrow Functions 5


Arrow function vs. regular function
There are two main differences between an arrow function and a regular function.

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.

2. Second, an arrow function cannot be used as a function constructor. If you use


the new keyword to create a new object from an arrow function, you will get an
error.

JavaScript arrow functions and this value


In JavaScript, a new function defines its own this value. However, it is not the case for
the arrow function. See the following example:

function Car() {
this.speed = 0;

this.speedUp = function (speed) {


this.speed = speed;
setTimeout(function () {
console.log(this.speed);// undefined
}, 1000);

};
}

let car = new Car();


car.speedUp(50);

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;

this.speedUp = function (speed) {


this.speed = speed;

JavaScript Arrow Functions 6


let self = this;
setTimeout(function () {
console.log(self.speed);
}, 1000);

};
}

let car = new Car();


car.speedUp(50);// 50;

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;

this.speedUp = function (speed) {


this.speed = speed;
setTimeout(
() => console.log(this.speed),
1000);

};
}

let car = new Car();


car.speedUp(50);// 50;

JavaScript arrow functions and the arguments object


An arrow function doesn’t have the arguments object. For example:

function show() {
return x => x + arguments[0];
}

let display = show(10, 20);


let result = display(5);
console.log(result);// 15

The arrow function inside the showMe() function references the arguments object.
However, this arguments object belongs to the show() function, not the arrow function.

JavaScript Arrow Functions 7


Also, an arrow function doesn’t have the new.target keyword.

JavaScript arrow functions and the prototype property


When you define a function using a function keyword, the function has a property
called prototype :

function dump( message ) {


console.log(message);
}
console.log(dump.hasOwnProperty('prototype'));// true

However, arrow functions don’t have the prototype property:

let dump = message => console.log(message);


console.log(dump.hasOwnProperty('prototype'));// false

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.

An arrow function doesn’t have its binding to this or super .

An arrow function doesn’t have arguments object, new.target keyword,


and prototype property.

JavaScript Arrow Functions 8


When You Should Not Use Arrow
Functions
An arrow function doesn’t have its own this value and the arguments object. Therefore,
you should not use it as an event handler, a method of an object literal, a prototype
method, or when you have a function that uses the arguments object.

1) Event handlers
Suppose that you have the following input text field:

<input type="text" name="username" id="username" placeholder="Enter a username">

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:

const greeting = document.querySelector('#greeting');


const username = document.querySelector('#username');
username.addEventListener('keyup', () => {
greeting.textContent = 'Hello ' + this.value;
});

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 .

When You Should Not Use Arrow Functions 1


As mentioned earlier, the arrow function doesn’t have its own this value. It uses
the this value of the enclosing lexical scope. In the above example, the this in arrow
function references the global object.
In the web browser, the global object is window . The window object doesn’t have
the value property. Therefore, the JavaScript engine adds the value property to
the window object and sets its values to undefined .
To fix this issue, you need to use a regular function instead. The this value will be
bound to the <input> element that triggers the event.

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

However, it returns NaN .


The reason is that when you use the arrow function inside the object, it inherits
the this value from the enclosing lexical scope which is the global scope in this
example.

When You Should Not Use Arrow Functions 2


The this.count inside the next() method is equivalent to the window.count (in the web
browser).
The window.count is undefined by default because the window object doesn’t have
the count property. The next() method adds one to undefined that results in NaN .
To fix this, you use regular functions as the method of an object literal as follows:

const counter = {
count: 0,
next() {
return ++this.count;
},
current() {
return this.count;
}
};

Now, calling the next() method will return one as expected:

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:

When You Should Not Use Arrow Functions 3


function Counter() {
this.count = 0;
}

Counter.prototype.next = function () {
return this.count;
};

Counter.prototype.current = function () {
return ++this.next;
}

4) Functions that use the arguments object


Arrow functions don’t have the arguments object. Therefore, if you have a function that
uses arguments object, you cannot use the arrow function.
For example, the following concat() function won’t work:

const concat = (separator) => {


let args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}

Instead, you use a regular function like this:

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.

When You Should Not Use Arrow Functions 4


JavaScript Rest Parameters
Introduction to JavaScript rest parameters
ES6 provides a new kind of parameter so-called rest parameter that has a prefix of
three dots (...) . A rest parameter allows you to represent an indefinite number of
arguments as an array. See the following syntax:

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:

fn(1, 2, 3, "A", "B", "C");

The args array stores the following values:

[3,'A','B','C']

If you pass only the first two parameters, the rest parameter will be an empty array:

fn(1,2);

The args will be:

[]

JavaScript Rest Parameters 1


Notice that the rest parameters must appear at the end of the argument list. The
following code will result in an error:

function fn(a,...rest, b) {
// error
}

Error:

SyntaxError: Rest parameter must be last formal parameter

More JavaScript rest parameters examples


See the following example:

function sum(...args) {
let total = 0;
for (const a of args) {
total += a;
}
return total;
}

sum(1, 2, 3);

The output of the script is:

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

JavaScript Rest Parameters 2


.filter(function (e) {
return typeof e === 'number';
})
.reduce(function (prev, curr) {
return prev + curr;
});
}

The following script uses the new sum() function to sum only numeric arguments:

let result = sum(10,'Hi',null,undefined,20);


console.log(result);

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:

function filterBy(type, ...args) {


return args.filter(function (e) {

JavaScript Rest Parameters 3


return typeof e === type;
});
}

JavaScript rest parameters and arrow function


An arrow function does not have the arguments object. Therefore, if you want to pass
some arguments to the arrow function, you must use the rest parameters. See the
following example:

const combine = (...args) => {


return args.reduce(function (prev, curr) {
return prev + ' ' + curr;
});
};

let message = combine('JavaScript', 'Rest', 'Parameters'); // =>console.log(message);


// JavaScript Rest Parameters

Output:

JavaScript Rest Parameters

The combine() function is an arrow that takes an indefinite number of arguments and
concatenates these arguments.

JavaScript rest parameter in a dynamic function


JavaScript allows you to create dynamic functions through the Function constructor.
And it is possible to use the rest parameter in a dynamic function. Here is an example:

var showNumbers = new Function('...numbers', 'console.log(numbers)');


showNumbers(1, 2, 3);

Output:

[ 1, 2, 3 ]

JavaScript Rest Parameters 4


In this tutorial, you have learned how to use the JavaScript rest parameter to represent
an indefinite number of arguments as an array.

JavaScript Rest Parameters 5


JavaScript Callbacks
What are callbacks
In JavaScript, functions are first-class citizens. Therefore, you can pass a function to
another function as an argument.

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.

Second, pass the function to the filter() function as an argument.

JavaScript Callbacks 1
Here’s the updated code:

function isOdd(number) {
return number % 2 != 0;
}

function filter(numbers, fn) {


let results = [];
for (const number of numbers) {
if (fn(number)) {
results.push(number);
}
}
return results;
}
let numbers = [1, 2, 4, 7, 3, 5, 6];
console.log(filter(numbers, isOdd));

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;
}

function filter(numbers, fn) {


let results = [];
for (const number of numbers) {
if (fn(number)) {
results.push(number);
}
}
return results;
}
let numbers = [1, 2, 4, 7, 3, 5, 6];

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:

function filter(numbers, callback) {


let results = [];
for (const number of numbers) {
if (callback(number)) {
results.push(number);
}
}
return results;
}

let numbers = [1, 2, 4, 7, 3, 5, 6];

let oddNumbers = filter(numbers, function (number) {


return number % 2 != 0;
});

console.log(oddNumbers);

In this example, we pass an anonymous function to the filter() function instead of


using a separate function.
In ES6, you can use an arrow function like this:

function filter(numbers, callback) {


let results = [];
for (const number of numbers) {
if (callback(number)) {
results.push(number);
}
}
return results;
}

let numbers = [1, 2, 4, 7, 3, 5, 6];

let oddNumbers = filter(numbers, (number) => number % 2 != 0);

console.log(oddNumbers);

There are two types of callbacks: synchronous and asynchronous callbacks.

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}`);
}

When you execute the following code:

let url = 'https://www.xyz.net/pic.jpg';

download(url);
process(url);

you will get the following output:

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:

Download the picture and wait for the download completes.

Process the picture.

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 download(url, callback) {


setTimeout(() => {
// script to download the picture here
console.log(`Downloading ${url} ...`);

// process the picture once it is completed


callback(url);
}, 1000);
}

function process(picture) {
console.log(`Processing ${picture}`);

JavaScript Callbacks 5
}

let url = 'https://wwww.xyz.net/pic.jpg';


download(url, process);

Output:

Downloading https://www.xyz.net/pic.jpg ...


Processing https://www.xyz.net/pic.jpg

Now, it works as expected.


In this example, the process() is a callback passed into an asynchronous function.
When you use a callback to continue code execution after an asynchronous operation,
the callback is called an asynchronous callback.
To make the code more concise, you can define the process() function as an
anonymous function:

function download(url, callback) {


setTimeout(() => {
// script to download the picture here
console.log(`Downloading ${url} ...`);
// process the picture once it is completed
callback(url);

}, 1000);
}

let url = 'https://www.xyz.net/pic.jpg';


download(url, function(picture) {
console.log(`Processing ${picture}`);
});

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:

function download(url, success, failure) {


setTimeout(() => {

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`)
);

Nesting callbacks and the Pyramid of Doom


How do you download three pictures and process them sequentially? A typical
approach is to call the download() function inside the callback function, like this:

function download(url, callback) {


setTimeout(() => {
console.log(`Downloading ${url} ...`);
callback(url);
}, 1000);
}

const url1 = 'https://www.xyz.net/pic1.jpg';


const url2 = 'https://www.xyz.net/pic2.jpg';
const url3 = 'https://www.xyz.net/pic3.jpg';

download(url1, function (url) {


console.log(`Processing ${url}`);
download(url2, function (url) {
console.log(`Processing ${url}`);
download(url3, function (url) {
console.log(`Processing ${url}`);
});
});
});

Output:

Downloading https://www.xyz.net/pic1.jpg ...


Processing https://www.xyz.net/pic1.jpg
Downloading https://www.xyz.net/pic2.jpg ...
Processing https://www.xyz.net/pic2.jpg
Downloading https://www.xyz.net/pic3.jpg ...
Processing https://www.xyz.net/pic3.jpg

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(){
....
});
});
});
});
});

To avoid the pyramid of doom, you use promises or async/await functions.

Summary
A callback is a function passed into another function as an argument to be executed
later.

A high-order function is a function that accepts another function as an argument.

Callback functions can be synchronous or asynchronous.

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:

let promise = new Promise(function(resolve, reject) {


// executor (the producing code, "singer")
});

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:

resolve(value) — if the job is finished successfully, with result value .

reject(error) — if an error has occurred, error is the error object.

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:

state — initially "pending" , then changes to either "fulfilled" when resolve is


called or "rejected" when reject is called.

result — initially undefined , then changes to value when resolve(value) is called


or error when reject(error) is called.

So the executor eventually moves promise to one of these states:

Later we’ll see how “fans” can subscribe to these changes.


Here’s an example of a promise constructor and a simple executor function with
“producing code” that takes time (via setTimeout ):

let promise = new Promise(function(resolve, reject) {


// the function is executed automatically when the promise is constructed

// after 1 second signal that the job is done with the result "done"
setTimeout(() => resolve("done"), 1000);
});

We can see two things by running the code above:

1. The executor is called automatically and immediately (by new Promise ).

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:

That was an example of a successful job completion, a “fulfilled promise”.


And now an example of the executor rejecting the promise with an error:

let promise = new Promise(function(resolve, reject) {


// after 1 second signal that the job is finished with an error
setTimeout(() => reject(new Error("Whoops!")), 1000);
});

The call to reject(...) moves the promise object to "rejected" state:


To summarize, the executor should perform a job (usually something that takes time)
and then call resolve or reject to change the state of the corresponding promise
object.
A promise that is either resolved or rejected is called “settled”, as opposed to an initially
“pending” promise.
There can be only a single result or an error
The executor should call only one resolve or one reject . Any state change is final.
All further calls of resolve and reject are ignored:

let promise = new Promise(function(resolve, reject) {


resolve("done");reject(new Error("…")); // ignored
setTimeout(() => resolve("…")); // ignored
});

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:

let promise = new Promise(function(resolve, reject) {


// not taking our time to do the job
resolve(123); // immediately give the result: 123
});

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.

Consumers: then, catch


A Promise object serves as a link between the executor (the “producing code” or
“singer”) and the consuming functions (the “fans”), which will receive the result or error.
Consuming functions can be registered (subscribed) using the
methods .then and .catch .

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:

let promise = new Promise(function(resolve, reject) {


setTimeout(() => resolve("done!"), 1000);
});

// resolve runs the first function in .then


promise.then(
result => alert(result),
// shows "done!" after 1 seconderror => alert(error) // doesn't run
);

The first function was executed.


And in the case of a rejection, the second one:

let promise = new Promise(function(resolve, reject) {


setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// reject runs the second function in .then


promise.then(
result => alert(result), // doesn't run
error => alert(error) // shows "Error: Whoops!" after 1 second);

If we’re interested only in successful completions, then we can provide only one function
argument to .then :

let promise = new Promise(resolve => {


setTimeout(() => resolve("done!"), 1000);
});

promise.then(alert); // shows "done!" after 1 second

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:

let promise = new Promise((resolve, reject) => {


setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// .catch(f) is the same as promise.then(null, f)


promise.catch(alert); // shows "Error: Whoops!" after 1 second

The call .catch(f) is a complete analog of .then(null, f) , it’s just a shorthand.

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:

new Promise((resolve, reject) => {


/* do something that takes time, and then call resolve or maybe reject */
})
// runs when the promise is settled doesn't matter successful or not
.finally(() => stop loading indicator)
// so the loading indicator is always stopped before we go on.then(result => show resul
t, err => show error)

Please note that finally(f) isn’t exactly an alias of then(f,f) though.


There are important differences:

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 :

new Promise((resolve, reject) => {


setTimeout(() => resolve("value"), 2000);
})
.finally(() => alert("Promise ready")) // triggers first
.then(result => alert(result)); // <-- .then shows "value"

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 :

new Promise((resolve, reject) => {


throw new Error("error");
})
.finally(() => alert("Promise ready")) // triggers first
.catch(err => alert(err)); // <-- .catch shows the error

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:

// the promise becomes resolved immediately upon creation


let promise = new Promise(resolve => resolve("done!"));

promise.then(alert); // done! (shows up right now)

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:

function loadScript(src, callback) {


let script = document.createElement('script');
script.src = src;

script.onload = () => callback(null, script);


script.onerror = () => callback(new Error(`Script load error for ${src}`));

JavaScript Promises 8
document.head.append(script);
}

Let’s rewrite it using Promises.


The new function loadScript will not require a callback. Instead, it will create and return
a Promise object that resolves when the loading is complete. The outer code can add
handlers (subscribing functions) to it using .then :

function loadScript(src) {
return new Promise(function(resolve, reject) {
let script = document.createElement('script');
script.src = src;

script.onload = () => resolve(script);


script.onerror = () => reject(new Error(`Script load error for ${src}`));

document.head.append(script);
});
}

Usage:

let promise = loadScript("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.


js");

promise.then(
script => alert(`${script.src} is loaded!`),
error => alert(`Error: ${error.message}`)
);

promise.then(script => alert('Another handler...'));

We can immediately see a few benefits over the callback-based pattern:

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.

So promises give us better code flow and flexibility.

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:

1. Select a user from the database.

2. Get services of the user from an API.

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.

function getUser(userId, callback) {


console.log('Get user from the database.');
setTimeout(() => {
callback({
userId: userId,
username: 'john'
});
}, 1000);
}

function getServices(user, callback) {


console.log(`Get services of ${user.username} from the API.`);
setTimeout(() => {
callback(['Email', 'VPN', 'CDN']);
}, 2 * 1000);
}

function getServiceCost(services, callback) {


console.log(`Calculate service costs of ${services}.`);
setTimeout(() => {
callback(services.length * 100);
}, 3 * 1000);
}

The following shows the nested callback functions:

JavaScript async/await 1
getUser(100, (user) => {
getServices(user, (services) => {
getServiceCost(services, (cost) => {
console.log(`The service cost is ${cost}`);
});
});
});

Output:

Get user from the database.


Get services of john from the API.
Calculate service costs of Email,VPN,CDN.
The service cost is 300

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);
});
}

Then, you chain the promises:

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:

let result = await f();

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:

async function showServiceCost() {


let user = await getUser(100);
let services = await getServices(user);
let cost = await getServiceCost(services);
console.log(`The service cost is ${cost}`);
}

showServiceCost();

As you can see, the asynchronous code now looks like the synchronous code.
Let’s dive in the async / await keywords.

The async keyword

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:

async function sayHi() {


return 'Hi';
}

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:

async function sayHi() {


return Promise.resolve('Hi');
}

The effect is the same.


Besides the regular functions, you can use the async keyword in the function
expressions:

let sayHi = async function () {


return 'Hi';
}

arrow functions:

let sayHi = async () => 'Hi';

JavaScript async/await 4
and methods of classes:

class Greeter {
async sayHi() {
return 'Hi';
}
}

The await keyword


You use the await keyword to wait for a Promise to settle either in resolved or rejected
state. And you can use the await keyword only inside an async function:

async function display() {


let result = await sayHi();
console.log(result);
}

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:

async function getUser(userId) {


await Promise.reject(new Error('Invalid User Id'));
}

… is the same as this:

async function getUser(userId) {


throw new Error('Invalid User Id');

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:

async function getUser(userId) {


try {
const user = await Promise.reject(new Error('Invalid User Id'));
} catch(error) {
console.log(error);
}
}

It’s possible to catch errors caused by one or more await promise ‘s:

async function showServiceCost() {


try {
let user = await getUser(100);
let services = await getServices(user);
let cost = await getServiceCost(services);
console.log(`The service cost is ${cost}`);
} catch(error) {
console.log(error);
}
}

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.

A document as a hierarchy of nodes


The DOM represents an HTML document as a hierarchy of nodes. Consider the
following HTML document:

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

Constant Value Description

JavaScript DOM 2
Node.ELEMENT_NODE 1
An Element node like <p> or <div> .

The actual Text inside


Node.TEXT_NODE 3
an Element or Attr .
A CDATASection , such as <!CDATA[[ …
Node.CDATA_SECTION_NODE 4
]]> .
A ProcessingInstruction of an XML
Node.PROCESSING_INSTRUCTION_NODE 7 document, such as <?xml-stylesheet …

?> .

Node.COMMENT_NODE 8 A Comment node, such as <!-- … --> .


Node.DOCUMENT_NODE 9 A Document node.

A DocumentType node, such


Node.DOCUMENT_TYPE_NODE 10
as <!DOCTYPE html> .
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.

To get the type of node, you use the nodeType property:

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
}

The nodeName and nodeValue properties


A node has two important properties: nodeName and nodeValue that provide specific
information about the node.
The values of these properties depend on the node type. For example, if the node type
is the element node, the nodeName is always the same as the element’s tag name
and nodeValue is always null .
For this reason, it’s better to test node type before using these properties:

JavaScript DOM 3
if (node.nodeType == Node.ELEMENT_NODE) {
let name = node.nodeName;// tag name like <p>
}

Node and Element


Sometimes it’s easy to confuse between the Node and the Element .
A node is a generic name of any object in the DOM tree. It can be any built-in DOM
element such as the document. Or it can be any HTML tag specified in the HTML
document like <div> or <p> .
An element is a node with a specific node type Node.ELEMENT_NODE , which is equal to 1.
In other words, the node is the generic type of element. The element is a specific type of
the node with the node type Node.ELEMENT_NODE .
The following picture illustrates the relationship between the Node and Element types:

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.

Each markup can be represented as a node with a specific node type.

Element is a specific type of node with the node type Node.ELEMENT_NODE .

In the DOM tree, a node has relationships with other nodes.

JavaScript DOM 6
getElementsByName
Introduction to JavaScript getElementsByName()
method
Every element on an HTML document may have a name attribute:

<input type="radio" name="language" value="JavaScript">

Unlike the id attribute, multiple HTML elements can share the same value of
the name attribute like this:

<input type="radio" name="language" value="JavaScript">


<input type="radio" name="language" value="TypeScript">

To get all elements with a specified name, you use the getElementsByName() method of
the document object:

let elements = document.getElementsByName(name);

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.

JavaScript getElementsByName() example


The following example shows a radio group that consists of radio buttons that have the
same name ( rate ).
When you select a radio button and click the submit button, the page will show the
selected value such as Very Poor , Poor , OK , Good , or Very Good :

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.

Second, listen to the click event of the submit button.

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.

The NodeList is an array-like object, not an array object.

getElementsByName 3
getElementsByTagName
Introduction to JavaScript getElementsByTagName() method
The getElementsByTagName() is a method of the document object or a specific DOM
element.

The getElementsByTagName() method accepts a tag name and returns a


live HTMLCollection of elements with the matching tag name in the order which they
appear in the document.
The following illustrates the syntax of the getElementsByTagName() :

let elements = document.getElementsByTagName(tagName);

The return collection of the getElementsByTagName() is live, meaning that it is automatically


updated when elements with the matching tag name are added and/or removed from
the document.
Note that the HTMLCollection is an array-like object, like arguments object of a function.

JavaScript getElementsByTagName() example


The following example illustrates how to use the getElementsByTagName() method to get
the number of H2 tags in the document.
When you click the Count H2 button, the page shows the number of H2 tags:

<!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:

First, select the button Count H2 by using the getElementById() method.

Second, hook the click event of the button to an anonymous function.

Third, in the anonymous function, use the document.getElementsByTagName() to get a list


of H2 tags.

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.

The getElementsByTagName() returns a live HTMLCollection of elements.


The HTMLCollection is an array-like object.

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:

let elements = document.getElementsByClassName(names);

However, when calling the method on a specific element, it returns the descendants of
that specific element with the given class name:

let elements = rootElement.getElementsByClassName(names);

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.

JavaScript getElementsByClassName() method


examples
Let’s take some examples of using the getElementsByClassName() method.

Suppose that you have the following HTML document:

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

1) Calling JavaScript getElementsByClassName() on an element


example
The following example illustrates how to use the getElementsByClassName() method to
select the <li> items which are the descendants of the <ul> element:

let menu = document.getElementById('menu');


let items = menu.getElementsByClassName('item');

let data = [].map.call(items, item => item.textContent);

console.log(data);

Output:

['HTML', 'CSS', 'JavaScript', 'TypeScript']

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.

Finally, create an array of the text content of <li> elements by borrowing


the map() method of the Array object.

2) Calling JavaScript getElementsByClassName() on the document


example
To search for the element with the class heading-secondary , you use the following code:

let elements = document.getElementsByClassName('secondary');


let data = [].map.call(elements, elem => elem.textContent);

console.log(data);

Output:

["Example 1", "Example 2"]

This example calls the getElementsByClassName() method on the document object.


Therefore, it searches for the elements with the class secondary in the entire document.

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:

let element = parentNode.querySelector(selector);

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:

let elementList = parentNode.querySelectorAll(selector);

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:

let nodeList = document.querySelectorAll(selector);


let elements = Array.from(nodeList);

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:

let element = document.querySelector('*');

And this select all elements in the document:

let elements = document.querySelectorAll('*');

2) Type selector
To select elements by node name, you use the type selector e.g., a selects
all <a> elements:

elementName

The following example finds the first h1 element in the document:

let firstHeading = document.querySelector('h1');

And the following example finds all h2 elements:

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:

let note = document.querySelector('.menu-item');

And the following example finds all elements with the menu class:

let notes = document.querySelectorAll('.menu-item');

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 :

let logo = document.querySelector('#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:

let autoplay = document.querySelector('[autoplay]');

And the following example finds all elements that have [autoplay] attribute with any
value:

let autoplays = document.querySelectorAll('[autoplay]');

Grouping selectors
To group multiple selectors, you use the following syntax:

selector, selector, ...

The selector list will match any element with one of the selectors in the group.
The following example finds all <div> and <p> elements:

let elements = document.querySelectorAll('div, p');

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:

let links = document.querySelector('p a');

2) Child combinator
The > child combinator finds all elements that are direct children of the first element:

selector > selector

The following example finds all li elements that are directly inside a <ul> element:

let listItems = document.querySelectorAll('ul > li');

To select all li elements that are directly inside a <ul> element with the class nav :

let listItems = document.querySelectorAll('ul.nav > li');

3) General sibling combinator


The ~ combinator selects siblings that share the same parent:

selector ~ selector

For example, p ~ a will match all <a> elements that follow the p element, immediately
or not:

let links = document.querySelectorAll('p ~ a');

4) Adjacent sibling combinator

querySelector 6
The + adjacent sibling combinator selects adjacent siblings:

selector + selector

For example, h1 + a matches all elements that directly follow an h1 :

let links = document.querySelectorAll('h1 + a');

And select the first <a> that directly follows an h1 :

let links = document.querySelector('h1 + a');

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:

let listItem = document.querySelectorAll('li:nth-child(2)');

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:

let links = document.querySelector('p::first-line');

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.

A CSS selector defines elements to which a CSS rule applies.

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:

let parent = node.parentNode;

The parentNode is read-only.

The Document and DocumentFragment nodes do not have a parent. Therefore,


the parentNode will always be null .
If you create a new node but haven’t attached it to the DOM tree, the parentNode of that
node will also be null .

JavaScript parentNode example


See the following HTML document:

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

JavaScript Get the Parent Element parentNode 1


The following picture shows the output in the Console:

How it works:

First, select the element with the .note class by using the querySelector() method.

Second, find the parent node of the element.

Summary
The node.parentNode returns the read-only parent node of a specified node or null if
it does not exist.

The document and DocumentFragment do not have a parent node.

JavaScript Get the Parent Element parentNode 2


Getting Child Elements
Suppose that you have the following HTML fragment:

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

Get the first child element


To get the first child element of a specified element, you use the firstChild property of
the element:

let firstChild = parentElement.firstChild;

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:

let content = document.getElementById('menu');


let firstChild = content.firstChild.nodeName;
console.log(firstChild);

Getting Child Elements 1


Output:

#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:

<article id="content"><h2>Heading</h2><p>First paragraph</p></article>

Or to get the first child with the Element node only, you can use
the firstElementChild property:

let firstElementChild = parentElement.firstElementChild;

The following code returns the first list item which is the first child element of the menu:

let content = document.getElementById('menu');


console.log(content.firstElementChild);

Output:

<li class="first">Home</li>

In this example:

First, select the #menu element by using the getElementById() method.

Second, get the first child element by using the firstElementChild property.

Get the last child element

Getting Child Elements 2


To get the last child element of a node, you use the lastChild property:

let lastChild = parentElement.lastChild;

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:

let lastChild = parentElement.lastElementChild;

The following code returns the list item which is the last child element of the menu:

let menu = document.getElementById('menu');


console.log(main.lastElementChild);

Output:

<li class="last">About Us</li>

Get all child elements


To get a live NodeList of child elements of a specified element, you use
the childNodes property:

let children = parentElement.childNodes;

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:

let children = parentElement.children;

The following example selects all child elements of the element with the Id main :

Getting Child Elements 3


let menu = document.getElementById('menu');
let children = menu.children;
console.log(children);

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.

Getting Child Elements 4


JavaScript Siblings
Let’s say you have the following list of items:

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

Get the next siblings


To get the next sibling of an element, you use the nextElementSibling attribute:

let nextSibling = currentNode.nextElementSibling;

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:

let current = document.querySelector('.current');


let nextSibling = current.nextElementSibling;

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:

let current = document.querySelector('.current');


let nextSibling = current.nextElementSibling;

while(nextSibling) {
console.log(nextSibling);
nextSibling = nextSibling.nextElementSibling;
}

Get the previous siblings


To get the previous siblings of an element, you use the previousElementSibling attribute:

let current = document.querySelector('.current');


let prevSibling = currentNode.previousElementSibling;

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:

let current = document.querySelector('.current');


let prevSiblings = current.previousElementSibling;

console.log(prevSiblings);

And the following example selects all the previous siblings of the list item that has
the current class:

let current = document.querySelector('.current');


let prevSibling = current.previousElementSibling;
while(prevSibling) {
console.log(prevSibling);
prevSibling = current.previousElementSibling;
}

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.

Second, select the first child element of that parent element.

Third, add the first element to an array of siblings.

Fourth, select the next sibling of the first element.

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.

The following function illustrates the steps:

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;
};

Put it all together:

<!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;
};

let siblings = getSiblings(document.querySelector('.current'));


siblingText = siblings.map(e => e.innerHTML);
console.log(siblingText);
</script>
</body>
</html>

Output:

["Home", "Products", "Careers", "Investors", "News", "About Us"]

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:

let element = document.createElement(htmlTag);

The document.createElement() accepts an HTML tag name and returns a new Node with
the Element type.

1) Creating a new div example


Suppose that you have the following HTML document:

<!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:

let div = document.createElement('div');

And add an HTML snippet to the div :

div.innerHTML = '<p>CreateElement example</p>';

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>

Adding an id to the div


If you want to add an id to a div , you set the id attribute of the element to a value, like
this:

let div = document.createElement('div');


div.id = 'content';
div.innerHTML = '<p>CreateElement example</p>';

document.body.appendChild(div);

Adding a class to the div


The following example set the CSS class of a new div note :

let div = document.createElement('div');


div.id = 'content';
div.className = 'note';
div.innerHTML = '<p>CreateElement example</p>';

document.body.appendChild(div);

Adding text to a 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 :

//Create a new div and set its attributes


let div = document.createElement('div');
div.id = 'content';
div.className = 'note';

// create a new text node and add it to the div


let text = document.createTextNode('CreateElement example');
div.appendChild(text);

// add div to the document


document.body.appendChild(div);

Adding an element to a div


To add an element to a div , you create an element and append it to the div using
the appendChild() method:

let div = document.createElement('div');


div.id = 'content';
div.className = 'note';

// create a new heading and add it to the div

let h2 = document.createElement('h2');
h2.textContent = 'Add h2 element to the div';
div.appendChild(h2);

// add div to the document

document.body.appendChild(div);

2) Creating new list items ( li ) example


Let’s say you have a list of items:

<ul id="menu"><li>Home</li></ul>

The following code adds two li elements to the ul :

CreateElement 3
let li = document.createElement('li');
li.textContent = 'Products';
menu.appendChild(li);

li = document.createElement('li');
li.textContent = 'About Us';

// select the ul menu element

const menu = document.querySelector('#menu');


menu.appendChild(li);

Output:

<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>

3) Creating a script element example


Sometimes, you may want to load a JavaScript file dynamically. To do this, you can use
the document.createElement() to create the script element and add it to the document.
The following example illustrates how to create a new script element and loads
the /lib.js file to the document:

let script = document.createElement('script');


script.src = '/lib.js';
document.body.appendChild(script);

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');

To load a JavaScript file asynchronously, you set the async attribute of


the script element to true :

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.

The element.appendChild() appends an HTML element to an existing 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.

The following illustrates the syntax of the appendChild() method:

parentNode.appendChild(childNode);

In this method, the childNode is the node to append to the given parent node.
The appendChild() returns the appended child.

If the childNode is a reference to an existing node in the document,


the appendChild() method moves the childNode from its current position to the new
position.

JavaScript appendChild() examples


Let’s take some examples of using the appendChild() method.

1) Simple appendChild() example


Suppose that you have the following HTML markup:

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

Put it all together:

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

2) Moving a node within the document example


Assuming that you have two lists of items:

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

// get the first list


const firstList = document.querySelector('#first-list');

//Take the first child element


const everest = firstList.firstElementChild;

// get the second list


const secondList = document.querySelector('#second-list');

// append the everest to the second list


secondList.appendChild(everest)

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.

Third, select the second element by its id ( second-list ) using


the querySelector() method.

appendChild 3
Finally, append the first child element from the first list to the second list using
the appendChild() method.

Here are the list before and after moving:

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:

let text = node.textContent;

Suppose that you have the following HTML snippet:

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

let note = document.getElementById('note');


console.log(note.textContent);

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:

JavaScript textContent Demo!


Hidden Text!

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:

let note = document.getElementById('note');


console.log(note.innerText);

Output:

JavaScript textContent Demo!

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.

Setting textContent for a node


Besides reading textContent , you can also use the textContent property to set the text
for a node:

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:

let note = document.getElementById('note');


note.textContent = 'This is a note';

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:

element.innerHTML = 'new content';


element.innerHTML;

Reading the innerHTML property of an element


To get the HTML markup contained within an element, you use the following syntax:

let content = element.innerHTML;

When you read the innerHTML of an element, the web browser has to serialize the HTML
fragment of the element’s descendants.

1) Simple JavaScript innerHTML example


Suppose that you have the following markup:

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

let menu = document.getElementById('menu');


console.log(menu.innerHTML);

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>

2) Examining the current HTML source


The innerHTML property returns the current HTML source of the document, including all
changes that have been made since the page was loaded.
See the following example:

<!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');

// create new li element


let li = document.createElement('li');
li.textContent = 'About Us';
// add it to the ul element
menu.appendChild(li);

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.

Setting the innerHTML property of an element


To set the value of innerHTML property, you use this syntax:

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>

And the app.js file looks like this:

const scriptHTML = `<script>alert("Alert from innerHTML");</script>`;


const main = document.getElementById('main');

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:

const main = document.getElementById('main');

const externalHTML = `<img src='1' onerror='alert("Error loading image")'>`;

// shows the alert


main.innerHTML = externalHTML;

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 div = document.querySelector('.container');

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:

let div = document.querySelector('.container');


div.innerHTML += '<p>JS DOM</p>';

Using innerHTML is cleaner and shorter when you want to add attributes to the element:

let div = document.querySelector('.container');


div.innerHTML += '<p class="note">JS DOM</p>';

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 .

#2) createElement is more secure

JavaScript innerHTML vs createElement 1


As mentioned in the innerHTML tutorial, you should use it only when the data comes
from a trusted source like a database.
If you set the contents that you have no control over to the innerHTML, the malicious
code may be injected and executed.

#3) Using DocumentFragment for composing DOM


Nodes
Assuming that you have a list of elements and you need in each iteration:

let div = document.querySelector('.container');

for (let i = 0; i < 1000; i++) {


let p = document.createElement('p');
p.textContent = `Paragraph ${i}`;
div.appendChild(p);
}

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:

let div = document.querySelector('.container');

// compose DOM nodes

let fragment = document.createDocumentFragment();


for (let i = 0; i < 1000; i++) {
let p = document.createElement('p');
p.textContent = `Paragraph ${i}`;
fragment.appendChild(p);
}

// append the fragment 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.

JavaScript innerHTML vs createElement 2


A document fragment does not link to the active DOM tree, therefore, it doesn’t incur
any performance.

JavaScript innerHTML vs createElement 3


JavaScript DocumentFragment
The DocumentFragment interface is a lightweight version of the Document that stores a
piece of document structure like a standard document. However, a DocumentFragment isn’t
part of the active DOM tree.

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:

let fragment = new DocumentFragment();

Or you can use the createDocumentFragment() method of the Document object:

let fragment = document.createDocumentFragment();

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 :

let languages = ['JS', 'TypeScript', 'Elm', 'Dart','Scala'];

let langEl = document.querySelector('#language')

let fragment = new DocumentFragment();


languages.forEach((language) => {
let li = document.createElement('li');
li.innerHTML = language;
fragment.appendChild(li);
})

langEl.appendChild(fragment);

How it works:

JavaScript DocumentFragment 2
First, select the <ul> element by its id using the querySelector() method.

Second, create a new document fragment.

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.

Finally, append the document fragment to the <ul> element.

Put it all together:

<!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'];

let langEl = document.querySelector('#language');


let fragment = new DocumentFragment();

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:

<input type="text" id="username">

The web browser will generate an HTMLInputElement object.

The input element has two attributes:

The type attribute with the value text .

The id attribute with the value username .

The generated HTMLInputElement object will have the corresponding properties:

The input.type with the value text .

The input.id with the value username .

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-property mapping is not always one-to-one. For example:

<input type="text" id="username" secured="true">

In this example, the secured is a non-standard attribute:

Working with Attributes 1


let input = document.querySelector('#username');
console.log(input.secured);// undefined

Attribute methods
To access both standard and non-standard attributes, you use the following methods:

element.getAttribute(name) – get the attribute value

element.setAttribute(name, value) – set the value for the attribute

element.hasAttribute(name) – check for the existence of an attribute

element.removeAttribute(name) – remove the attribute

element.attributes
The element.attributes property provides a live collection of attributes available on a
specific element. For example:

let input = document.querySelector('#username');

for(let attr of input.attributes) {


console.log(`${attr.name} = ${attr.value}` )
}

Output:

type = text
id = username
secure = true

Note that element.attributes is a NamedNodeMap , not an Array , therefore, it has no Array’s


methods.

Attribute-property synchronization
When a standard attribute changes, the corresponding property is auto-updated with
some exceptions and vice versa.

Working with Attributes 2


Suppose that you have the following input element:

<input type="text" id="username" tabindex="1">

The following example illustrates the change of the tabindex attribute is propagated to
the tabIndex property and vice versa:

let input = document.querySelector('#username');

// attribute -> property


input.setAttribute('tabindex', 2);
console.log(input.tabIndex); // 2
// property -> attribute
input.tabIndex = 3;
console.log(input.getAttribute('tabIndex')); // 3

The following example shows when the value attribute changes, it reflects in
the value property, but not the other way around:

let input = document.querySelector('#username');

// attribute -> property: OK


input.setAttribute('value','guest');
console.log(input.value); // guest

// property -> attribute: doesn't change

input.value = 'admin';
console.log(input.getAttribute('value'));// guest

DOM properties are typed


The value of an attribute is always a string. However, when the attribute is converted to
the property of a DOM object, the property value can be a string, a boolean, an object,
etc.
The following checkbox element has the checked attribute. When the checked attribute is
converted to the property, it is a boolean value:

Working with Attributes 3


<input type="checkbox" id="chkAccept" checked> Accept

let checkbox = document.querySelector('#chkAccept');


console.log(checkbox.checked); // true

The following shows an input element with the style attribute:

<input type="password" id="password" style="color:red;with:100%">

The style attribute is a string while the style property is an object:

let input = document.querySelector('#password');

let styleAttr = input.getAttribute('style');


console.log(styleAttr);

console.dir(input.style);

Output:

[object CSSStyleDeclaration]

The data-* attributes


If you want to add a custom attribute to an element, you should prefix it with
the data- e.g., data-secured because all attributes start with data- are reserved for the
developer’s uses.
To access data-* attributes, you can use the dataset property. For example, we have
the following div element with custom attributes:

<div id="main" data-progress="pending" data-value="10%"></div>

The following shows how to access the data-* attributes via the dataset property:

Working with Attributes 4


let bar = document.querySelector('#main');
console.log(bar.dataset);

Output:

[object DOMStringMap] {
progress: "pending",
value: "10%"
}

Summary
Attributes are specified in HTML elements.

Properties are specified DOM objects.

Attributes are converted to properties respectively.

Use the element.attributes property to access standard and custom attributes of an


element.

Use the element.dataset property to access the data-* attributes.

Working with Attributes 5


JavaScript Style
Setting inline styles
To set the inline style of an element, you use the style property of that element:

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';

The following table shows the common CSS properties:

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';

Or you can use the setAttribute() method:

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:

function css(e, styles) {


for (const property in styles)
e.style[property] = styles[property];
}

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:

First, select the paragraph element whose id is content by using


the querySelector() method.

Then, set the color and font-weight properties of the paragraph by setting
the color and fontWeight properties of the style object.

Getting inline styles


The style property returns the inline styles of an element. It is not very useful in
practice because the style property doesn’t return the rules that come from elsewhere
e.g., styles from an external style sheet.
To get all styles applied to an element, you should use
the window.getComputedStyle() method.

Summary

JavaScript Style 5
Use the properties of element.style object to set the inline CSS properties for the
HTML element.

For further exploration and learning, please visit the following


links:
getComputedStyle() – return the computed style of an element.

className property – return a list of space-separated CSS classes.

classList property – manipulate CSS classes of an 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.

Suppose you have a button with the id btn :

<button id="btn">Click Me!</button>

To define the code that will be executed when the button is clicked, you need to register
an event handler using the addEventListener() method:

let btn = document.querySelector('#btn');

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.

Then, define a function called display() as an event handler.

Finally, register an event handler using the addEventListener() so that when users
click the button, the display() function will be executed.

Working with Events 1


A shorter way to register an event handler is to place all code in an anonymous
function, like this:

let btn = document.querySelector('#btn');

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

2. div with the id container

3. body

Working with Events 2


4. html

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

Working with Events 3


4. div with the id container

5. button

The following picture illustrates the event capturing effect:

DOM Level 2 Event flow


DOM level 2 events specify that event flow has three phases:

First, event capturing occurs, which provides the opportunity to intercept the event.

Then, the actual target receives 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:

Working with Events 4


Event object
When the event occurs, the web browser passed an Event object to the event handler:

let btn = document.querySelector('#btn');

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

Working with Events 5


cancelable true if the default behavior of the event can be canceled

currentTarget the current element on which the event is firing

defaultPrevented return true if the preventDefault() has been called.

detail more informatio nabout the event

eventPhase 1 for capturing phase, 2 for target, 3 for bubbling

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

type the type of event that was fired

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:

<a href="https://www.xyz.net/">JS Tutorial</a>

However, you can prevent this behavior by using the preventDefault() method of
the event object:

let link = document.querySelector('a');

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 .

Working with Events 6


stopPropagation()
The stopPropagation() method immediately stops the flow of an event through the DOM
tree. However, it does not stop the browers default behavior.
See the following example:

let btn = document.querySelector('#btn');

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.

Here is a list of some common events:


Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

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.

Working with Events 7


DOM Level 2 Event specifies that the event flow has three phases: event bubbling,
the event occurs at the exact element, and event capturing.

Use addEventListener() to register an event that connects an event to an event


listener

The event object is accessible only within the event listener.

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.

Working with Events 8

You might also like