CS202 — Final Term Summary (Lectures 23–88)
📘 Lecture 23 — HTML Head
📖 Overview: This lecture covers the HTML
<head>element and its role in storing metadata about web documents. It explains how to properly structure document metadata including title, styles, scripts, and character encoding, and introduces HTML entities, symbols, character encoding standards, and URL encoding for proper web page functionality.
🗂️ Topics Covered
The lecture covers the HTML <head> element and its child elements including <title>, <style>, <link>, <meta>, <script>, and <base>. It also explains how to omit <html>, <body>, and <head> tags in HTML5. Additional topics include HTML entities and non-breaking spaces, combining diacritical marks, HTML symbol entities (mathematical symbols and Greek letters), character encoding standards (ASCII, ANSI, ISO-8859-1, UTF-8), and URL structure with encoding rules.
📝 Lecture Summary
The HTML <head> Element
The <head> element is a container for Metadata (data about data). HTML metadata is data about the HTML document and is not displayed. Metadata typically defines document title, styles, links, scripts, and other meta information. The following tags describe metadata: <title>, <style>, <meta>, <link>, <script>, and <base>.
🔑 Definition — Metadata: Data about the HTML document that is not displayed but defines document properties like title, styles, and scripts.
Omitting <html> and <body>
In the HTML5 standard, the <html>, <body>, and <head> tags can be omitted. The <html> element is the document root and is the recommended place for specifying the page language using the lang attribute:
<!DOCTYPE html>
<html lang="en-US">
Declaring a language is important for accessibility applications (screen readers) and search engines. Omitting <html> and <body> can crash badly written DOM and XML software. Omitting <body> can produce errors in older browsers (IE9).
Omitting <head>
In HTML5, the <head> tag can also be omitted. By default, browsers will add all elements before <body> to a default <head> element. You can reduce the complexity of HTML by omitting the <head> tag.
The HTML <title> Element
The <title> element defines the title of the document and is required in all HTML/XHTML documents. The <title> element:
- Defines a title in the browser toolbar
- Provides a title for the page when it is added to favorites
- Displays a title for the page in search engine results
The HTML <style> Element
The <style> element is used to define style information for an HTML document. Inside the <style> element you specify how HTML elements should render in a browser:
<style>
body {background-color:yellow;}
p {color:blue;}
</style>
The HTML <link> Element
The <link> element defines the page relationship to an external resource. It is most often used to link to style sheets:
<link rel="stylesheet" href="mystyle.css">
<meta> Element
The <meta> element is used to specify page description, keywords, author, and other metadata. Metadata is used by browsers (how to display content), by search engines (keywords), and other web services.
Define keywords for search engines:
<meta name="keywords" content="HTML, CSS, XML, XHTML, JavaScript">
Define a description of your web page:
<meta name="description" content="Free Web tutorials on HTML and CSS">
Define the character set:
<meta charset="UTF-8">
Define the author of a page:
<meta name="author" content="Hege Refsnes">
Refresh document every 30 seconds:
<meta http-equiv="refresh" content="30">
The HTML <script> Element
The <script> element is used to define client-side JavaScripts. Example:
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello JavaScript!";
}
</script>
The HTML <base> Element
The <base> element specifies the base URL and base target for all relative URLs in a page:
<base href="http://www.google.com/images/" target="_blank">
HTML Entities
Some characters are reserved in HTML. If you use the less than (<) or greater than (>) signs in your text, the browser might mix them with tags. Character entities are used to display reserved characters in HTML. A character entity looks like this:
&entity_name;
OR
&#entity_number;
To display a less than (<) sign we must write: < or <
🔑 Definition — Character entities: Codes used to display reserved characters in HTML that might otherwise be interpreted as HTML tags.
Non Breaking Space
A common character entity used in HTML is the non breaking space ( ). Browsers will always truncate spaces in HTML pages. If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the character entity.
Combining Diacritical Marks
A diacritical mark is a "glyph" added to a letter. Some diacritical marks, like grave (`) and acute (´) are called accents. Diacritical marks can appear both above and below a letter, inside a letter, and between two letters. Diacritical marks can be used in combination with alphanumeric characters to produce a character that is not present in the character set (encoding) used in the page.
HTML Symbol Entities
HTML entities were described in the previous chapter. Many mathematical, technical, and currency symbols are not present on a normal keyboard. To add these symbols to an HTML page, you can use an HTML entity name. If no entity name exists, you can use an entity number; a decimal (or hexadecimal) reference.
Example:
<p>I will display €</p>
<p>I will display €</p>
<p>I will display €</p>
Result: I will display € (all three methods produce the same euro symbol)
💡 Why this matters: HTML symbol entities allow you to display mathematical, technical, and currency symbols that are not available on standard keyboards, ensuring proper rendering across all browsers.
Some Mathematical Symbols Supported by HTML include: ∀ (FOR ALL), ∂ (PARTIAL DIFFERENTIAL), ∃ (THERE EXISTS), ∅ (EMPTY SETS), ∇ (NABLA), ∈ (ELEMENT OF), ∉ (NOT AN ELEMENT OF), ∋ (CONTAINS AS MEMBER), ∏ (N-ARY PRODUCT), ∑ (N-ARY SUMMATION).
Some Greek Letters Supported by HTML include: Α (ALPHA), Β (BETA), Γ (GAMMA), Δ (DELTA), Ε (EPSILON), Ζ (ZETA).
Character Encoding
ASCII was the first character encoding standard (also called character set). It defines 127 different alphanumeric characters that could be used on the internet. ASCII supported numbers (0-9), English letters (A-Z), and some special characters like ! $ + - ( ) @ < >.
ANSI (Windows-1252) was the original Windows character set. It supported 256 different character codes. ISO-8859-1 was the default character set for HTML 4. It also supported 256 different character codes. Because ANSI and ISO were limited, the default character encoding was changed to UTF-8 in HTML5.
UTF-8 (Unicode) covers almost all of the characters and symbols in the world.
The HTML charset Attribute: To display an HTML page correctly, a web browser must know the character set used in the page. This is specified in the <meta> tag.
For HTML4: <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
For HTML5: <meta charset="UTF-8">
The ASCII Character Set:
- Uses values from 0 to 31 (and 127) for control characters
- Uses values from 32 to 126 for letters, digits, and symbols
- Does not use values from 128 to 255
The ANSI Character Set (Windows-1252):
- Identical to ASCII for values 0 to 127
- Has proprietary characters for values 128 to 159
- Identical to UTF-8 for values 160 to 255
The ISO-8859-1 Character Set:
- Identical to ASCII for values 0 to 127
- Does not use values 128 to 159
- Identical to UTF-8 for values 160 to 255
The UTF-8 Character Set:
- Identical to ASCII for values 0 to 127
- Does not use values 128 to 159
- Identical to both ANSI and 8859-1 for values 160 to 255
- Continues from value 256 with more than 10,000 different characters
URL Structure
A URL (Uniform Resource Locator) is another word for a web address. A URL can be composed of words (google.com) or an Internet Protocol (IP) address (192.68.20.50). Web browsers request pages from web servers by using a URL.
A URL like http://www.htmllectures.com/html/default.asp follows this syntax:
scheme://host.domain:port/path/filename
- scheme - defines the type of Internet service (most common is http)
- host - defines the domain host (default host for http is www)
- domain - defines the Internet domain name (google.com)
- port - defines the port number at the host (default for http is 80)
- path - defines a path at the server (If omitted: the root directory of the site)
- filename - defines the name of a document or resource
Common URL Schemes:
- http - HyperText Transfer Protocol - Common web pages. Not encrypted
- https - Secure HyperText Transfer Protocol - Secure web pages. Encrypted
- ftp - File Transfer Protocol - Downloading or uploading files
- file - A file on your computer
URL Encoding
URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into ASCII. URL encoding converts characters into a format that can be transmitted over the Internet.
URL encoding replaces non-ASCII characters with a "%" followed by hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign, or %20.
⭐ Key Takeaways
The <head> element is essential for storing metadata like title, styles, scripts, and character encoding information that browsers and search engines use to understand and display your web page correctly. HTML entities and symbol entities allow you to display reserved characters and special symbols that are not available on standard keyboards using &entity_name; or &#entity_number; syntax. Character encoding standards have evolved from ASCII (127 characters) through ANSI and ISO-8859-1 (256 characters) to UTF-8 which supports over 10,000 characters and is the default for HTML5. URLs follow the syntax scheme://host.domain:port/path/filename and must be URL-encoded to replace non-ASCII characters with % followed by hexadecimal digits for proper transmission over the Internet.
🧠 Quick Revision Questions
- What are the six tags that describe metadata in the HTML
<head>element? - How do you display a less than sign (<) in HTML without it being interpreted as a tag?
- What is the difference between ASCII, ANSI, ISO-8859-1, and UTF-8 character sets in terms of the number of characters they support?
- What is the correct HTML5 syntax for specifying the character set in a webpage?
- What are the components of a URL and what does URL encoding do to non-ASCII characters?
📘 Lecture 27 — HTML and XHTML
📖 Overview: This lecture introduces XHTML (Extensible HyperText Markup Language) as a stricter, XML-based version of HTML. It explains why XHTML was developed to address problems with "bad" HTML code, covers the key differences between HTML and XHTML, and provides guidelines for converting HTML to XHTML. The lecture also introduces CSS (Cascading Style Sheets), including its syntax, selectors, and methods of insertion into HTML documents.
🗂️ Topics Covered
The lecture covers the definition and purpose of XHTML, reasons for its development due to browser inconsistencies and poorly written HTML, the most important differences from HTML including document structure rules, element and attribute requirements (proper nesting, closing, lowercase, quoting), mandatory DOCTYPE and namespace declarations, and a step-by-step guide for converting from HTML to XHTML. It then transitions to CSS, covering its definition as a style sheet language, basic syntax with selectors and declarations, CSS comments, various CSS selectors (classes, IDs, elements, combinators, attributes), and three methods of inserting CSS (external, internal, and inline style sheets).
📝 Lecture Summary
What Is XHTML?
XHTML stands for Extensible HyperText Markup Language. It is almost identical to HTML but is stricter and defined as an XML application. XHTML is supported by all major browsers.
Why XHTML?
Many web pages contain "bad" HTML that, while functional, does not follow proper rules. With the variety of browser technologies, including mobile phones and small devices that lack resources to interpret incorrect markup, a stricter standard was needed. XML requires documents to be "well-formed," so by combining the strengths of HTML and XML, XHTML was developed. XHTML is essentially HTML redesigned as XML.
🔑 Definition — XHTML: A stricter, XML-based version of HTML that requires documents to be well-formed and properly structured.
The Most Important Differences from HTML: Document Structure
- The XHTML DOCTYPE is mandatory
- The xmlns attribute in the
<html>element is mandatory - The elements
<html>,<head>,<title>, and<body>are all mandatory
XHTML Elements and Attributes
XHTML requires that elements be properly nested, always closed, and written in lowercase. Documents must have one root element. Attribute names must be in lowercase, attribute values must be quoted, and attribute minimization is forbidden.
📌 Example (Proper Nesting):
Incorrect: <b><i>This text is bold and italic</b></i>
Correct: <b><i>This text is bold and italic</i></b>
📌 Example (Elements Must Be Closed):
Incorrect: <p>hi, everyone <p>How are you?
Correct: <p>hi, everyone</p> <p>How are you?</p>
📌 Example (Empty Elements Must Also Be Closed):
A break: <br />
A horizontal rule: <hr />
An image: <img src="happy.gif" alt="Happy face" />
📌 Example (Lowercase Elements):
Incorrect: <BODY> <P>Hi, Everyone</P> </BODY>
Correct: <body> <p>Hi, Everyone</p> </body>
< !DOCTYPE .... > Is Mandatory
An XHTML document must have an XHTML DOCTYPE declaration. The <html>, <head>, <title>, and <body> elements must also be present, and the xmlns attribute in <html> must specify the XML namespace for the document.
How to Convert from HTML to XHTML
- Add an XHTML
<!DOCTYPE>to the first line of every page - Add an xmlns attribute to the html element of every page
- Change all element names to lowercase
- Close all empty elements
- Change all attribute names to lowercase
- Quote all attribute values
💡 Why this matters: Following these conversion steps ensures your web pages are valid XHTML and will render correctly across all modern browsers and devices.
CSS (Cascading Style Sheets)
CSS is a style sheet language used for describing the presentation of a document written in a markup language. CSS defines how HTML elements are to be displayed. CSS styles were added to HTML 4.0 to solve presentation problems. Styles are normally stored in an external .css file, allowing you to change the style of an entire site by editing just that one file.
🔑 Definition — CSS (Cascading Style Sheets): A style sheet language used for describing the presentation of a document written in a markup language, separating content from design.
CSS Syntax
CSS syntax consists of a selector and a declaration block. The selector points to the HTML element you want to style, and the declaration block contains one or more declarations separated by semicolons. Each declaration has a property name and a value, separated by a colon.
📌 Example (Basic CSS Syntax):
h1 {
color: blue;
font-size: 12px;
}
h1is the selectorcolor: blue;andfont-size: 12px;are declarationscolorandfont-sizeare property namesblueand12pxare values
CSS comments start with /* and end with */.
30- CSS Selectors
CSS selectors are patterns used to select the element(s) you want to style.
📌 Examples of Important CSS Selectors:
.class— selects all elements withclass="intro"(CSS1)#id— selects the element withid="firstname"(CSS1)element— selects all<p>elements (CSS1)element>element— selects all<p>elements where the parent is a<div>element (CSS2)element1~element2— selects every<ul>element preceded by a<p>element (CSS3)[attribute]— selects all elements with a target attribute (CSS2)[attribute=value]— selects all elements withtarget="_blank"(CSS2)[attribute|=value]— selects all elements with a lang attribute value starting with "en" (CSS2)
31- CSS Insertion (How to Insert CSS in HTML File)
CSS can be inserted into HTML documents using three methods: external style sheets, internal style sheets, or inline styles.
External Style Sheet
Each page includes a reference to the external CSS file using the <link> element inside the <head> section.
📌 Example:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Internal Style Sheet
Internal styles are defined within the <style> element inside the <head> section of an HTML page, used when a single page has a unique style.
📌 Example:
<head>
<style>
body {background-color: linen;}
h1 {color: maroon; margin-left: 40px;}
</style>
</head>
⭐ Key Takeaways
XHTML is a stricter version of HTML defined as an XML application, requiring proper document structure with mandatory DOCTYPE, namespace, and core elements. All XHTML elements must be properly nested, closed (including empty elements with a trailing slash), and in lowercase, while attributes must be lowercase, quoted, and never minimized. CSS is a style sheet language used to describe presentation, separating content from design, with syntax consisting of selectors and declaration blocks. CSS can be applied via external files (linked in <head>), internal <style> blocks, or inline styles, with selectors ranging from simple (class, ID, element) to complex (combinators, attribute selectors) across CSS1, CSS2, and CSS3 versions.
🧠 Quick Revision Questions
- What does XHTML stand for, and how is it different from HTML?
- List three mandatory elements that must be present in every XHTML document.
- Why must empty elements like
<br>be written with a trailing slash in XHTML? - What is the CSS syntax structure, and what does each part represent?
- Name two CSS selectors and give an example of what each one selects.
📘 Lecture 33 — 33a- CSS Text and Fonts
📖 Overview: This lecture covers CSS styling properties for text and fonts, including text color, transformation, indentation, and comprehensive font-family, style, and size control. It extends into practical styling applications for links, lists, tables, and the CSS box model, which are fundamental for web design and layout.
🗂️ Topics Covered
This lecture explains text properties like color, transformation, and indentation; font properties including family, style, and size with absolute and relative units; link styling with states and decorations; list styling with markers and images; table styling with borders, alignment, padding, and colors; the CSS box model with content, padding, border, and margin; and border and outline properties.
📝 Lecture Summary
CSS Text and Fonts
The CSS color property is used to set the color of the text. With CSS, a color is most often specified by a HEX value like "#ff0000", an RGB value like "rgb(255,0,0)", or a color name like "red". The default color for a page is defined in the body selector.
🔑 Definition — Text Transformation: The text-transform property specifies uppercase and lowercase letters in a text. It can turn everything into uppercase or lowercase, or capitalize the first letter of each word.
📌 Example:
p.uppercase {text-transform: uppercase;}p.lowercase {text-transform: lowercase;}p.capitalize {text-transform: capitalize;}
🔑 Definition — Text Indentation: The text-indent property specifies the indentation of the first line of a text or paragraph.
🔑 Definition — CSS Font: CSS font properties define the font family, boldness, size, and the style of a text.
🔑 Definition — CSS Font Families: There are two types of font family names: generic family (a group of font families with a similar look like "Serif" or "Monospace") and font family (a specific font family like "Times New Roman" or "Arial").
📌 The table shows:
- Serif (e.g., Times New Roman, Georgia): have small lines at the ends on some characters
- Sans-serif (e.g., Arial, Verdana): "Sans" means without, these fonts do not have the lines at the ends of characters
- Monospace (e.g., Courier New, Lucida Console): all characters have the same width
🔑 Definition — Font Family: The font-family property should hold several font names as a "fallback" system. If the browser does not support the first font, it tries the next font. If the name of a font family is more than one word, it must be in quotation marks.
📌 Example: p { font-family: "Times New Roman", Times, serif; }
🔑 Definition — CSS Font Style: The font-style property is mostly used to specify italic text, with three values: normal (text shown normally), italic (text shown in italics), and oblique (text is "leaning", very similar to italic but less supported).
📌 Example:
p.normal {font-style: normal;}p.italic {font-style: italic;}p.oblique {font-style: oblique;}
🔑 Definition — Font Size: The font-size property sets the size of the text. Being able to manage text size is important in web design. The font-size value can be absolute or relative. Absolute size sets the text to a specified size and does not allow a user to change the text size in all browsers (bad for accessibility). Relative size sets the size relative to surrounding elements and allows a user to change the text size in browsers.
📌 Set Font Size with Pixels: Setting the text size with pixels gives you full control over the text size. Example:
h1 {font-size: 40px;}h2 {font-size: 30px;}p {font-size: 14px;}
📐 Formula: pixels/16 = em — 1em is equal to the current font size. The default text size in browsers is 16px. 📌 Example: In CSS, the em size unit is recommended by the W3C to allow users to resize text.
📌 Use a Combination of Percent and Em: The solution that works in all browsers is to set a default font-size in percent for the <body> element.
Example:
body {font-size: 100%;}h1 {font-size: 2.5em;}h2 {font-size: 1.875em;}p {font-size: 0.875em;}
CSS Links
Styling Links: Links can be styled with any CSS property. Below example is used to give a specific color to all the link text in a file.
📌 Example: a {color: #FF0000;}
🔑 Definition — The four link states are:
a:link- a normal, unvisited linka:visited- a link the user has visiteda:hover- a link when the user mouses over ita:active- a link the moment it is clicked
🔑 Definition — Text Decoration: This property is mostly used to remove underlines from links. 📌 Example:
a:link {text-decoration: none;}– to remove the link decorationa:visited {text-decoration: none;}– to remove the visited link's decorationa:hover {text-decoration: underline;}– underline the link text while mouse overa:active {text-decoration: underline;}– underline the active link
🔑 Definition — Background Color: The background-color property specifies the background color for links.
📌 Example: a:link {background-color: #B2FF99;}
CSS Lists
In CSS, the list properties allow you to set different list item markers for ordered and unordered lists, and set an image as the list item marker.
🔑 Definition — Lists in HTML: There are two types of lists: unordered lists (<ul>) where list items are marked with bullets, and ordered lists (<ol>) where list items are marked with numbers or letters. The type of list item marker is specified with the list-style-type property.
📌 Example:
ul.a {list-style-type: circle;}ul.b {list-style-type: square;}ol.c { list-style-type: upper-roman;}ol.d {list-style-type: lower-alpha;}
🔑 Definition — An Image as the List Item Marker: To specify an image as the list item marker, use the list-style-image property.
📌 Example: ul { list-style-image: url('sqpurple.gif');}
🔑 Definition — List - Shorthand property: The list-style property is a shorthand property used to set all the list properties in one declaration.
📌 Example: ul {list-style: square inside url("sqpurple.gif");}
CSS Tables
The look of an HTML table can be greatly improved with CSS.
🔑 Definition — Table Borders: To specify table borders in CSS, use the border property.
📌 Example: table, th, td { border: 1px solid black;}
🔑 Definition — Double Borders: Notice that the table in the example above has double borders because both the table and the <th>/<td> elements have separate borders. To display a single border for the table, use the border-collapse property.
📌 Example: table {border-collapse: collapse;} table, th, td {border: 1px solid black;}
🔑 Definition — Table Width and Height: Width and height of a table is defined by the width and height properties.
📌 Example: table {width: 100%;} th {height: 50px;}
🔑 Definition — Horizontal Text Alignment: The text-align property sets the horizontal alignment (left, right, or center). By default, text in <th> elements are center-aligned and text in <td> elements are left-aligned.
📌 Example: th {text-align: left;}
🔑 Definition — Vertical Text Alignment: The vertical-align property sets the vertical alignment (top, bottom, or middle). By default, the vertical alignment of text in a table is middle (for both <th> and <td> elements).
📌 Example: td { height: 50px; vertical-align: bottom;}
🔑 Definition — Table Padding: To control the space between the border and content in a table, use the padding property on <td> and <th> elements.
📌 Example: td {padding: 15px;}
🔑 Definition — Table Color: We can specify using CSS the color of the borders, and the text and background color of <th> elements.
📌 Example: table, td, th {border: 1px solid green;} th {background-color: green; color: white;}
CSS Box Model
All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout. The CSS box model is essentially a box that wraps around HTML elements and consists of: margins, borders, padding, and the actual content. The box model allows us to add a border around elements and to define space between elements.
🔑 Definition — The different parts of the box model:
- Content - The content of the box, where text and images appear
- Padding - Clears an area around the content. The padding is transparent
- Border - A border that goes around the padding and content
- Margin - Clears an area outside the border. The margin is transparent
📌 Example: div {width: 300px; padding: 25px; border: 25px solid navy; margin: 25px;}
🔑 Definition — Width and Height of an Element: In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.
📌 Example: To style a <div> element to have a total width of 350px: div {width: 320px; padding: 10px; border: 5px solid gray; margin: 0; }
💡 Why this matters: The total width of an element is calculated by adding the width, padding, border, and margin. Without understanding the box model, you cannot predict the actual space an element occupies on the page.
CSS Border and Outline
🔑 Definition — Border Style: The border-style property specifies what kind of border to display. Common values include solid, dotted, dashed, double, groove, ridge, inset, and outset.
🔑 Definition — Border Width: The border-width property sets the width of the border in pixels or using pre-defined values: thin, medium, or thick. Note: The "border-width" property does not work if used alone; use the "border-style" property to set the borders first.
📌 Example:
p.one {border-style: solid; border-width: 5px;}p.two { border-style: solid; border-width: medium;}
🔑 Definition — Border Color: The border-color property sets the color of the border. Color can be set by name (like "red"), RGB (like "rgb(255,0,0)"), or Hex (like "#ff0000"). If the border color is not set, it is inherited from the color property of the element.
📌 Example:
p.one { border-style: solid; border-color: red; }p.two {border-style: solid; border-color: #98bf21; }
🔑 Definition — Border - Individual sides: In CSS, it is possible to specify different borders for different sides.
📌 Example: p { border-top-style: dotted; border-right-style: solid; border-bottom-style: dotted; border-left-style: solid;}
🔑 Definition — Border - Shorthand property: The border property is shorthand for the individual border properties: border-width, border-style (required), and border-color.
🔑 Definition — CSS Outlines: An outline is a line drawn around elements (outside the borders) to make the element "stand out". The outline properties specify the style, color, and width of an outline. The outline is different from the border property because the outline is not a part of an element's dimensions; the element's total width and height is not affected by the width of the outline.
📌 Example: p {border: 1px solid red; outline: green dotted thick; }
⭐ Key Takeaways
For the exam, you must know the four CSS text properties (color, transformation, indentation, and font properties) with their correct syntax. You need to memorize the four link states (link, visited, hover, active) and how to style them using text-decoration and background-color. For tables, remember that border-collapse removes double borders, and that text-align and vertical-align control alignment. The CSS box model is critical: the total width of an element equals width + padding + border + margin. Finally, understand that outlines differ from borders as they do not affect element dimensions.
🧠 Quick Revision Questions
- What are the four ways to specify color in CSS text, and provide one example for each method?
- Explain the difference between absolute and relative font sizing, and give an example of using em units.
- What are the four link states in CSS and the correct order in which they should be defined?
- How do you remove double borders in a CSS table, and what is the default vertical alignment of text in table cells?
- What are the four components of the CSS box model, and how does the outline property differ from the border property in terms of element dimensions?
📘 Lecture 40 — CSS Margin and Padding
📖 Overview: This lecture covers the core CSS properties for controlling spacing around and within HTML elements. It explains how margins create transparent space outside element borders, while padding creates space between the border and content, and then expands into related topics like dimensions, alignment, positioning, floats, and combinators for complete layout control.
🗂️ Topics Covered
This lecture begins with CSS margin properties including individual sides and shorthand notation, then moves to CSS padding with similar individual and shorthand approaches. It continues with CSS dimension properties for controlling height and width, CSS align techniques including center, left/right alignment using margin, position, and float properties. The lecture also covers CSS display properties (block vs inline elements, hiding elements), CSS positioning methods (static, fixed, relative, absolute), overlapping elements with z-index, CSS float and clear properties, and concludes with CSS combinators (descendant, child, adjacent sibling, and general sibling selectors).
📝 Lecture Summary
CSS Margin
The CSS margin properties define the space around elements. The margin clears an area around an element (outside the border). The margin does not have a background color, and is completely transparent. The top, right, bottom, and left margin can be changed independently using separate properties. A shorthand margin property can also be used to change all margins at once.
Possible values for margin properties include: auto (the browser calculates a margin), length (specifies a margin in px, pt, cm, etc., default value is 0px), % (specifies a margin in percent of the width of the containing element), and inherit (specifies that the margin should be inherited from the parent element).
🔑 Definition — Margin: The CSS property that defines the transparent space around an element, outside its border.
📐 Formula: margin: [top] [right] [bottom] [left] → The shorthand property specifying margins in clockwise order (top, right, bottom, left).
📌 Example: For a paragraph element, individual margins can be set: p { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; }. The shorthand p { margin: 100px 50px; } sets top/bottom to 100px and right/left to 50px. The four-value shorthand p { margin: 25px 50px 75px 100px; } sets top=25px, right=50px, bottom=75px, left=100px.
CSS Padding
The CSS padding properties define the space between the element border and the element content. It clears an area around the content (inside the border) of an element. The padding is affected by the background color of the element. The top, right, bottom, and left padding can be changed independently using separate properties. A shorthand padding property can also be used to change all paddings at once.
🔑 Definition — Padding: The CSS property that defines the space between an element's border and its content, which is affected by the element's background color.
📐 Formula: padding: [top] [right] [bottom] [left] → The shorthand property specifying all padding values in clockwise order.
📌 Example: Individual padding: p { padding-top: 25px; padding-right: 50px; padding-bottom: 25px; padding-left: 50px; }. Shorthand p { padding: 25px 50px; } sets top/bottom to 25px and right/left to 50px. One-value shorthand padding: 25px sets all four paddings to 25px. Three-value shorthand padding: 25px 50px 75px sets top=25px, right/left=50px, bottom=75px.
💡 Why this matters: Understanding the difference between margin (outside, transparent) and padding (inside, colored with background) is fundamental for creating proper spacing in web layouts.
CSS Dimension
The CSS dimension properties allow you to control the height and width of an element.
📌 Example: img { width: 200px; } sets an image width to 200px. p { min-height: 100px; background-color: yellow; } ensures a paragraph is at least 100px tall.
CSS Align
A block element is an element that takes up the full width available and has a line break before and after it. Examples include <h1>, <p>, and <div>.
Center Aligning Using the margin Property: Block elements can be center-aligned by setting the left and right margins to "auto". This specifies that they should split the available margin equally.
📌 Example: .center { margin-left: auto; margin-right: auto; width: 70%; background-color: #b0e0e6; }
Left and Right Aligning Using the position Property: One method of aligning elements is to use absolute positioning.
📌 Example: .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; }
Cross Browser Compatibility Issues: When aligning elements, it is always a good idea to predefine margin and padding for the <body> element to avoid visual differences in different browsers. IE8 and earlier, when using the position property without a !DOCTYPE declaration, will add a 17px margin on the right side.
📌 Example: body { margin: 0; padding: 0; } .container { position: relative; width: 100%;} .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; }
Left and Right Aligning Using the float Property: One method of aligning elements is to use the float property.
📌 Example: .right { float: right; width: 300px; background-color: #b0e0e6; }
💡 Why this matters: Cross-browser compatibility requires proper DOCTYPE declaration and resetting body margins/padding when using absolute positioning.
CSS Display
The display property specifies if/how an element is displayed, and the visibility property specifies if an element should be visible or hidden.
Hiding an Element - display: none or visibility: hidden: These two methods produce different results. Visibility: hidden hides an element, but it will still take up the same space as before and affect the layout. Display: none hides an element completely, and it will not take up any space.
📌 Example: h1.hidden {visibility: hidden;} hides the heading but keeps its space. h1.hidden {display: none;} hides the heading and removes its space from the layout.
Block and Inline Elements: A block element takes up the full width available and has a line break before and after it (e.g., <h1>, <p>, <li>, <div>). An inline element only takes up as much width as necessary and does not force line breaks (e.g., <span>, <a>).
Changing How an Element is displayed: Changing an inline element to a block element, or vice versa, can be useful for making the page look a specific way.
📌 Example: li {display: inline;} displays list items as inline elements.
CSS Positioning & Floats
The CSS positioning properties allow you to position an element. Elements can be positioned using the top, bottom, left, and right properties, but these will not work unless the position property is set first.
There are four different positioning methods:
1- Static Positioning: HTML elements are positioned static by default. A static positioned element is always positioned according to the normal flow of the page and is not affected by the top, bottom, left, and right properties.
2- Fixed Positioning: An element with a fixed position is positioned relative to the browser window and will not move even if the window is scrolled. Fixed positioned elements are removed from the normal flow and can overlap other elements.
📌 Example: p.pos_fixed { position: fixed; top: 30px; right: 5px; }
3- Relative Positioning: A relative positioned element is positioned relative to its normal position. The content can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow. Relatively positioned elements are often used as container blocks for absolutely positioned elements.
📌 Example: h2.pos_left { position: relative; left: -20px; } moves the element 20px to the left of its normal position. h2.pos_top { position: relative; top: -50px; } moves it 50px upward.
4- Absolute Positioning: An absolute positioned element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html>. Absolutely positioned elements are removed from the normal flow and can overlap other elements.
📌 Example: h2 { position: absolute; left: 100px; top: 150px; }
Overlapping Elements: When elements are positioned outside the normal flow, they can overlap other elements. The z-index property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order. An element can have a positive or negative stack order.
📌 Example: img { position: absolute; left: 0px; top: 0px; z-index: -1; } places the image behind other elements.
CSS Float: With CSS float, an element can be pushed to the left or right, allowing other elements to wrap around it. Elements are floated horizontally (left or right, not up or down). A floated element will move as far to the left or right as it can. The elements after the floating element will flow around it, while elements before it are not affected.
📌 Example: img { float: right; } floats an image to the right, and following text flows around it to the left.
Turning off Float - Using Clear: Elements after the floating element will flow around it. To avoid this, use the clear property, which specifies which sides of an element other floating elements are not allowed.
💡 Why this matters: Understanding the four positioning methods and how z-index works is critical for creating complex layouts where elements need to overlap or stay fixed during scrolling.
CSS Combinators
A combinator explains the relationship between the selectors. A CSS selector can contain more than one simple selector, and between them, we can include a combinator. There are four different combinators in CSS3:
Descendant Selector: The descendant selector matches all elements that are descendants of a specified element. It uses a space between selectors.
📌 Example: div p { background-color: yellow; } selects all <p> elements inside <div> elements (at any nesting level).
Child Selector: The child selector selects all elements that are the immediate children of a specified element. It uses the > symbol.
📌 Example: div > p { background-color: yellow; } selects all <p> elements that are direct children of a <div> element.
Adjacent Sibling Selector: The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and "adjacent" means "immediately following". It uses the + symbol.
📌 Example: div + p { background-color: yellow; } selects <p> elements placed immediately after <div> elements.
General Sibling Selector: The general sibling selector selects all elements that are siblings of a specified element. It uses the ~ symbol.
📌 Example: div ~ p { background-color: yellow; } selects all <p> elements that are siblings of <div> elements.
⭐ Key Takeaways
Margins create transparent space outside element borders and do not show background color, while paddings create space inside borders and are affected by the element's background color. Both properties support individual side control and shorthand notation with 1-4 values following the clockwise order (top, right, bottom, left). The display property offers two ways to hide elements: visibility:hidden keeps the space, while display:none removes the element entirely. CSS positioning has four methods (static default, fixed to viewport, relative to normal position, and absolute to nearest positioned ancestor), with z-index controlling stack order. Combinators (descendant, child, adjacent sibling, general sibling) define specific relationships between selectors for targeted styling.
🧠 Quick Revision Questions
- What is the difference between margin and padding in terms of background color visibility?
- Using the shorthand property
padding: 10px 20px 30px 40px;, what are the individual padding values for top, right, bottom, and left? - How do
visibility: hiddenanddisplay: nonediffer when hiding an element? - What are the four CSS positioning methods, and how does absolute positioning determine its containing block?
- What symbol does the child selector use to select immediate children, and how does it differ from the descendant selector?
📘 Lecture 44 — CSS Pseudo-Class
📖 Overview: This lecture introduces CSS pseudo-classes, which are used to define special states of elements. It covers how to style elements based on user interaction and document structure, including anchor links, first-child elements, and language-specific styling, enabling dynamic and context-sensitive web designs.
🗂️ Topics Covered
The lecture covers what pseudo-classes are and their syntax, anchor pseudo-classes for different link states, combining pseudo-classes with CSS classes, the :first-child pseudo-class for targeting first child elements, and the :lang pseudo-class for language-specific styling. Examples and code snippets demonstrate each concept.
📝 Lecture Summary
What are Pseudo-classes?
A pseudo-class is used to define a special state of an element. For example, it can be used to style an element when a user's mouse is over it, or to style visited and unvisited links differently.
The syntax of pseudo-classes is:
selector:pseudo-class {
property:value;
}
Anchor Pseudo-classes
Links can be displayed in different ways using these four pseudo-classes:
a:link— styles unvisited linksa:visited— styles visited linksa:hover— styles when the mouse is over the linka:active— styles the selected link
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
🔑 Definition — Pseudo-class: A keyword added to a selector that specifies a special state of the selected element(s).
📌 Example: The a:hover pseudo-class changes the link color to #FF00FF (magenta) when the user hovers the mouse over it.
Pseudo-classes and CSS Classes
Pseudo-classes can be combined with CSS classes.
a.highlight:hover {
color: #ff0000;
}
📌 Example: When you hover over the link with class highlight, it will change color to red (#ff0000).
CSS - The :first-child Pseudo-class
The :first-child pseudo-class matches a specified element that is the first child of another element.
Example 1: Selects any <p> element that is the first child of any element:
p:first-child {
color: blue;
}
Example 2: Selects the first <i> element in all <p> elements:
p i:first-child {
color: blue;
}
Example 3: Selects all <i> elements in <p> elements that are the first child of another element:
p:first-child i {
color: blue;
}
CSS - The :lang Pseudo-class
The :lang pseudo-class allows you to define special rules for different languages.
Note: IE8 supports the :lang pseudo-class only if a <!DOCTYPE> is specified.
📌 Example: The :lang class defines the quotation marks for <q> elements with lang="no" (Norwegian):
q:lang(no) {
quotes: "~" "~";
}
⭐ Key Takeaways
Pseudo-classes are essential for creating interactive and context-sensitive web designs. The four anchor pseudo-classes (:link, :visited, :hover, :active) must be used in this specific order for proper link styling. The :first-child pseudo-class targets elements that are the first child of their parent, and its behavior changes based on selector positioning. The :lang pseudo-class enables language-specific styling, which is crucial for international websites. Pseudo-classes can be combined with regular CSS classes for more specific targeting.
🧠 Quick Revision Questions
- What is the correct syntax for writing a pseudo-class in CSS?
- What are the four anchor pseudo-classes, and in what order should they be defined?
- How does
p:first-child idiffer fromp i:first-childin terms of what elements they select? - What special requirement is needed for IE8 to support the
:langpseudo-class? - How can you combine a pseudo-class with a regular CSS class? Provide an example.
📘 Lecture 46 — CSS Class, Image Gallery, Navigation Menu, Image Opacity, Image Sprites
📖 Overview: This lecture covers CSS class selectors and their syntax, then explores practical applications including image galleries, navigation bars, image opacity/transparency effects, and image sprites for optimizing web performance. These concepts are fundamental for creating visually appealing and efficient websites.
🗂️ Topics Covered
The lecture covers CSS class selectors and how to apply them to specific HTML elements, creating CSS image galleries, building vertical and horizontal navigation bars using HTML lists, implementing image transparency with opacity properties and hover effects, and using CSS image sprites to reduce server requests by combining multiple images into one.
📝 Lecture Summary
46- CSS Class
In CSS, a class is a type of selector. The .class selector styles all elements with the specified class attribute value. Class names can use alphanumeric characters but must NOT start with a number.
🔑 Definition — CSS Class: A selector that targets all HTML elements containing a specific class attribute value, allowing for reusable styling across multiple elements.
📐 Formula: .className { css-declarations } → Applies the specified styles to all elements with that class
📌 Example:
.imp {color:blue; font-size:14px}
<div class="imp"> ... </div>
<span class="imp"> ... </span>
<a class="imp"> ... </a>
All three elements (div, span, a) with class="imp" will display blue text at 14px size.
You can also specify that only specific HTML elements should be affected by a class using element.class selector:
p.imp {color:blue; font-size:14px}
Now only <p> elements with class="imp" will be styled - the <div> and <span> with class="imp" will NOT be affected.
47- CSS Image Gallery
CSS can be used to create an image gallery. This allows displaying multiple images in an organized grid layout with borders, captions, and hover effects using CSS properties.
💡 Why this matters: Image galleries are essential for portfolio sites, e-commerce product displays, and photo albums.
48- CSS Navigation Menu
Navigation bars transform boring HTML menus into good-looking navigation bars. A navigation bar is essentially a list of links, so using <ul> and <li> elements is the standard approach.
🔑 Definition — Navigation Bar: A list of links styled with CSS to provide easy-to-use website navigation, built from standard HTML unordered lists.
Base HTML structure:
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
Standard code for all navigation bars:
ul { list-style-type: none; margin: 0; padding: 0;}
list-style-type: none- Removes the bulletsmargin: 0; padding: 0- Removes browser default settings
Vertical Navigation Bar:
a {display: block; width: 60px;}
display: block- Makes the whole link area clickable (not just the text)width: 60px- Specifies the width of block elements
Horizontal Navigation Bar - Inline method:
li {display: inline; }
display: inline- Removes line breaks before/after each list item, displaying them on one line
Horizontal Navigation Bar - Floating method (for equal-width links):
li {float: left; }
a { display: block; width: 60px; }
width: 60px- Block elements take full width by default, so specifying width allows them to float next to each otherfloat: left- Gets block elements to slide next to each otherdisplay: block- Makes the whole link area clickable
💡 Why this matters: The floating method ensures all links have equal width, while inline method has varying widths based on text length.
48- CSS Image Opacity
The CSS opacity property creates transparent images. It's part of the CSS3 recommendation. The opacity property takes a value from 0.0 - 1.0, where lower values make elements more transparent.
🔑 Definition — CSS Opacity: A property that controls the transparency level of an element, ranging from 0.0 (completely transparent) to 1.0 (completely opaque).
Creating a transparent image:
img {opacity: 0.4; filter: alpha(opacity=40); /* For IE8 and earlier */ }
- IE9, Firefox, Chrome, Opera, Safari: use
opacityproperty (0.0 - 1.0) - IE8 and earlier: use
filter:alpha(opacity=x)where x ranges from 0 to 100
Image Transparency with Hover Effect:
img { opacity: 0.4; filter: alpha(opacity=40); }
img:hover { opacity: 1.0; filter: alpha(opacity=100); }
The image is semi-transparent by default but becomes fully opaque when hovered.
Text in Transparent Box:
Create a <div> (class="background") with background image and border, then another <div> (class="transbox") inside it with background color and border - the inner div is transparent, containing text inside a <p> element.
49- CSS Image Sprites
An image sprite is a collection of images put into a single image. Using image sprites reduces the number of server requests and saves bandwidth when a web page has many images.
🔑 Definition — Image Sprite: A single composite image containing multiple smaller images, used with CSS background positioning to display only the required portion.
Basic sprite example:
#home {width: 46px; height: 44px; background: url(img_navsprites.gif) 0 0;}
<img id="home" src="img_trans.gif">- Uses a small transparent image since src cannot be emptywidth: 46px; height: 44px- Defines the portion of the sprite image to displaybackground: url(img_navsprites.gif) 0 0- Sets background image and position (left 0px, top 0px)
Creating a Navigation List with Sprites:
#navlist {position:relative;}
#navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;}
#navlist li, #navlist a {height:44px;display:block;}
position:relative- Allows absolute positioning inside- List items are absolutely positioned with no margins, padding, or bullets
Positioning specific sprite parts:
#home {left:0px;width:46px; background:url(img_navsprites.gif) 0 0;}
#prev {left:63px;width:43px; background:url('img_navsprites.gif') -47px 0;}
#home: Positioned left, width 46px, background at 0,0#prev: Positioned 63px right (46px home width + spacing), width 43px, background shifted -47px right (46px + 1px divider)
⭐ Key Takeaways
CSS classes use the .class selector to style multiple elements with the same class attribute, and the element.class syntax restricts styling to specific HTML elements. Navigation bars are built from unordered lists with bullets removed, where vertical bars use block display on links, and horizontal bars use either inline list items or floating with specified widths for equal sizing. Image opacity ranges from 0.0 to 1.0 in modern browsers, with separate filter syntax for older IE versions, and can include hover effects for interactive transparency changes. Image sprites combine multiple images into one file to reduce server requests, using CSS background positioning with precise width and height values to display only the needed portion. The sprite technique is particularly useful for navigation menus where different states of buttons need to be displayed from a single image source.
🧠 Quick Revision Questions
- What is the correct CSS syntax to style only
<p>elements that have the class "highlight"? - What are the two methods for creating a horizontal navigation bar, and which one ensures all links have equal width?
- What CSS property creates transparency in modern browsers, and what is its value range?
- How would you display the second image in a sprite when the first image is 46px wide with a 1px divider?
- Why is
display: blockimportant when creating navigation bars from anchor elements?
📘 Lecture 51 — CSS Attribute Selectors
📖 Overview: This lecture covers CSS Attribute Selectors, a powerful way to style HTML elements based on their attributes or attribute values. It explains how to target elements with specific attributes, exact values, partial matches, and how to apply these selectors for practical tasks like styling forms without needing classes or IDs.
🗂️ Topics Covered
This lecture introduces the concept of styling HTML elements with specific attributes, then systematically covers seven CSS attribute selectors: [attribute], [attribute=value], [attribute~=value], [attribute|=value], [attribute^=value], [attribute$=value], and [attribute*=value]. Each selector is explained with its syntax, purpose, and a code example. The lecture concludes with a practical application of attribute selectors for styling forms.
📝 Lecture Summary
Style HTML Elements with Specific Attributes
It is possible to style HTML elements that have specific attributes or attribute values. This approach allows for precise targeting without relying on classes or IDs.
CSS [attribute] Selector
The [attribute] selector is used to select elements with a specified attribute. The following example selects all <a> elements with a target attribute:
a[target] {
background-color: yellow;
}
🔑 Definition — [attribute] Selector: Selects all elements that have the specified attribute, regardless of its value.
CSS [attribute=value] Selector
The [attribute=value] selector is used to select elements with a specified attribute and value. The example below selects all <a> elements with a target="_blank" attribute:
a[target="_blank"] { background-color: yellow; }
🔑 Definition — [attribute=value] Selector: Selects all elements that have the specified attribute exactly equal to the specified value.
CSS [attribute~=value] Selector
The [attribute~=value] selector is used to select elements with an attribute value containing a specified word. The example below selects all elements with a title attribute that contains a space-separated list of words, one of which is "flower":
[title~="flower"] { border: 5px solid yellow; }
🔑 Definition — [attribute~=value] Selector: Selects elements where the attribute value is a space-separated list of words, and one of those words is exactly the specified value.
CSS [attribute|=value] Selector
The [attribute|=value] selector is used to select elements with the specified attribute starting with the specified value. The following example selects all elements with a class attribute value that begins with "top":
[class|="top"] { background: yellow; }
Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen(-), like class="top-text"!
🔑 Definition — [attribute|=value] Selector: Selects elements where the attribute value is exactly the specified value or starts with the specified value followed by a hyphen (-).
CSS [attribute^=value] Selector
The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value. The following example selects all elements with a class attribute value that begins with "top":
[class^="top"] {background: yellow; }
🔑 Definition — [attribute^=value] Selector: Selects elements where the attribute value starts with the specified value. This is a "begins with" match, similar to a prefix search.
CSS [attribute$=value] Selector
The [attribute$=value] selector is used to select elements whose attribute value ends with a specified value. The following example selects all elements with a class attribute value that ends with "test":
[class$="test"] { background: yellow; }
🔑 Definition — [attribute$=value] Selector: Selects elements where the attribute value ends with the specified value. This is an "ends with" match, similar to a suffix search.
CSS [attribute*=value] Selector
The [attribute*=value] selector is used to select elements whose attribute value contains a specified value. The following example selects all elements with a class attribute value that contains "te":
[class*="te"] { background: yellow; }
🔑 Definition — [attribute=value] Selector*: Selects elements where the attribute value contains the specified value anywhere within it. This is a "contains" match, similar to a substring search.
Styling Forms
The attribute selectors can be useful for styling forms without class or ID. This example demonstrates styling form elements based on their type attribute, such as text inputs and buttons:
input[type="text"] {width: 150px; display: block; margin-bottom: 10px; background-color: yellow; }
input[type="button"] { width: 120px; margin-left: 35px; display: block;}
💡 Why this matters: This technique reduces the need for adding extra classes or IDs to form elements, keeping the HTML cleaner and making the CSS more efficient for targeting specific input types.
⭐ Key Takeaways
The key to mastering CSS Attribute Selectors is understanding the subtle differences between the partial matching operators: ~= for whole words in a space-separated list, |= for exact or hyphen-prefixed values, ^= for any beginning match, $= for any ending match, and *= for any substring match. The exact match selector [attribute=value] is the strictest, while [attribute] is the broadest. Remember that attribute selectors are incredibly useful for styling forms by targeting input[type="text"] or input[type="button"] without needing extra HTML markup. Crucially, for the |= selector, the value must be a whole word or followed by a hyphen, not just any prefix. Mastering these selectors allows for cleaner, more semantic HTML and more precise, efficient CSS styling.
🧠 Quick Revision Questions
- Which CSS attribute selector would you use to style all
<input>elements that have atypeattribute, regardless of its value? - What is the difference between the
[attribute^=value]selector and the[attribute|=value]selector, especially regarding what "starts with" means? - You want to select all elements with a
classattribute that contains the word "box" in a space-separated list. Which selector do you use? - Explain the practical benefit of using
input[type="text"]instead of a class selector like.text-inputfor styling text fields in a form. - For the
[attribute$=value]selector, will[class$="er"]match an element withclass="container"? Why or why not?
📘 Lecture 54-59 — JavaScript Statements, Comments, Variables, Operators, Functions, Objects & Scope
📖 Overview: This lecture covers fundamental JavaScript concepts including statements, comments, variables, operators, functions, objects, and scope. These building blocks are essential for writing any JavaScript program and understanding how the language executes code, stores data, and manages variable accessibility.
🗂️ Topics Covered
This lecture covers JavaScript statements with semicolons and code blocks, single-line and multi-line comments for code explanation and testing, JavaScript variables with identifiers and data types (numbers and strings), operators including arithmetic and string operators, JavaScript functions with syntax and invocation methods, JavaScript objects as containers for properties and methods, and JavaScript scope differentiating local and global variables.
📝 Lecture Summary
54- JavaScript Statements
A JavaScript statement tells the browser what to do. Statements are executed one by one in the same order as written. Most JavaScript programs contain many statements. Example: document.getElementById("demo").innerHTML = "Hi, Everyone."; This tells the browser to write "Hello Everyone." inside an HTML element with id="demo".
Semicolons (;) separate JavaScript statements. Add a semicolon at the end of each executable statement. When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b;
JavaScript White Space: JavaScript ignores multiple spaces. You can add white space to make your script more readable.
JavaScript Line Length and Line Breaks: For best readability, programmers often avoid code lines longer than 80 characters. If a statement doesn't fit, break it after an operator:
document.getElementById("demo").innerHTML =
"Hello Dolly.";
JavaScript Code Blocks: Statements can be grouped together in code blocks inside curly brackets {...}. The purpose is to define statements to be executed together.
55- JavaScript Comments
JavaScript comments explain JavaScript code and make it more readable. You can also use comments to prevent execution when testing alternative code.
- Single Line Comments: Start with
//. Any text between//and the end of the line will be ignored by JavaScript. - Multi-line Comments: Start with
/*and end with*/. Any text between/*and*/will be ignored by JavaScript.
Using Comments to Prevent Execution: Adding // in front of a code line changes it from an executable line to a comment. This is suitable for code testing.
56a- JavaScript Variables & Operators
JavaScript Variables: Containers for storing data values. In the example, x, y, and z are variables:
var x = 5;
var y = 6;
var z = x + y;
- x stores the value 5
- y stores the value 6
- z stores the value 11
JavaScript Identifiers: All JavaScript variables must be identified with unique names called identifiers. General rules:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter
- Names can also begin with $ and _
- Names are case sensitive (y and Y are different variables)
- Reserved words (like JavaScript keywords) cannot be used as names
The Assignment Operator: In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.
JavaScript Data Types: Variables can hold numbers like 100 and text values like "John Doe". Text values are called text strings. Strings are written inside double or single quotes. Numbers are written without quotes.
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
var anum = '3.14';
Declaring (Creating) JavaScript Variables: Creating a variable is called "declaring" a variable. Use the var keyword:
var carName;
After declaration, the variable is empty (has no value). To assign a value: carName = "Volvo";
One Statement, Many Variables: You can declare many variables in one statement:
var person = "John Doe", carName = "Volvo", price = 200;
Value = undefined: A variable declared without a value will have the value undefined. If you re-declare a variable, it will not lose its value.
56b- JavaScript Variables & Operators
JavaScript Operators: You can do arithmetic with variables using operators like = and +:
var x = 5 + 2 + 3;
var x = 5; // assign the value 5 to x
var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z
JavaScript String Operators: The + operator can also add (concatenate) strings:
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2; // "John Doe"
The += assignment operator can also concatenate strings:
txt1 = "What a very ";
txt1 += "nice day"; // "What a very nice day"
Adding Strings and Numbers: Adding two numbers returns the sum. Adding a number and a string returns a string:
x = 5 + 5; // 10 (number)
y = "5" + 5; // "55" (string)
z = "Hello" + 5; // "Hello5" (string)
57- JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task. The function is executed when "something" invokes (calls) it.
Function Syntax: Defined with the function keyword, followed by a name, followed by parentheses ():
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function definition. Function arguments are the real values received when invoked.
Function Invocation: The code executes when "something" invokes the function:
- When an event occurs (user clicks a button)
- When invoked (called) from JavaScript code
- Automatically (self invoked)
Function Return: When JavaScript reaches a return statement, the function stops executing. JavaScript will "return" to execute the code after the invoking statement.
Why Functions? You can reuse code: Define the code once and use it many times with different arguments to produce different results:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(32);
The () Operator Invokes the Function: toCelsius refers to the function object, and toCelsius() refers to the function result. Accessing a function without () returns the function definition.
Functions Used as Variables: You can use functions the same way as variables:
var text = "The temperature is " + toCelsius(32) + " Centigrade";
58- JavaScript Objects
Object properties can be primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods.
59- JavaScript Scope
Scope is the set of variables, objects, and functions you have access to. JavaScript has function scope: The scope changes inside functions.
Local JavaScript Variables: Variables declared within a function become LOCAL to the function. They can only be accessed within the function. Local variables are created when a function starts and deleted when the function completes:
// code here cannot use variable userName
function myFunction() {
var userName = "Tariq";
// code here can use variable userName
}
Global JavaScript Variables: A variable declared outside a function becomes GLOBAL. All scripts and functions on a web page can access it. The global scope is the complete JavaScript environment.
Automatically Global: If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
The Lifetime of JavaScript Variables:
- Local variables are deleted when the function is completed
- Global variables are deleted when you close the page
- Function arguments (parameters) work as local variables inside functions
- In HTML, the global scope is the window object: All global variables belong to the window object
💡 Why this matters: Understanding scope prevents variable naming conflicts and ensures variables are accessible only where needed, which is crucial for writing secure, maintainable JavaScript code.
⭐ Key Takeaways
The most critical concepts from this lecture are: JavaScript statements must end with semicolons and can be grouped in code blocks; variables are declared with var and can hold numbers or strings, with strings requiring quotes; the + operator concatenates strings but adding a number and string produces a string; functions are defined with the function keyword, can take parameters, and use return to output values; and scope determines variable accessibility — local variables exist only within functions while global variables exist throughout the page. Understanding these fundamentals is essential for writing any JavaScript program.
🧠 Quick Revision Questions
- What is the purpose of semicolons in JavaScript statements?
- How do you declare a JavaScript variable, and what value does an undeclared variable hold?
- What happens when you add a number and a string together in JavaScript?
- What is the difference between a function parameter and a function argument?
- What is the difference between a local variable and a global variable in JavaScript, and when is each one deleted?
📘 Lecture 60 — JavaScript Events
📖 Overview: This lecture introduces JavaScript's event-driven interaction with HTML, explaining how events triggered by users or the browser can execute JavaScript code. It covers fundamental event handling, string manipulation, number properties/methods, the Math object, Date object, and JavaScript arrays, providing essential building blocks for dynamic web development.
🗂️ Topics Covered
The lecture covers JavaScript Events and HTML event handling, JavaScript Strings including length property and special characters, JavaScript Numbers with 64-bit floating point storage, precision, hexadecimal and Infinity/NaN values, Number Methods for conversion, the Math object with rounding functions and constants, Date object creation, formats, get/set methods and comparison, and JavaScript Arrays including creation, properties, methods, and associative arrays.
📝 Lecture Summary
JavaScript Events
JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. An HTML event can be something the browser does (like a page finishing loading) or something a user does (like clicking a button or changing an input field). HTML allows event handler attributes with JavaScript code to be added to HTML elements.
🔑 Definition — Event Handler Attribute: An HTML attribute that specifies JavaScript code to execute when a particular event occurs on an element.
Syntax:
- With single quotes:
<some-HTML-element some-event='some JavaScript'> - With double quotes:
<some-HTML-element some-event="some JavaScript">
📌 Example 1: Using onclick to display the current date in another element:
<button onclick="getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
📌 Example 2: Using onclick to change its own element's content:
<button onclick="this.innerHTML=Date()">The time is?</button>
💡 Why this matters: Event handling is the foundation of interactive web pages, allowing dynamic responses to user actions without page reloads.
JavaScript Strings
A JavaScript string simply stores a series of characters. A string can be any text inside quotes, using single or double quotes.
🔑 Definition — String: A sequence of characters enclosed in single or double quotes.
📌 Example: var carname = "Volvo XC60"; or var carname = 'Volvo XC60';
String Length: The length of a string is found in the built-in property length.
📌 Example:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length; // returns 26
Special Characters: The backslash escape character (\) turns special characters into string characters, preventing JavaScript from misinterpreting quotes.
📌 Example:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north.";
Breaking Long Code Lines: For readability, break code lines after an operator. Use a backslash to break a text string, or use string addition.
📌 Example with backslash: document.getElementById("demo").innerHTML = "hi \ How are you?";
📌 Example with string addition: document.getElementById("demo").innerHTML = "Hi," + "How are you?";
⚠️ You cannot break a code line with a backslash at the beginning of a line.
Strings Can be Objects: Normally strings are primitive values, but can also be defined as objects with the new keyword.
📌 Example:
var x = "Mike";
var y = new String("Mike");
// typeof x returns string
// typeof y returns object
When using == (equality operator), equal strings look equal. When using === (strict equality operator), equal strings are not equal because it expects equality in both type and value.
💡 Why this matters: Understanding the difference between primitive strings and String objects is crucial for avoiding bugs when comparing values.
JavaScript Numbers
JavaScript numbers can be written with or without decimals, and extra large or small numbers can be written with scientific notation.
🔑 Definition — JavaScript Number: A 64-bit double precision floating point number following the IEEE 754 standard, stored in 64 bits (fraction in bits 0-51, exponent in bits 52-62, sign in bit 63).
📌 Example: var x = 123e5; // 12300000, var y = 123e-5; // 0.00123
Precision: Integers are accurate up to 15 digits. The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate.
📌 Example of precision issue:
var x = 0.2 + 0.1; // returns 0.30000000000000004
To solve: var x = (0.2 * 10 + 0.1 * 10) / 10; // returns 0.3
Hexadecimal: JavaScript interprets numeric constants as hexadecimal if preceded by 0x.
📌 Example: var x = 0xFF; // returns 255
Infinity: Infinity (or -Infinity) is returned when calculating a number outside the largest possible number or dividing by zero. typeof Infinity returns "number".
📌 Example: var x = 2 / 0; // x will be Infinity
NaN - Not a Number: NaN is a reserved word indicating a value is not a number. Use the global function isNaN() to check.
📌 Example: isNaN(100 / "Apple"); // returns true
Numbers Can be Objects: Like strings, numbers can be primitive values or objects created with new Number().
📌 Example:
var x = 500;
var y = new Number(500);
// x == y is true (equal values)
// x === y is false (different types)
// Objects cannot be compared: new Number(500) == new Number(500) is false
💡 Why this matters: Understanding number precision and object comparison prevents common arithmetic and logic errors.
JavaScript Number Methods
Number methods return a new value and do not change the original variable.
Table of Number Methods:
| Method | Description |
|---|---|
| toString() | Returns a number as a string |
| toExponential() | Returns a string with number rounded and written using exponential notation |
| toFixed() | Returns a string with number rounded and written with specified decimals |
| toPrecision() | Returns a string with number written with specified length |
| valueOf() | Returns a number as a number |
Converting Variables to Numbers (Global JavaScript Methods):
🔑 Number(): Converts JavaScript variables to numbers.
📌 Examples:
Number(true)→ 1Number(false)→ 0Number("10")→ 10Number("10 20")→ NaN
🔑 parseInt(): Parses a string and returns a whole number. Only the first number is returned; spaces are allowed.
📌 Examples:
parseInt("10.33")→ 10parseInt("10 years")→ 10parseInt("years 10")→ NaN
🔑 parseFloat(): Parses a string and returns a number (including decimals). Only the first number is returned.
📌 Examples:
parseFloat("10.33")→ 10.33parseFloat("10 years")→ 10parseFloat("years 10")→ NaN
JavaScript Math
The Math object allows you to perform mathematical tasks.
🔑 Key Math Methods:
- Math.random(): Returns a random number between 0 (inclusive) and 1 (exclusive)
- Math.round(): Rounds to the nearest integer
Math.round(4.7)→ 5Math.round(4.4)→ 4
- Math.ceil(): Rounds up to the nearest integer
Math.ceil(4.4)→ 5
- Math.floor(): Rounds down to the nearest integer
Math.floor(4.7)→ 4
- Math.min(): Returns the lowest value in a list of arguments
Math.min(0, 150, 30, 20, -8)→ -8
- Math.max(): Returns the highest value in a list of arguments
Math Constants (8 mathematical constants):
| Constant | Returns |
|---|---|
| Math.E | Euler's number |
| Math.PI | PI |
| Math.SQRT2 | Square root of 2 |
| Math.SQRT1_2 | Square root of 1/2 |
| Math.LN2 | Natural logarithm of 2 |
| Math.LN10 | Natural logarithm of 10 |
| Math.LOG2E | Base 2 logarithm of E |
| Math.LOG10E | Base 10 logarithm of E |
JavaScript Date
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds).
Date Formats: JavaScript dates can be written as strings or numbers (milliseconds since January 1, 1970, 00:00:00).
Creating Date Objects: Date objects are created with the new Date() constructor.
📌 Ways to create dates:
new Date()— current date and timenew Date(milliseconds)— zero time plus millisecondsnew Date(dateString)— e.g.,new Date("October 13, 2014 11:13:00")new Date(year, month, day, hours, minutes, seconds, milliseconds)— 7 numbers
📌 Example: var d = new Date(86400000); // creates date for January 2, 1970
Date Methods:
- toString() — converts date to string automatically
- toUTCString() — converts to UTC string
- toDateString() — converts to more readable format
Date Formats:
- ISO Format: YYYY-MM-DD (preferred) —
new Date("2015-03-25") - Long Format: MMM DD YYYY —
new Date("Mar 25 2015") - Short Format: MM/DD/YYYY —
new Date("03/25/2015")
Date Get Methods: Used for getting a part of a date (e.g., getDate(), getDay(), getFullYear(), getHours(), getMinutes()).
Date Set Methods: Used for setting a part of a date (e.g., setDate(), setFullYear(), setHours()).
📌 Example (adding 4 days to current date):
var d = new Date();
d.setDate(d.getDate() + 4);
String to Date: Use Date.parse() to convert a valid date string to milliseconds.
📌 Example: var msec = Date.parse("March 21, 2012");
Date Comparison: Date objects can be compared using standard comparison operators.
📌 Example:
var today = new Date();
var anotherday = new Date("03/25/2016");
if (anotherday > today) {
result = "Today is before March 25, 2016.";
}
JavaScript Arrays
An array is a special variable that can hold more than one value at a time.
🔑 Definition — Array: A data structure that stores multiple values under a single name, accessed by index numbers.
Creating an Array:
- Using array literal:
var cars = ["Toyota", "Honda", "BMW"]; - Using
newkeyword:var cars = new Array("Toyota", "Honda", "BMW");
Accessing Elements: By index number (starting at 0)
cars[0]— accesses first elementcars[0] = "Audi"— modifies first element
Arrays are Objects: Arrays are special types of objects. The typeof operator returns "object" for arrays.
📌 Difference:
- Arrays use numbered indexes:
person[0]returns "Adil" - Objects use named indexes:
person.firstNamereturns "Adil"
Array Properties and Methods:
- length — returns the number of array elements
- sort() — sorts the array
Adding Array Elements: Use the length property
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds Lemon
Looping Array Elements: Use a for loop
var index;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
for (index = 0; index < fruits.length; index++) {
text += fruits[index];
}
Associative Arrays: JavaScript does NOT support arrays with named indexes. Arrays use numbered indexes; objects use named indexes.
⚠️ Avoid new Array(): Use [] instead of new Array(). The new keyword complicates code and produces side effects.
📌 Example: var points = []; // Good vs var points = new Array(); // Bad
How to Recognize an Array: Since typeof returns "object", create an isArray() function:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
💡 Why this matters: Arrays are fundamental for storing and manipulating collections of data, essential for building dynamic web applications.
⭐ Key Takeaways
The lecture covers six core JavaScript topics essential for web development. Events enable interactive user experiences through HTML event handler attributes. Strings require careful handling of quotes using escape characters, and their primitive vs. object nature affects equality comparisons. Numbers follow IEEE 754 64-bit standard with important precision limitations, and methods like parseInt()/parseFloat() are crucial for type conversion. The Math object provides essential mathematical operations like rounding and constants. The Date object is versatile with multiple creation methods and formats, supporting get/set operations and comparisons. Arrays store multiple values efficiently, use numbered indexes, and the length property is the safest way to add elements—always prefer array literals over new Array().
🧠 Quick Revision Questions
- What is the difference between
==and===when comparing a string primitive to a String object? - Why does
0.2 + 0.1return0.30000000000000004in JavaScript and how can this be fixed? - What is the difference between
parseInt()andparseFloat()when converting "10.33 years"? - How would you create a Date object for March 25, 2015, and then add 7 days to it?
- Why should you avoid using
new Array()to create arrays, and what is the correct alternative?
📘 Lecture 69 — Array Methods
📖 Overview: This lecture provides a comprehensive exploration of JavaScript array methods, including operations for converting, modifying, sorting, and manipulating arrays. It also covers comparisons, conditions, loops, error handling, and debugging techniques essential for effective JavaScript programming.
🗂️ Topics Covered
The lecture covers JavaScript array methods such as converting arrays to strings, popping and pushing elements, shifting, changing, deleting, splicing, sorting, reversing, using the compare function, joining, and slicing arrays. It then moves into JavaScript comparisons including comparison operators, logical operators, conditional operators, comparing different types, and bitwise operators. Following that, JavaScript conditions are explained with if, else, and else if statements. The switch statement, for loops, while loops, break and continue statements, data types, type conversion, regular expressions, hoisting, error handling with try/catch/throw/finally, and debugging methods are all covered in detail.
📝 Lecture Summary
Converting Arrays to Strings
In JavaScript, all objects have the valueOf() and toString() methods. The valueOf() method is the default behavior for an array and returns the array as a comma-separated string.
🔑 Definition — valueOf(): The default method for arrays that returns the array elements as a comma-separated string.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.valueOf(); outputs Banana,Orange,Apple,Mango
Popping and Pushing
The pop() method removes the last element from an array. The push() method adds a new element to an array at the end.
🔑 Definition — pop(): Removes the last element from an array.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); removes "Mango" from fruits.
🔑 Definition — push(): Adds a new element to the end of an array.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); adds "Kiwi" to the end of fruits.
Shifting Elements
The shift() method removes the first element of an array and shifts all other elements one position up.
🔑 Definition — shift(): Removes the first element of an array and shifts remaining elements up.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); removes "Banana" from fruits.
Changing Elements
Array elements are accessed using their index number. Elements can be changed by assigning a new value to a specific index. You can also append a new element using the length property.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; changes first element to "Kiwi". fruits[fruits.length] = "Kiwi"; appends "Kiwi" to the array.
Deleting Elements
Elements can be deleted using the JavaScript delete operator, which sets the element to undefined.
🔑 Definition — delete operator: Removes an array element but leaves an undefined hole in the array.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; makes first element undefined: [undefined, "Orange", "Apple", "Mango"]
Splicing an Array
The splice() method can add new items to an array at a specified position, optionally removing elements.
🔑 Definition — splice(): Adds/removes elements from an array. Parameters are: (position, how many elements to remove, new elements to add).
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 1, "Lemon", "Kiwi"); removes 1 element at index 2 and adds "Lemon" and "Kiwi", resulting in ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]
💡 Why this matters: The first parameter (2) defines position, second (1) defines how many to remove, rest define new elements.
Sorting an Array
The sort() method sorts an array alphabetically.
🔑 Definition — sort(): Sorts array elements alphabetically.
📌 Example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); results in ["Apple", "Banana", "Mango", "Orange"]
Reversing an Array
The reverse() method reverses the elements in an array and can be used with sort() for descending order.
🔑 Definition — reverse(): Reverses the order of array elements.
📌 Example: After sorting, fruits.reverse(); gives ["Orange", "Mango", "Banana", "Apple"]
The Compare Function
The compare function defines an alternative sort order for numeric sorting. It should return a negative, zero, or positive value.
🔑 Definition — compare function: A function that defines sort order. Returns negative (a before b), zero, or positive (b before a).
📐 Formula: function(a, b){return a-b} → sorts numbers in ascending order.
📌 Example: var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b}); sorts numbers numerically. When comparing 40 and 100, the function returns 40-100 = -60 (negative), so 40 is sorted lower than 100.
Joining Arrays
The concat() method creates a new array by concatenating two or more arrays.
🔑 Definition — concat(): Creates a new array by joining two or more arrays.
📌 Example: var myGirls = ["Aisha", "Meryam"]; var myBoys = ["Bilal", "Umer", "Ali"]; var myChildren = myGirls.concat(myBoys); results in ["Aisha", "Meryam", "Bilal", "Umer", "Ali"]
Slicing an Array
The slice() method extracts a portion of an array into a new array without modifying the original.
🔑 Definition — slice(): Slices out a piece of an array into a new array. Parameters: (start index, end index — not included).
📌 Example: var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); gives ["Orange", "Lemon"]. fruits.slice(2); gives ["Lemon", "Apple", "Mango"]
JavaScript Comparisons
Comparison operators are used to determine equality or difference between variables or values. Major operators include == (equal to), === (equal value and type), != (not equal), !== (not equal value or type), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).
📌 Example for x=5: x == 5 returns true, x === "5" returns false, x != 8 returns true, x > 8 returns false, x < 8 returns true, x >= 8 returns false.
Logical operators determine logic between variables: && (and), || (or), ! (not).
📌 For x=6, y=3: (x < 10 && y > 1) is true, (x == 5 || y == 5) is false, !(x == y) is true.
The conditional (ternary) operator assigns a value based on a condition.
📐 Formula: variablename = (condition) ? value1:value2
📌 Example: var vo = (age < 18) ? "Too young":"Old enough";
When comparing different types, JavaScript converts the number to a string for comparison. Comparing strings alphabetically means "2" is greater than "12" because 1 is less than 2. Variables should be converted to proper type before comparison using Number(age) and isNaN().
JavaScript Conditions
Conditional statements perform different actions for different decisions. The if statement executes code if a condition is true. The else statement executes code if the condition is false. The else if statement specifies a new condition if the first is false.
📌 Example: if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
📌 Example with else if: if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
JavaScript Switch Statement
The switch statement selects one of many blocks of code to execute based on different conditions.
📐 Formula:
switch(expression) {
case n1: code block; break;
case n2: code block; break;
default: default code block;
}
📌 Example: switch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; }
The break keyword stops execution and exits the switch block. The default keyword specifies code to run if no case matches. Multiple cases can share the same code block (fall-through).
JavaScript For Loop
Loops execute a block of code multiple times. The for loop loops through a block of code a number of times.
📐 Formula: for (statement 1; statement 2; statement 3) { code block }
- Statement 1 executes before the loop starts (initialization)
- Statement 2 defines the condition for running the loop
- Statement 3 executes each time after the loop
📌 Example: for (i = 0; i < 5; i++) { text += "The number is " + i; } outputs numbers 0 through 4.
All three statements are optional. Statement 1 can initialize multiple values. Statement 2 can be omitted but must have a break inside. Statement 3 can do negative increment or anything.
The for/in loop iterates through the properties of an object.
📌 Example: for (x in person) { text += person[x]; } outputs "John Doe 25"
JavaScript While Loop
The while loop executes a block of code as long as a specified condition is true.
📐 Formula: while (condition) { code block }
📌 Example: while (i < 10) { text += "The number is " + i; i++; }
The do/while loop executes the code block once before checking the condition, then repeats as long as the condition is true.
📐 Formula: do { code block } while (condition);
📌 Example: do { text += "The number is " + i; i++; } while (i < 10); always executes at least once.
A while loop is similar to a for loop with statement 1 and statement 3 omitted.
JavaScript Break and Continue
The break statement jumps out of a loop entirely. The continue statement jumps over one iteration and continues with the next.
📌 Example with break:
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i;
}
Output: numbers 0, 1, 2 (stops at 3).
📌 Example with continue:
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i;
}
Output: numbers 0, 1, 2, 4, 5, 6, 7, 8, 9 (skips 3).
JavaScript Data Types
There are 5 data types that can contain values: String, Number, Boolean, Object, Function. There are 3 types of objects: Object, Date, Array. And 2 data types that cannot contain values: null, undefined.
The typeof operator finds the data type of a variable.
📌 Examples: typeof "John" returns "string", typeof 3.14 returns "number", typeof NaN returns "number", typeof [1,2,3,4] returns "object", typeof null returns "object".
The constructor property returns the constructor function for all JavaScript variables and can be used to check if an object is of a certain type.
JavaScript Type Conversion
JavaScript variables can be converted using JavaScript functions or automatically. The String() method converts numbers, booleans, and dates to strings. The toString() method does the same. Methods like toExponential(), toFixed(), and toPrecision() format numbers.
The Number() method converts strings to numbers (empty strings become 0, anything else becomes NaN). The unary + operator also converts variables to numbers.
Booleans convert to numbers: Number(false) returns 0, Number(true) returns 1. Dates convert to milliseconds.
Automatic type conversion happens when JavaScript operates on wrong data types: 5 + null returns 5, "5" + null returns "5null", "5" + 1 returns "51", "5" - 1 returns 4.
JavaScript RegExp
A regular expression is a sequence of characters forming a search pattern for text search and replace operations.
📐 Formula: /pattern/modifiers;
Modifiers include: i (case-insensitive), g (global match), m (multiline matching). Brackets find ranges: [abc] (any of characters), [0-9] (any digit), (x|y) (alternatives). Metacharacters include: \d (digit), \s (whitespace), \b (word boundary), \uxxxx (Unicode). Quantifiers include: n+ (one or more), n* (zero or more), n? (zero or one).
The test() method returns true/false if pattern is found. The exec() method returns the found text or null.
JavaScript Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. Variables can be used before they are declared because declarations (not initializations) are hoisted.
📌 Example: x = 5; var x; works because var x; is hoisted to the top.
Only declarations are hoisted, not initializations. To avoid bugs, always declare all variables at the beginning of every scope.
JavaScript Error Handling
The try statement tests a block of code for errors. The catch statement handles the error. The throw statement creates custom errors. The finally statement executes code after try/catch regardless of result.
📐 Formula:
try { block of code to try }
catch(err) { block of code to handle errors }
finally { block of code executed regardless }
The throw statement allows custom exceptions: throw "Too big"; or throw 500;
📌 Input validation example:
try {
if (x == "") throw "empty";
if (isNaN(x)) throw "not a number";
if(x < 5) throw "too low";
if(x > 10) throw "too high";
} catch(err) {
message = "Input is " + err;
}
JavaScript Debugging
Debugging is searching for errors in programming code. All modern browsers have built-in debuggers. The console.log() method displays JavaScript values in the debugger window. Breakpoints stop code execution to examine values. The debugger keyword stops execution and calls the debugging function.
📌 Example: debugger; stops execution before the next line.
⭐ Key Takeaways
Array methods like push(), pop(), shift(), splice(), slice(), sort(), reverse(), and concat() are essential for manipulating arrays efficiently. Comparison operators (==, ===, !=, !==, >, <, >=, <=) and logical operators (&&, ||, !) are fundamental for decision-making in conditional statements and loops. The for, while, and do/while loops enable repetitive code execution, with break and continue controlling loop flow. Understanding type conversion, regular expressions, hoisting (declarations moved to top), and error handling with try/catch/throw/finally is crucial for writing robust JavaScript code. Debugging tools like console.log() and the debugger keyword help identify and fix errors.
🧠 Quick Revision Questions
- What does the splice() method do and what do its first two parameters represent?
- Explain the difference between == and === in JavaScript comparisons with an example.
- How does the ternary operator work? Provide its syntax and an example.
- What is the difference between break and continue statements in loops?
- What is hoisting in JavaScript and does it apply to initializations?
📘 Lecture 83 — JavaScript Best Practices
📖 Overview: This lecture covers essential JavaScript best practices for writing clean, efficient, and maintainable code. It emphasizes the importance of avoiding global variables, using proper declarations, and handling type conversions and comparisons correctly to prevent bugs and performance issues.
🗂️ Topics Covered
The lecture addresses several key best practices including avoiding global variables, always declaring local variables, placing declarations at the top, initializing variables, avoiding object declarations for primitives, using literal syntax instead of constructors, beingware of automatic type conversions, using strict equality (===), setting parameter defaults, and ending switch statements with defaults.
📝 Lecture Summary
Avoid Global Variables
Minimize the use of global variables, including all data types, objects, and functions. Global variables and functions can be overwritten by other scripts, causing unpredictable behavior. Use local variables instead, and learn how to use closures to maintain variable scope.
💡 Why this matters: Global variables create dependencies and make code harder to maintain and debug, especially in larger projects with multiple scripts.
Always Declare Local Variables
All variables used in a function should be declared as local variables. Local variables must be declared with the var keyword; otherwise they will become global variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function. This will:
- Give cleaner code
- Provide a single place to look for local variables
- Make it easier to avoid unwanted (implied) global variables
- Reduce the possibility of unwanted re-declarations
// Declare at the beginning
var firstName, lastName, price, discount, fullPrice;
// Use later
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
fullPrice = price * 100 / discount;
This also goes for loop variables:
// Declare at the beginning
var i;
// Use later
for (i = 0; i < 5; i++) {
....
}
Initialize Variables
It is a good coding practice to initialize variables when you declare them. This will:
- Give cleaner code
- Provide a single place to initialize variables
- Avoid undefined values
Never Declare Number, String, or Boolean Objects
Always treat numbers, strings, or booleans as primitive values, not as objects. Declaring these types as objects slows down execution speed and produces nasty side effects.
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Or even worse:
var x = new String("John");
var y = new String("John");
(x == y) // is false because you cannot compare objects.
Don't Use new Object()
- Use
{}instead ofnew Object() - Use
""instead ofnew String() - Use
0instead ofnew Number() - Use
falseinstead ofnew Boolean() - Use
[]instead ofnew Array() - Use
/()/instead ofnew RegExp() - Use
function(){}instead ofnew function()
Check this example:
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/; // new regexp object
var x7 = function(){}; // new function object
Beware of Automatic Type Conversions
Beware that numbers can accidentally be converted to strings or NaN (Not a Number). JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type.
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
When doing mathematical operations, JavaScript can convert numbers to strings. Subtracting a string from a string does not generate an error but returns NaN.
📌 Example:
"Hello" - "Dolly" // returns NaN
Use === Comparison
The == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type.
0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // false
🔑 Definition — Strict Equality (===): An operator that compares both values and types without performing type conversion.
Use Parameter Defaults
If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments.
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
End Your Switches with Defaults
End your switch statements with defaults, even if you think it's not needed.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown";
}
⭐ Key Takeaways
The most critical practices from this lecture include: always declare variables at the top of their scope using var to avoid global scope pollution; initialize variables when declared to prevent undefined values; use primitive literals (e.g., "", 0, false, []) instead of constructor objects (new String(), new Number(), etc.) to avoid performance issues and unexpected behavior; always use === instead of == to avoid automatic type coercion; and be cautious of JavaScript's loose typing, which can cause numbers to become strings or NaN during operations.
🧠 Quick Revision Questions
- Why should you avoid global variables in JavaScript?
- What is the difference between
==and===in JavaScript? - What does the expression
"Hello" - "Dolly"evaluate to in JavaScript, and why? - What is the recommended way to create an empty array:
new Array()or[]? Why? - What happens when a function is called with a missing argument in JavaScript?
📘 Lecture 85 — JavaScript Common Mistakes
📖 Overview: This lecture covers the most common mistakes programmers make in JavaScript and explains how to avoid them. Understanding these pitfalls is crucial for writing reliable, secure, and bug-free JavaScript code in real-world applications.
🗂️ Topics Covered
The lecture covers a comprehensive list of common JavaScript mistakes including: accidentally using assignment operator instead of comparison, expecting loose comparison versus strict comparison, switch statement issues with strict comparison, confusion between addition and concatenation, floating point precision problems, improper string breaking, semicolon misplacement, return statement breaking, array access with named indexes, array/object definition ending with commas, undefined versus null confusion, and block level scope expectations.
📝 Lecture Summary
Accidentally Using the Assignment Operator
JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment operator (=), instead of a comparison operator (==) in an if statement. When using x = 10 inside an if condition, JavaScript assigns the value 10 to x and returns true because 10 is a truthy value. Similarly, x = 0 returns false because 0 is falsy.
🔑 Definition — Assignment Operator: The = operator assigns a value to a variable, while == compares values.
📐 Formula: if (x = 10) → This assigns 10 to x and evaluates as true, instead of comparing x to 10
📌 Example:
var x = 0;
if (x = 10) // Returns true because 10 is truthy, x becomes 10
if (x = 0) // Returns false because 0 is falsy, x becomes 0
Expecting Loose Comparison
In regular comparison using ==, data type does not matter. In strict comparison using ===, data type does matter. This is a common source of bugs when developers expect type coercion to work in specific ways.
🔑 Definition — Loose vs Strict Comparison: == compares values after type conversion; === compares both value and type without conversion 📌 Example:
var x = 10;
var y = "10";
if (x == y) // Returns true (loose comparison)
if (x === y) // Returns false (strict comparison - different types)
Switch Statement
It is a common mistake to forget that switch statements use strict comparison. If the case value type doesn't match the variable type, the case won't execute.
📌 Example:
var x = 10;
switch(x) {
case 10: alert("Hello"); // Works - matches type and value
}
switch(x) {
case "10": alert("Hello"); // Won't work - string vs number
}
Confusing Addition & Concatenation
Addition is about adding numbers. Concatenation is about adding strings. In JavaScript both operations use the same + operator. When one operand is a string, JavaScript converts the other operand to a string and concatenates.
📌 Example:
var x = 10, y = 5;
var z = x + y; // z = 15 (numeric addition)
var x = 10, y = "5";
var z = x + y; // z = "105" (string concatenation)
Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). All programming languages have difficulties with precise floating point values.
📌 Example:
var x = 0.1, y = 0.2;
var z = x + y; // z will not be exactly 0.3
if (z == 0.3) // This if test will fail
var z = (x * 10 + y * 10) / 10; // Solution: multiply and divide to get 0.3
💡 Why this matters: Floating point precision issues cause calculation errors in financial and scientific applications if not handled properly.
Breaking a JavaScript String
JavaScript allows breaking a statement into two lines, but breaking a statement in the middle of a string will not work. You must use a backslash if you must break a string.
📌 Example:
var x = "Hello \
World!"; // Valid - backslash allows string continuation
// var x = "Hello // Invalid - string broken mid-value
// World!";
Misplacing Semicolon
Because of a misplaced semicolon, a code block will execute regardless of the value of x.
📌 Example:
if (x == 19); // Semicolon ends the if statement here
{ // This block always executes
// code block
}
Breaking a Return Statement
It is a default JavaScript behavior to automatically close a statement at the end of a line. If you break a return statement onto a new line, the function will return undefined.
📌 Example:
function myFunction(a) {
var power = 10;
return // JavaScript adds semicolon here automatically
a * power; // This line is never reached
// Function returns undefined
}
Accessing Arrays with Named Indexes
JavaScript does not support arrays with named indexes. Arrays use numbered indexes, while objects use named indexes. Using named indexes on an array will redefine the array to a standard object.
📌 Example:
var person = [];
person[0] = "John"; // Correct - numbered index
person["firstName"] = "John"; // Incorrect - converts array to object
var x = person.length; // Returns 0 for object
Ending an Array or Object Definition with a Comma
Trailing commas in array or object definitions can cause JSON and JavaScript engines to fail or behave unexpectedly.
📌 Incorrect:
points = [40, 100, 1, 5, 25, 10,]; // Trailing comma
person = {firstName:"John", lastName:"Doe", age:46,} // Trailing comma
📌 Correct:
points = [40, 100, 1, 5, 25, 10];
person = {firstName:"John", lastName:"Doe", age:46}
Undefined is Not Null
With JavaScript, null is for objects, undefined is for variables, properties, and methods. To be null, an object must be defined. You must test typeof() before checking if an object exists.
🔑 Definition — Null vs Undefined: null is an intentional absence of object value; undefined means a variable has been declared but not assigned a value
📌 Example:
// Incorrect - throws error if myObj is undefined
if (myObj !== null && typeof myObj !== "undefined")
// Correct - test typeof first
if (typeof myObj !== "undefined" && myObj !== null)
Expecting Block Level Scope
JavaScript does not create a new scope for each code block. Variables declared with var inside code blocks (like if statements or loops) are accessible outside those blocks. Block-level scoping with let and const was introduced in ES6.
⭐ Key Takeaways
Always use strict comparison (===) instead of loose comparison (==) to avoid unexpected type coercion, and never use assignment operators (=) in conditional statements. Remember that JavaScript uses strict comparison in switch statements and has automatic semicolon insertion that can break return statements. Arrays must use numbered indexes only, and objects use named indexes. Floating point arithmetic requires special handling through multiplication and division. Always test typeof() before checking if an object exists, and never end array or object definitions with trailing commas in JSON-compatible code.
🧠 Quick Revision Questions
- What is the difference between loose comparison (==) and strict comparison (===) in JavaScript?
- Why does
var z = 0.1 + 0.2not equal exactly 0.3, and how can this be fixed? - What happens when you use named indexes on an array instead of numbered indexes?
- Why does breaking a return statement onto a new line cause the function to return undefined?
- What is the correct order for checking if an object exists: should you check for null or typeof() first?
📘 Lecture 88 — JavaScript Global Functions and Properties
📖 Overview: This lecture introduces several global JavaScript properties and functions that are available across all built-in JavaScript objects. It explains the meaning and usage of properties like
Infinity,NaN, andundefined, and theeval()function, while also providing a caution about the deprecatedconstkeyword.
🗂️ Topics Covered
The lecture begins by warning against using the const keyword as it is not a standard part of older JavaScript versions (ES3 or ES5). It then defines the global properties Infinity, NaN, and undefined, followed by the eval() function with examples of how it evaluates expressions and executes statements. The lecture concludes by advising against the use of eval() unless absolutely necessary.
📝 Lecture Summary
Const is an extension to JavaScript. It is supported by the JavaScript engine used in Firefox and Chrome. But it is a part of the JavaScript standards ES3 or ES5. Do not use it.
const is an extension to JavaScript but is not part of the ECMAScript 3 (ES3) or ES5 standards. While supported in Firefox and Chrome, using it is not recommended because it may not be supported in all environments.
88- JavaScript Global Functions and Properties
The JavaScript global properties and functions can be used with all the built-in JavaScript objects. They are accessible from anywhere in your code without needing to reference a specific object.
🔑 Definition — Infinity: A numeric value that represents positive or negative infinity. It is displayed when a number exceeds the upper or lower limit of the floating point numbers. 🔑 Definition — NaN: The "Not-a-Number" value property. It indicates that a value is not a legal number. 🔑 Definition — undefined: Indicates that a variable has not been assigned a value.
🔑 Definition — eval(): A global function that evaluates a string and executes it as if it were script code. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
📌 Example: The eval() function can evaluate simple mathematical expressions or operations involving variables.
var x = 10;
var y = 20;
var a = eval("x * y"); // 200
var b = eval("2 + 2"); // 4
var c = eval("x + 17"); // 27
📌 Example: You can execute any JavaScript statement using eval().
💡 Why this matters: eval() can execute arbitrary code, which is a major security risk. It is not recommended to use it unless you have no other choice.
⭐ Key Takeaways
The lecture emphasizes that const is not part of the ES3 or ES5 standards and should be avoided for compatibility. It introduces the global properties Infinity, NaN, and undefined for handling numeric limits, illegal numbers, and unassigned variables. The eval() function is explained as a powerful but dangerous tool for executing string-based code. The primary takeaway is to understand these built-in features while being mindful of browser compatibility and security implications.
🧠 Quick Revision Questions
- Why is it recommended to avoid using the
constkeyword in JavaScript according to this lecture? - What does the global
NaNproperty represent, and when would it occur? - What is the primary purpose of the
eval()function? - Give an example of how the
Infinityproperty might be triggered in a JavaScript program. - What is the value of a variable that has been declared but has not been assigned a value?