- You can destructure an object in a function argument list
function vectorAdd({x: x1, y: y1}, {x: x2, y: y2}) {
return {x: x1 + x2, y: y1 + y2};
}
- Because you can treat functions as objects, you can effectively add properties to them as you would an array or any other object.
- If you wanted to use the function as a type of "cache" you could do so like this:
function factorial(n) {
if (Number.isInteger(n) && n > 0) {
if (!(n in factorial)) {
factorial[n] = n * factorial(n - 1);
}
return factorial[n];
} else {
return NaN;
}
}
- Here, we basically treat the function as a cache that will persist across all calls to the function, like so
factorial[1] = 1;
factorial(6) // => 720
factorial[5] // => 120; the call above caches this value
-
The
<output>
is a container element into which a site or app can inject the results of a calculation or the outcome of a user action- It's particularly helpful for forms, where you can use it to display the results of a calculation or the outcome of a user action
-
The
<p>
element represents a paragraph- They are block-level elements, and notably will automatically close if another block-level element is parse before the closing
</p>
tag
- They are block-level elements, and notably will automatically close if another block-level element is parse before the closing
-
The
<picture>
element is a container for zero or more<source>
elements and one<img>
element to offer alternative versions of an image for different display/device scenarios- The browser will consider each child
<source>
element and choose the best match among them - If no matches are found, the URL of the
<img>
element'ssrc
attribute is selected - The selected image is then presented in the space occupied by the
<img>
element - (Continued tomorrow)
- The browser will consider each child
- Boxes also have an inner display type, which dictates how elements inside that box are laid out
- There is normal flow, flex, and grid
- Parameter defaults enable functions to be invoked with fewer arguments than parameters
- Rest parameters enable functions to be invoked with more arguments than parameters
function max(first=-Infinity, ...rest) {
let maxValue = first; // Start by assuming the first arg is biggest
// Then loop through the rest of the arguments, looking for bigger ones
for (let n of rest) {
if (n > maxValue) {
maxValue = n;
}
}
// Finally return the biggest
return maxValue;
}
max(1, 10, 100, 2, 3, 1000, 4, 5); // => 1000
- A rest parameter is preceded by three periods, and it must be the last parameter in a function declaration
- The value of the rest parameter will always be an array within the body of the function
-
The
<ol>
element represents an ordered list of items, typically rendered as a numbered list- It accepts these common attributes:
reversed
: a Boolean attribute that indicates that the list should be displayed in reverse orderstart
: a number that specifies the starting value of the first list item in an ordered listtype
: a string that specifies the kind of marker to use in the list- The default value is
1
, which uses decimal numbers - Other possible values include
a
(lowercase letters),A
(uppercase letters),i
(lowercase Roman numerals), andI
(uppercase Roman numerals) - The specified type is used for the entire list unless a different
type
attribute is used on an enclosed<li>
element
- The default value is
- It accepts these common attributes:
-
The
<optgroup>
HTML element creates a grouping of options within a<select>
element- It can contain one or more
<option>
elements or<optgroup>
elements - It also accepts these attributes (in addition to the global attributes)
disabled
: a Boolean attribute that indicates that the option group is disabledlabel
: a string that provides a label for the option group
- It can contain one or more
-
The
<option>
element is used to define an item contained in a<select>
, an<optgroup>
or a<datalist>
element- Pertinent attribute include:
disabled
: a Boolean attribute that indicates that the option is disabledlabel
: a string that provides a label for the optionselected
: a Boolean attribute that indicates that the option is pre-selectedvalue
: a string that provides the value of the option
- Pertinent attribute include:
- Everything in CSS has a box around it
- The general categories of them fall into Block and Inline
- For Outer Display Types:
-
display: block
elements:- Break onto a new line
width
andheight
properties are respected- Padding, margin and border will cause other elements to be pushed away from the box
- If the
width
is not specified, the box will extend in the inline direction to fill the space available in its container
- If the
- Some elements, like
<h1>
and<p>
are block elements by default
-
display: inline
elements:- The box will not break onto a new line
- The
width
andheight
properties will not apply - Top and bottom padding, margins, and borders will apply but will not cause other inline boxes to move away from the box
- Left and right padding, margins, and borders will apply and will cause other inline boxes to move away from the box
- Elements like
<span>
,<em>
,<strong>
and<a>
are inline by default
-
- In ES6, you can define a default value for each function parameter directly in the parameter list of your function
function getPropertyNames(o, a = []) {
for (let property in o) a.push(property);
return a;
}
- You can also the value of a previous parameter to define the default value of the parameters that follow it:
const rectangle = (width, height = width * 2) => ({width, height});
rectangle(1) // => {width: 1, height: 2}
- This element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser
<noscript>
<!-- anchor linking to external file -->
<a href="https://www.mozilla.org"/>External Link</a>
</noscript>
<p>Rocks!</p>
- This element represents an external resource, which can be treated as an image, nested browsing context, or a resource to be handled by a plugin
<object type="application/pdf" data="/media/examples/In-CCO.pdf" width="250" height="200"></object>
- Relevant attributes:
data
: the URL of the resource to be embeddedform
: the form element that the object element is associated with (must be an ID of a<form>
element in the same document)height
: the height of the objecttype
: a content type specified by data
- Another advanced topic that you might not use right away but may need to understand in the future is
@scope
- This is an at-rule that enables you to create a block of rules that only apply to a specific subsection of the HTML on your page
- For example, you can specify styles that will only apply to
<img>
elements when they're nested inside elements that have afeature
class
@scope (.feature) {
img {
border: 1px solid black;
display: block;
}
}
-
Scoping proximity is the mechanism that resolves conflicts between scoped elements
-
It states that when two scopes have conflicting styles, the style with the smallest number of hops up the DOM tree to the scope root wins
-
Skills assessment: check the index.html and styles.css files for the rundown
- Cascade Layers are explicit specificity containers providing simpler and greater control over CSS declarations that ultimately get applied
- Javascript's binding of
this
is particularly finicky- Arrow functions automatically inherit the
this
value from the environment in which they are defined - Nested functions, however, do not
- Arrow functions automatically inherit the
let o = {
m: function () {
let self = this; // Save the this value in a variable
this === o // => true: this is the object o
f(); // Call f() as a regular function
function f() {
this === o // => false: this is the global object (in non-strict mode) or undefined (in strict mode)
self === o // => true: self is the outer this value
}
}
}
- In the method
m
, we can assign thethis
value to a variableself
, and within the nested functionf
, we can useself
instead of this to refer to the containing object - Inside the nested function
f()
, thethis
keyword is not equal to the objecto
, but rather the global object orundefined
in strict mode - This is widely considered to be a flaw in the Javascript language, and it is important to be aware of
- Another workaround is to use the
bind()
method to bind thethis
value to a function
const f = (function () {
this === 0 // true, since we bound this function to the outer this
}).bind(this);
-
Constructor functions do not normally use the
return
keyword- They instead initialize the new object and then return implicitly when they reach the end of their body
-
Indirect Invocation:
- All JS functions have two methods called
call()
andapply()
- These both invoke a function indirectly
- Both methods allow you to explicitly specify the
this
value for the invocation, which you can invoke any function as a method of any object, even if it is not actually a method of that object - Both allow you to specify the arguments to be passed to the function
call()
uses its own argument list as arguments to the functionapply()
expects an array of values to be passed as arguments to the function
- All JS functions have two methods called
- The
<meter>
represents a scalar value within a known range or a fractional valuevalue
attribute: the value of the scalar measurementmin
attribute: the lower bound of the rangemax
attribute: the upper bound of the rangelow
attribute: the upper bound of the low rangehigh
attribute: the lower bound of the high rangeoptimum
attribute: the optimal value of the gauge
-
When you declare CSS in cascade layers, the order of precedence is determined by the order in which the layers are declared
-
CSS styles declared outside any layer are combined, in the order in which those layers are declared, into an unnamed layer, as if it were the last layer declared
-
With competing normal (not important) styles, late layers take precedence over earlier defined layers
-
For styles flagged with
!important
, however, the order is reversed, with important styles in earlier layers taking precedence over important styles in later layers -
Inline styles take precedence over all author styles, no matter the layer
-
When you have multiple style blocks in different layers providing competing values for a property on a single element, the order in which the layers are declared determines the precedence
-
Specificity between layers doesn't matter, but specificity within a single layer does
-
Arrow functions inherit the value of
this
from the environment in which they are defined, rather than defining their own invocation context -
Arrow functions also differ from other functions in that they do not have a
prototype
property, which means they cannot be used as constructor functions for new classes -
Functions can be invoked in 5 ways:
- As functions
- As methods
- As constructors
- Indirectly through their
call()
andapply()
methods - Implicitly, via JS language features that do not appear like normal function invocations
-
Conditional invocation is possible, where you write
f?.(x)
// this is equivalent to
(f !== null && f !== undefined) ? f(x) : undefined
- Method function invocation binds
this
keyword to the invocation context of the object on which the method is called
- The
<meta>
element represents metadata that can't be represented by other HTML meta-related elements ( like<base>
,<link>
,<script>
,<style>
, ortitle
) - The type of metadata provided by the
<meta>
element can be one of the following:- If the
name
attribute is set, the<meta
element provides document-level metadata, applying to the whole page - If the
http-equiv
attribute is set, the<meta>
element is a pragma directive, providing information equivalent to what can be given by a similarly-named HTTP header - If the
charset
attribute is set, the<meta>
element is a charset declaration, giving the character encoding in which the document is encoded - If the
itemprop
attribute is set, the<meta>
element provides user-defined metadata
- If the
- It's possible for users to set custom stylesheets to override the developer's styles
- E.g., a visually impaired user might want to set the font size on all web pages they visit to be double the normal size to allow for easier reading
- Order of overriding declarations:
- Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:
- Declarations in user agent style sheets (e.g., the browser's default styles)
- Normal declarations in user style sheets (custom styles set by a user)
- Normal declarations in author style sheets (styles set by the developer)
- Important declarations in author style sheets
- Important declarations in user style sheets
- Important declarations in user agent style sheets
- Conflicting declarations will be applied in the following order, with later ones overriding earlier ones:
- In addition to function declarations, you can use a function expression
- Function expressions appear within the context of a larger expression or statement, and the name is optional
// This function expression defines a function that squares its argument
// Not that we assign it to a variable
const square = function (x) {
return x * x;
};
// Function expressions can include names, which is useful for recursion.
const f = function fact(x) {
if (x <= 1) return 1; else return x * fact(x - 1);
};
- The
<mark>
element represents text which is highlighted for reference or notation purposes due to the marked passage's relevance in the enclosing context - Do not use it purely for formatting purposes
- Also, most screen reading technologies do not announce the presence of the
<mark>
element by default, so you can add a::before
or::after
pseudo-element to make it known - Sometimes, screen readers will deliberately disabled announcing content that creates extra verbosity, so do not abuse this technique
- The
<menu>
element is described in the HTML as a semantic alternative to<ul>
, but treated by browsers (and exposed through the accessibility tree) as no different from a<ul>
- It represents an unordered list of items (which are represented by
<li>
elements) - Primarily,
<ul>
is used for display, while<menu>
is used for interactive items
- Inline styles take precedence over all normal styles, no matter the specificity
- There is a special piece of CSS that you can use to overrule all of the above calculations, even inline styles
- The
join()
method converts all elements of an array to strings at concatenates them, returning the resulting string- You can specify an optional string that separates the elements in the returned string
- If no separator string is specified, a comma is used
- This is effectively the inverse of
String.split()
- Arrays' inbuilt
toString()
method is effectivelyjoin()
with no arguments
- In addition to the static methods
Array.of()
andArray.from()
, there is an inbuiltArray.isArray()
which returns true/false depending on the value of the passed in argument
- Strings behave like read-only arrays of UTF-16 Unicode characters
- Instead of accessing individual characters with the
charAt()
method, you can use square brackets
let s = "test";
s.charAt(0) // => "t"
s[1] // => "e"
- Strings behaving like arrays also means that we can apply generic array methods to them
Array.prototype.join.call("Javascript", " ") // => "J a v a s c r i p t"
- Because strings are immutable values, so they are treated like read-only arrays
- Array methods like
push()
,sort()
,reverse()
, andsplice()
do not work on strings
- Functions defined using the
function
keyword are hoisted in a program, meaning they can be invoked before their definition in a block of code
- This is used to represent the dominant content of the
<body>
of a document - It consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application
- A document must not have more than one
<main>
element that doesn't have thehidden
attribute specified
- This element is used with the
<area>
element to define an image map (a clickable link area) - It must contain the
name
attribute with no space characters
- To further understand specificity as it pertains to CSS rule application, consider the following about selector
specificity:
- Identifiers: Score one in this column for each ID selector contained inside the overall selector.
- Classes: Score one in this column for each class selector, attribute selector, or pseudo-class contained inside the overall selector.
- Elements: Score one in this column for each element selector or pseudo-element contained inside the overall selector.
- Each of these search an array for an element with a specified value and return the index of the first such element found, or -1 if none is found
indexOf()
searches the array from the beginning, andlastIndexOf()
searches from the end- Each uses the
===
operator, so objects are compared by equivalent reference, not value - If you want to actually look at object contents, use
find()
with a custom predicate function - Each of these methods take an optional second argument, which is the index at which to begin the search
- This method takes a single argument and returns
true
if the array contains that value orfalse
otherwise - This method uses a slightly different version of equality that does consider
NaN
to be equal to itself - This means that
includes()
is a good way to check for the presence ofNaN
in an array, butindexOf()
is not
- This method sorts the elements of an array in place and returns the sorted array
- When called with no arguments, it sorts the array elements in alphabetical order (temporarily converting them to strings to perform the comparison, if necessary)
- Undefined elements are sorted to the end of the array
- If you want to sort an array of numbers, you must pass a comparison function as an argument
- If the first argument should appear after the second in the sorted array, the function should return a positive number
- If the first argument should appear before the second, the function should return a negative number
- If the two arguments are equal, the function should return 0
- An interesting example would be to sort an array of strings, with case ignored in the alphabetical comparison
let a = ["Banana", "apple", "Cherry", "decks"]
a.sort() // => ["Banana", "Cherry", "apple", "decks"]
a.sort((a, b) => {
let s = a.toLowerCase(), t = b.toLowerCase();
if (a > b) return 1
if (a < b) return -1
return 0
}) // => ["apple", "Banana", "Cherry", "decks"]
- This method reverse the order of the elements of an array and returns the reversed array
- It does this in place, or without creating a new array
- This specifies relationships between the current document and an external resourrce
- It's most commonly used to link to stylesheets, but also used to establish site icons
- It's placed inside the
<head>
element, like this
<link href="main.css" rel="stylesheet"/>
<link href="favicon.ico" rel="icon"/>
- Often times you can use the
rel
attribute to indicate special icon types for use on various mobile platforms sizes
attribute can be used to specify the size of the icontype
attribute can be used to specify the MIME type of the linked resource- You can also provide a media type or query inside a
media
attribute- This resource will then only be loaded if the media condition is true
- In ascending, the factors that apply the final styling to an element are:
- Source Order
- Specificity
- Important
- Source Order:
- If you have more than one rule, all of which have exactly the same weight, then the one that comes last in the CSS will win
- Source order only matters when the specificity weight of the rule is the same
- The
fill()
method sets the elements of an array, or a slice of an array, to a specified value - It mutates the array it's called on, and also returns the modified array
let a = new Array(5); // start the array with no elements and length 5
a.fill(0); // => [0, 0, 0, 0, 0]
a.fill(9, 1); // => [0, 9, 9, 9, 9]; fill with 9 starting at index 1
a.fill(8, 2, -1) // => [0, 9, 8, 8, 9]; fill with 8 starting at index 2 and ending at the second-to-last index
-
First argument is the value to fill
-
Second argument is the start index
- If omitted, the entire array will be filled
-
Third argument is the end index
- If omitted, the array will be filled to the end index
-
The
copyWithin()
method copies a slice of an array to a new position within the array -
It modifies the array in place and returns the modified array, but will not change the length of the array
-
First argument specifies the destination index to which the first element will be copied
-
The second argument is the index of the first element to be copied
- If this is omitted, 0 is used
-
The third argument specifies the end of the slice of elements to be copied
- If omitted, the length of the array is used
-
Elements from the start index up to, but not including, the end index will be copied
let a = [1, 2, 3, 4, 5];
a.copyWithin(1) // => [1, 1, 2, 3, 4]: copy the entire array to index 1
a.copyWithin(2, 3, 5) // => [1, 1, 3, 4, 4]: copy last 2 elements to index 2
a.copyWithin(0, -2) // => [4, 4, 3, 4, 4]: negative offsets work, too
- This represents a caption for the content of its parent
<fieldset>
<fieldset>
<legend>Choose your favorite monster</legend>
<input type="radio" id="kraken" name="monster" value="K"/>
<label for="kraken">Kraken</label><br/>
<input type="radio" id="sasquatch" name="monster" value="S"/>
<label for="sasquatch">Sasquatch</label><br/>
<input type="radio" id="mothman" name="monster" value="M"/>
<label for="mothman">Mothman</label>
</fieldset>
- Check this example out in
index.html
- Used to represent an item in a list
- Must be contained in a parent element: an unordered list or ordered list, or a menu
- Notable Attributes:
value
: this integer attribute indicates the current ordinal value of the list item as defined by the<ol>
element- The only allowed value for this attribute is a number, even if the list is displayed with Roman numerals or letters
- The CSS shorthand property
all
can be used to apply one of these inheritance values to (almost) all properties at once - Its value can be any one of the inheritance values (
inherit
,initial
,revert
,revert-layer
, orunset
)- It's a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes
- Example to follow on Monday
slice()
: theslice()
method returns a slice, or subarray of the specified array.- Its two arguments specify the start and end of the slice to be returned
- In includes the first argument index up to, but not including the second argument index
- If only one argument is specified, the returned array contains all elements from the argument index to the end of the array
- If either argument is negative, it specifies an array element relative to the length of the array
- An argument of -1, for example, specifies the last element of the array, and the element -2 specifies the element before that one
slice()
does not modify the array on which it is invoked
let a = [1, 2, 3, 4, 5]; a.slice(0, 3); // returns [1, 2, 3] a.slice(3); // returns [4, 5] a.slice(1, -1); // returns [2, 3, 4] a.slice(-3, -2); // returns [3]
splice()
is a general-purpose method for inserting or removing elements from an array- Unlike
slice()
andconcat()
,splice()
modifies the array on which it is invoked - The first argument to
splice()
specifies the array position at which the insertion and/or deletion is to begin - The second argument specifies the number of elements that should be deleted from (spliced out of) the array
- This is another key difference
- The second argument to
slice()
is an end index - The second argument to
splice()
is a length
- The second argument to
- This is another key difference
let a = [1, 2, 3, 4, 5, 6, 7, 8]; a.splice(4) // => [5, 6, 7, 8]; a is now [1, 2, 3, 4] a.splice(1, 2) // => [2, 3]; a is now [1, 4] a.splice(1, 1) // [4]; a is now [1]
- The first two arguments to
splice()
specify the position and number of elements to delete - The arguments can be followed by any number of arguments that specify elements to be inserted at the point of the first argument in the array
let a = [1, 2, 3, 4, 5]; a.splice(2, 0, "a", "b") // []; a is now [1, 2, "a", "b", 3, 4, 5] a.splice(2, 2, [1, 2], 3) // ["a", "b"] a is now [1, 2, [1, 2], 3, 3, 4, 5]
- Unlike
- Associating a
<label>
with a form control, such as<input>
or<textarea>
offers some major advantages- The label is not just visually, but programmatically associated with its control, allowing screen readers to dictate the content more accurately
- Tapping/touching the label propagates the focus to the associated input, allowing for a larger hit area on a control or textarea
- To associate a label with a text input, you first add an
id
to the associated input - Next, you add the
for
attribute to the label with the matchingid
- Don't add interactive anchor tags or buttons inside a label, instead use the
for
attribute to associate the label with the input - Don't add headers or similar elements for the sake of styling, instead use CSS to achieve such effects
- Properties like
width
,margin
,padding
, andborder
are not inherited properties - You can often guess whether a property will be inherited if you know what aspect the property value will style
- CSS provides five universal property values for controlling inheritance. Every CSS property accepts these values
inherit
: sets the property value applied for a selected element to the same as that of its parent element. This "turns on" inheritanceinitial
: sets the property value to its default valuerevert
: resets the property value to the browser's default styling rather than the defaults applied to that property. This value acts likeunset
in many casesrevert-layer
: resets the property value applied to a selected element to the value established in a previous cascade layerunset
: resets the property value to its inherited value if it inherits, or to its default value if it does not
-
These work by iterating over arrays and calling a function you provide for each element
-
If an array is sparse, the function you pass is not invoked for nonexistent elements
-
The
forEach()
Method- The argument is the function to be invoked for each element
- The function can have three parameters
- The value of the element
- The index of the element
- The array object being traversed
- If you want to ignore parameters, you can simply use the first parameter
let data = [1, 2, 3, 4, 5], sum = 0; data.forEach(value => { sum += value}) // sum == 15 data.forEach((v, i, a) => { a[i] = v + 1;}) // data == [2, 3, 4, 5, 6]
- Note that
forEach()
does not provide a way to terminate iteration before all elements have been passed to the function, like abreak
statement in afor
loop
-
The
map()
Method- This passes each element of the array on which is invoked to the function you specify and returns an array containing the values returned by your function
- The function you pass should return a value
- The function returns a new array: it does not modify the array it is invoked on
- If the array is sparse, the function won't be called on missing elements, but the returned array will be sparse in the same way as the original array (with the same length and missing elements)
-
The
filter()
Method- This method returns an array containing a subset of the elements of the original array
- The function you pass should be a "predicate", returning
true
orfalse
- The return value is always a
dense
array, and missing elements from sparse arrays will be skipped - To close a sparse array, you could do this
let dense = sparse.filter(() => true); a = a.filter(x => x !== undefined && x !== null) // this is a way to remove undefined and null, and close gaps
-
find()
andfindIndex()
- These work like
filter()
in that they iterate through your array looking for elements for which your predicate function returns a truthy value - Unlike
filter
, they stop iterating the first time the predicate finds an element find()
returns the first found element, andfindIndex()
returns the index of the matching element- If no matching element is found
find()
returns undefined andfindIndex()
returns -1
- If no matching element is found
- These work like
-
every()
andsome()
- These are array predicates: they apply a predicate function you specify to the elements of the array, then
return
true
andfalse
- The
every()
method is like a mathematical "for all" quantifier, returning true only if your predicate returns true to all elements in the array - The
some()
method is like a mathematical "there exists" quantifier, returning true if there exists at least one element in the array for which the predicate returns true, and false otherwise - Note that both
every()
andsome()
stop iterating elements as soon as they know what to return- Some returns
true
as soon as one element returnstrue
, andevery()
returnsfalse
as soon as one element returnsfalse
- Some returns
- Note also that
every()
returns true andsome()
returns false for empty arrays, by mathematical convention
- These are array predicates: they apply a predicate function you specify to the elements of the array, then
return
-
reduce()
andreduceRight()
- These combine the elements of an array, using the function you specify, to produce a single value
- This is a common operation in functional programming and also goes by the names "inject" and "fold"
- The
reduce()
function takes two arguments- The first is the function that performs the reduction operation
- The task of this function is to somehow combine or reduce two values into a single value and to return that reduced value
- The second (optional) argument is an initial value to pass to the function
- Functions used with
reduce()
are different than the functions used withforEach()
andmap()
- The familiar value, index, and array values are passed as the second, third, and fourth arguments
- The first argument is the accumulated result of the reduction so far
- On the first call to the function, the first argument is the initial value you passed as the second
argument to
reduce()
- On subsequent calls, it is the value returned by the previous call to the function
- On the first call to the function, the first argument is the initial value you passed as the second
argument to
- Calling
reduce()
on an empty array with no initial value argument causes aTypeError
- If you call it on an array with only one value (either one element in an array and no initial value, or an element array and an intial value), it simply returns that one value without ever calling the reduction function
- The first is the function that performs the reduction operation
- The
reduceRight()
method works just likereduce()
, except that it processes the array from highest index to lowest (right-to-left)
-
flat()
andflatMap()
flat()
creates and returns a new array that contains the same elements as the array it is called on, except that any elements that are themselves arrays are "flattened" into the return array[1, [2, 3]].flat() // => [1, 2, 3] [1, [2, [3]]].flat() // => [1, 2, [3]]
- When calls with no arguments,
flat()
flattens one level of nesting - If you want to flatten more levels, pass a number to
flat()
- When calls with no arguments,
flatMap()
works just likemap()
but the returned array is automatically flattened as if passed toflat()
- In other words,
a.flatMap(f)
is a shorthand fora.map(f).flat()
- In other words,
-
The
concat()
method creates and returns a new array that contains the elements of the original array on whichconcat()
was invoked, followed by each of the arguments passed intoconcat()
- If any of these arguments is itself an array, then the elements of that array are concatenated rather than the array itself
- Note that it will only flatten the outermost arguments passed in, and not any nested arrays
- Note that
concat()
creates a new copy of the array it is called on- Because this can be an expensive operation, consider using
push()
orsplice()
instead of creating a new one
- Because this can be an expensive operation, consider using
-
The
push()
andpop()
methods allow you to work with arrays as if they were stackspush()
adds one or more elements to the end of an array, and returns the new length of the array- Unlike
concat()
,push()
does not flatten array arguments
- Unlike
pop()
removes the last element of an array, decrements the length of the array, and returns the removed value- Both methods modify the array in place
- The
push()
method does not flatten an array you pass to it, but if you want to push all of the elements from one array onto another array, you can use the spread operator to flatten it explicitly
a.push(...values);
-
The
unshift()
andshift()
methods behave much likepush()
andpop()
, except that they insert and remove elements from the beginning of an array rather than from the endunshift()
adds an element or elements to the beginning of the array, shifts the existing array elements up t higher indexes to make room, and returns the new length of the arrayshift()
removes and returns the first element of the array, shifting all subsequent elements down one place to occupy the newly vacant space at the start of the array- You could use
unshift()
andshift()
to implement a stack, but it would be less efficient that usingpush()
andpop()
due to the moving of elements - Instead, you can implement a queue data structure by using
push()
to add elements at the end of an array andshift()
to remove them from the start of the array - Keep in mind that if you use
unshift()
with multiple elements, all of them will be inserted at once, which will cause a different ordering of the elements than unshifting them one at a time
let a = [] // a == [] a.unshift(1) // a == [1] a.unshift(2) // a == [2, 1] a = [] a.unshift(1, 2) // a == [1, 2]
- The
<ins>
element represents a range of text that has been added to a document- You can use the
<del>
element to similarly represent a range of text that has been deleted from the document - The presence of the
<ins>
element is not announced by most screen reading technology in its default configuration - It can be made to be announced by using the CSS
content
property, along with the::before
and::after
pseudo-elementsins::before, ins::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } ins::before { content: " [insertion start] "; } ins::after { content: " [insertion end] "; }
- You can use the
- The
<kbd>
or Keyboard Input Element- This represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device
- Nesting a
<kbd>
element within another<kbd>
element represents an actual key or other unit of input as a portion of larger input - Nesting a
<kbd>
element inside a<samp>
element represents input that has been echoed back to the user by the system - Nesting a
<samp>
element inside a<kbd>
element represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen
- This topic controls how CSS is applied to HTML and how conflicts between style declarations are resolved
- Stylesheets cascade, which means the origin, the cascade layer, and the order of CSS rules matter
- When two rules from the same cascade layer apply and both have equal specificity, the one that is defined last in
the stylesheet is the one that will be used
h1 { color: red; } h1 { color: blue; }
- In this case the rules are from the same source, have an identical element selector, and therefore carry the same specificity, but the last one in the source order wins
- When two rules from the same cascade layer apply and both have equal specificity, the one that is defined last in
the stylesheet is the one that will be used
- Specificity is the algorithm that the browser uses to decide which property value is applied to an element
- If multiple style blocks have different selectors that configure the same property with different values and target the same element, specificity decides the property value that gets applied to the element
- An element selector is less specific. It will select all elements of that type that appear on a page, so it has
less weight
- Pseudo-element selectors have the same specificity as regular element selectors
- A class selector is more specific, so it has more weight
- Attribute selectors and pseudo-classes have the same weight as a class
.main-heading { color: red; } h1 { color: blue; }
- In this case, the class selector is more specific than the element selector, so the color of the
.main-heading
class will be red
- Inheritance - some property values set on parent elements are inherited by their child elements, and some aren't
- E.g., if you set a
color
andfont-family
on an element, every element inside it will also be styled with that color and font, unless you've applied different values directly to them - Some properties do not inherit, so if you set a
width
of 50% on an element, all of its descendants do not get a width of 50% of their parent's width- If this was the case, CSS would be super frustrating and require much more styling
- E.g., if you set a
- Arrays are a specialized kind of object
- The square brackets used to access array elements work just like the square brackets used to access object properties
- JS converts the numeric array index you specify to a string–the index 1 becomes the string "1", then uses that string as a property name
let o = {};
o[1] = "one";
o["1"] // => "one"; numeric and string property names are the same
- All indexes are property names, but only property names that are integers between 0 and 2^32 - 2 are indexes
- All arrays are objects, and you can create properties of any name on them
- If you use properties that are array indexes, however, arrays have the special behavior of updating their length property as needed
- Note that you can index an array using numbers that are negative or that are not integers
- In this case, they are simply stores as properties of the array object, and do not affect the
length
property
- In this case, they are simply stores as properties of the array object, and do not affect the
- If you index an array with a string that happens to be a non-negative integer, it behaves as an array index, not an object property
a[-1.23] = true; // this creates a property names "-1.23"
a["1000"] = 0; // this sets the 1000th element of the array
a[1.000] // Array index 1. same as a[1] = 1
- Sparse arrays have a length value greater than the number of elements
- If you assign a value to an array whose index i is greater than or equal to the array's current
length
, the value of thelength
property is set toi + 1
- In order to maintain the length invariant is that, if you set the length property to a non-negative integer
n
smaller than its current value, any array elements whose index is greater than or equal ton
are deleted from the array:
a = [1, 2, 3, 4, 5];
a.length = 3;
a.length = 0; // deletes all elements
a.length = 5; // length is 5, but no elements, like new Array(5)
- Pushing a value onto an array is the same as assigning the value to
a[a.length]
- You can use the
unshift()
method to insert a value at the beginning of an array - The
pop()
method is the opposite ofpush()
, removing the last element of the array and returning it - Similarly the
shift()
method removes and returns the first element of the array, reducing the length by 1 and shifting all elements down to an index one lower than their current index - You can delete array elements with the
delete
operator, just as you can delete object properties
let a = [1, 2, 3]
delete a[2] // a now has no element at index 2
2 in a // => false: no array index 2 is defined
a.length // => 3: delete does not affect array length
- If you delete an element from an array, it becomes sparse
splice()
is the general purpose method for inserting, deleting, or replacing array elements- It alters the length property and shifts array elements to higher or lower indexes as needed
- The
for/of
loop returns the elements of an array in ascending order- It has no special behavior for sparse arrays and simply returns
undefined
for any array elements that do not exist - If you want to use a
for/of
loop for an array and need to know the index os each array element, use theentries()
method of the array, along with destructuring assignment, like this:
- It has no special behavior for sparse arrays and simply returns
let everyother = "";
for (let [index, letter] of letters.entries()) {
if (index % 2 === 0) everyother += letter;
}
- Another good way to iterate arrays is with
forEach()
- This is not a new form of the
for
loop, but an array method that offers a functional approach to array iteration - It iterates the array in order, and actually passes the array index to your function as a second argument
- Unlike the
for/of
loop, theforEach()
function is aware of sparse arrays and does not invoke your function for elements that are not there
- This is not a new form of the
- Sometimes, good ole-fashioned iteration is useful, using a standard
for
loop
- JS does not have true multidimensional arrays, but you can simulate them with arrays of arrays
- The
<input>
element is used to create interactive controls for web-based forms in order to accept data from the user- More Types include:
number
: a control for entering a number. Displays a spinner and adds default validation, displays a numeric keypad in some devices with dynamic keypadspassword
: a single-line text field whose value is obscured. Will alert user if site is not secureradio
: a radio button, allowing a single value to be selected out of multiple choices with the samename
valuerange
: a control for entering a number whose exact value is not important. Displays as a range widget default to the middle value. Used in conjunction withmin
andmax
to define the range of acceptable valuesreset
: a button that resets the contents of the form to default valuessearch
: a single line text field for entering search strings. Line-breaks are automatically removed from the input value. May include a delete icon in supporting browsers that can be used to clear the field. Displays a search icon instead of enter key on some devices with dynamic keypadssubmit
: a button that submits the formtel
: a control for entering a telephone number. Displays a telephone keypad in some devices with dynamic keypadstext
: a single-line text field. Line-breaks are automatically removed from the input valuetime
: a control for entering a time value with no time zone. Displays a time picker or numeric wheels for hours and minutes when active in supporting browsersurl
: a field for editing a URL. It looks like atext
input, but has validation parameters and a keyboard optimized for URL entryweek
: a control for entering a date consisting of a week-year number and a week number within that year. Displays a week picker or numeric wheels for week and year when active in supporting browsers
- More Types include:
- For CSS today, I am completing the Selectors Assessment tasks
Array.of()
enables you to input arguments and allow them to be the elements of the newly created array (even if there is just one- Using the
Array
constructor with a single numeric argument will create an array with that length, not with that element
- Using the
Array.from()
is another ES6 factory function- It takes an Array-like or iterable object and returns an array that contains the same elements
- It is also a simple way to create a shallow copy of an array
- This function is important because it allows for the copying of Array-like objects
- This function also allows for a second argument, which is a function to be applied to each element being passed
into the array
- In other words, you can perform mapping as you're building your new array
- Array-like Objects are objects who have a numeric length property defined, along with properties whose names happen
to integers
- These are somewhat common as return-types for built-in browser methods
- The
<input>
element is used to create interactive controls for web-based forms in order to accept data from the user - Within it, a multitude of data and control widgets are available, depending on the client's device and user agent
- Types include:
button
: A push button with no default behavior, displaying the value of thevalue
attribute, and nothing by defaultcheckbox
: A check box allowing single values to be selected/deselectedcolor
: A control for specifying a color, which opens a color picker in supporting browsersdate
: a control for entering a date (year, month, and day, with no time). opens a date picker or numeric wheels for years, months and day when active in supporting browsersdatetime-local
: A control for entering a date and time, with no time zone. Opens a date picker or numeric wheels for date- and time-components when active in supporting browsersemail
: A field for editing an e-mail address. It looks like atext
input, but has validation parameters and a keyboard optimized for email addressesfile
: A control that lets the user select a file. Use theaccept
attribute to define the types of files that the control can selecthidden
: A control that is not displayed but whose value is submitted to the server. Useful for form honey-pots!image
: A graphical submit button. You must use thesrc
attribute to define the source of the image and thealt
attribute to define alternative textmonth
: A control for entering a month and year, with no time zone. Opens a date picker or numeric wheels for month and year when active in supporting browsers
- Types include:
- Before completing the combinator/selector assessment tomorrow, here's a bite-sized tidbit:
- The
::selection
pseudo-element applies styles to the portion of a document that has been highlighted by the user
- The
let p = {
// x and y are regular read-write data properties. x: 1.0,
y: 1.0,
// r is a read-write accessor property with getter and setter.
// Don't forget to put a comma after accessor methods.
get r() {
return Math.hypot(this.x, this.y);
}, set r(newvalue) {
let oldvalue = Math.hypot(this.x, this.y);
let ratio = newvalue / oldvalue;
this.x *= ratio;
this.y *= ratio;
},
// theta is a read-only accessor property with getter only.
get theta() {
return Math.atan2(this.y, this.x);
}
};
p.r // => Math.SQRT2 p.theta // => Math.PI / 4
- This object has data properties to represent the x and y coordinates of the point, and it has accessor properties that give the equivalent polar coordinates of the point
- The code uses accessor properties to define an API that provides two representations (Cartesian coordinates and polar coordinates) of a single set of data
- Other reasons to use accessor properties include sanity checking of property writes and returning different values on each property read:
// This object generates strictly increasing serial numbers
const serialnum = {
// This data property holds the next serial number. // The _ in the property name hints that it is for internal use only.
_n: 0,
// Return the current value and increment it
get next() {
return this._n++;
},
// Set a new value of n, but only if it is larger than current
set next(n) {
if (n > this._n) this._n = n;
else throw new Error("serial number can only be set to a larger value");
}
};
serialnum.next = 10;
serialnum.next
serialnum.next
// Set the starting serial number
// => 10
// => 11: different value each time we get next
- Arrays use 32-bit indexs, so the first element is index 0, and the maximum available index is 2^32 - 2, for a maximum array size of 4,294,967,295 elements
- JS arrays are dynamic, they grow or shrink as needed, and there is no need to declare a fixed size for the array when you create it or reallocate it when the size changes
- JS arrays may be sparse (the elements need not have contiguous indexes, and there may be gaps
- Every array has a
length
property - For sparse arrays,
length
is larger than the highest index of any element (it will be the length of the array if all elements were contiguous) - JS arrays are specialized forms of JS objects, and array indexes are object property names
- Implementations of arrays are typically optimized so that accessing numerically indexed array elements is generally significantly faster than access to regular object properties
- Arrays inherit properties from
Array.prototype
, which defines a rich set of array manipulation methods - JS strings behave like arrays of characters
- ES6 introduces a set of new array classes known as
typed arrays
- Unlike regular JS arrays, typed arrays have a fixed length and a fixed numeric element type
- They offer high performance and byte-level access to binary data
- There are several ways to create arrays:
- Array literals
- Very simple, just a comma-separated list of elements within square brackets
- The
...
spread operator on an iterable objectlet a = [1, 2, 3]; let b = [0, ...a, 4];
- The dots "spread" the elements of the array
a
so that a is replaced by its elements - The operator is a convenient way to create a shallow copy of an array
let original = [1,2,3]; let copy = [...original]; copy[0] = 0; // Modifying the copy does not change the original original[0] // => 1
- The dots "spread" the elements of the array
- The
Array()
constructor- This is almost always superceded by the ease/functionality of the Array Literal Syntax
- But, you can create an array like
this:
let a = new Array(10); // this would create an array with 10 undefined elements
- Note that no values are stored in the array, and the array index properties "0" and "1" and so on are not even defined for the array
- Explicitly specify two or more array elements or a single non-numeric element for the array:
let a = new Array(5, 4, 3, 2, 1, 'testing', 'testing'); // => [5, 4, 3, 2, 1, 'testing', 'testing']
- The
Array.of()
andArray.from()
factory methods- Since the
Array()
constructor will interpret a single numeric element as a length, and multiple elements are array elements, this means you cannot simply create an Array with one numeric element using the constructor
- Since the
- Array literals
- The
<img>
element embeds an image into the document- The
src
attribute is required, and contains the path to the image you want to embed - The
alt
attribute is also required, and incredibly useful for accessibility - Supported image formats:
- APNG, BMP, GIF, JPEG, PNG, SVG, WebP
- The
- The descendant combinator, typically represented by a single space character, combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, etc.) element matching the first selector
body article p {
color: red;
}
- The child combinator, represented by the
>
character, matches only elements that are direct children of a parent element
article > p {
color: red;
}
- The next sibling combinator, represented by the
+
character, selects only the element that is immediately preceded by the former element - For example, to select all
<img>
elements that are immediately preceded by a<p>
element
p + img {
margin-top: 20px;
}
- The subsequent-sibling combinator, which selects all elements that follow (at any distance) the former sibling element
p ~ img {
margin-top: 20px;
}
- When a function is defined as a property of an object, we call it a method
- In ES6, the object literal syntax (and also class definition syntax we'll see in Chapter 9) has been extended to allow a shortcut where the function keyword and the colon are omitted
let square = {
area() {
return this.side * this.side;
},
side: 10
};
square.area() // => 100
- All of the object properties discussed up til now are data properties
- JS also supports accessor properties (getters and setters), which do not have a single value but instead have one or two accessor methods: a getter and/or a setter
- If a property has both a getter and a setter method, it is a read/write property
- If it has only a setter method, it is a write-only property (something that is not possible with data properties)
- Attempts to read it always evaluate to undefined
- This represents a nested browsing context, embedding another HTML page into the current one
- Each embedded browsing context has its own document and allows URL navigations
- The navigations of each embedded browsing context are linearized into the session history of the topmost browsing context
- The topmost browsing context, the one with no parent, is usually the browser window, represented by the
Window
object - Relevant attributes:
allow
: specifies a permissions policy for the<iframe>
allowfullscreen
browsingtopics
: specifies that the selected topics for the current user should be sent with the request for the<iframe>
's sources. See more under theTopics API
credentialless
: set totrue
means that content will be loaded in a new, ephemeral context. It doesn't have access to the network, cookies, and storage data associated with its origincsp
: a Content security policy enforced for the embedded resourcereferrerpolicy
: indicates which referrer to send when fetching the frame's resourcesandbox
: controls the restriction applied to the content embedded in the<iframe>
- A pseudo-class is a selector that selects elements that are in a specific state, e.g., they are the first element of their type, or they are being hovered over by the mouse pointer
- E.g.
:hover
is a pseudo-class - Other pseudo-classes
are
:hover
,:focus
,:first-child
,:last-child
,:nth-child()
,:nth-last-child()
,:nth-of-type()
,:nth-last-of-type()
,:first-of-type
,:last-of-type
,:only-child
,:only-of-type
,:empty
,:not()
,:target
,:enabled
,:disabled
,:checked
,:default
,:valid
,:invalid
,:in-range
,:out-of-range
,:required
,:optional
,:read-only
,:read-write
,:placeholder-shown
,:root
,:scope
,:user-invalid
,:blank
,:nth-match()
,:nth-last-match()
,:current
,:past
,:future
,:active
,
- Pseudo-elements behave in a similar way, but as if you added a whole new HTML element into the markup, rather than applying a class to existing elements
- Pseudo-elements start with a double colon
::
- An example is
::first-line
, which will automatically select and style the first line of a text element and style it as though it had a special span with a class name assigned to it - There are a couple of special pseudo-elements, which are used along with the
content
property to insert content into your document using CSS - The use of
::before
and::after
pseudo-elements along with thecontent
property is referred to as "Generated Content" in CSS
- In JS, you can assign variable properties to an object the following way:
let x = 1, y = 2;
let o = {
x: x,
y: y
};
- In ES6, you can use shorthand property names to simplify this process
let x = 1, y = 2;
let o = {x, y};
- Sometimes you need to create an object with a specific property, but the name of that property is not a compile-time constant that you can type literally in your source code
- Instead, the property name you need is stored in a variable or is the return value of a function that you invoke
- You can't use a basic object literal for this kind of property
- Instead, you have to create an object and then add the desired properties as an extra step:
const PROPERTY_NAME = "p1";
function computePropertyName() {
return "p" + 2
}
let o = {};
o[PROPERTY_NAME] = 1;
o[computePropertyName()] = 2;
- In ES6, you can use computed property names to simplify this process
const PROPERTY_NAME = "p1";
function computePropertyName() {
return "p" + 2
}
let p = {
[PROPERTY_NAME]: 1,
[computePropertyName()]: 2
};
- The Computed Property syntax also enables you to use Symbol values as property names
const extension = Symbol("my extension symbol");
let o = {
[extension]: { /* extension data here */}
};
- Symbols are opaque values. You can't do anything with them other than use them as property names
- Every symbol is different from every other symbol, which means that they are good for creating unique property names
- Symbols are primitives, not objects, so
Symbol()
is not a constructor function that you invoke withnew
- Creating a
Symbol
s with identical strings will still yield different symbols - The string returned by
Symbol.toString()
is not the same as the string you passed toSymbol()
- The point of symbols is not security, but to define a safe extension mechanism for JS objects
- If you received a 3rd-party object and wanted to add a property to it, you could use a symbol as the property name to avoid any chance of a name collision
- The spread operator will copy properties of an existing object into a new object using the "spread" operator
...
inside an object literal
let position = {x: 1, y: 3};
let dimensions = {width: 100, height: 75};
let rect = {...position, ...dimensions};
rect.x + rect.y + rect.width + rect.height // => 179
dimensions.height = 50;
rect.height // => 75: the rect object has its own copy of the height property
- If the object that is spread and the object it is being spread into both have a property with the same name, then the value of that property will be the one that comes last:
let o = {x: 1};
let p = {x: 0, ...o};
p.x // => 1: the value from object o overrides the initial value
let q = {...o, x: 2};
q.x // => 2: the value 2 overrides the previous value from o.
- In addition to the basic
toString()
method, objects all have atoLocaleString()
- The default
toLocaleString()
method defined by Object doesn't do any localization itself - It simply calls
toString()
and returns that value - The Date and Number classes define customized versions of
toLocaleString()
that attempts to format numbers, dates, and times according to local conventions
- The default
- The
valueOf()
method is much like the `toString() method, but it is called when JS needs to convert an object to some primitive type other than a string (typically, a number)- You can define your own
valueOf()
method for your own classes, like defining a customvalueOf()
method below
let point = { x: 1, y: 1, valueOf: function() { return Math.hypot(this.x, this.y); } };
- Date class does something similar, where it converts all times into their millisecond distance from Jan 1 1970 for
direct date comparison using the
<
or>
operators
- You can define your own
- The
toJSON()
method:Object.prototype
does not actually define atoJSON()
method, butJSON.stringify()
looks for atoJSON()
method on any object it is asked to serialize- If the method exists, it is invoked, and the return value is serialized, instead of the original object
- The
<hgroup>
HTML element represents a heading and related content.- It groups a single
<h1>-<h6>
element with one of more<p>
elements - The
<hgroup>
presently has no strong accessibility semantics - The content of the element (a heading and optional paragraphs) is what is exposed by browser accessibility APIs)
- It groups a single
- The
<hr>
element is the Thematic Break (Horizontal Rule) element- It represents a thematic break between paragraph-level elements
- For example, a change of scene in a story, or a shift of topic within a section
- Historically, this has been presented as a horizontal rule or line
- While it may still be displayed as a horizontal rule in visual browsers, this element is now defined in semantic terms, rather than presentation terms
- If you solely wish to draw a horizontal line, you should do so using appropriate CSS
- The
<html>
or HTML Document/Root element represents the top-level element in an HTML document.- While HTML does not require authors to specify
<html>
element start and ending tags, doing so allows you to specify thelang
attribute for the webpage
- While HTML does not require authors to specify
- The
<i>
element (or Idiomatic Text Element) represents a range of text that is set off from the normal text for some reason- Examples are idiomatic text, technical terms, taxonomical designations, among others
- In earlier versions of the HTML specification, the
<i>
element was merely a presentation element used to display text in italics, much like the<b>
element was used for bold letters - These tags now define semantics rather than appearance.
- A gentle reminder for the appropriate markup for alternative text:
- Use
<em>
to indicate stress emphasis. - Use
<strong>
to indicate importance, seriousness, or urgency. - Use
<mark>
to indicate relevance. - Use
<cite>
to mark up the name of a work, such as a book, play, or song. - Use
<dfn>
to mark up the defining instance of a term.
- Use
- Substring Match Selectors:
- For more advanced matching of attribute values, you can use these substring match selectors
[attr^=value]
- Selects elements that have theattr
attribute with a value that begins exactly withvalue
[attr$=value]
- Selects elements that have theattr
attribute with a value that ends exactly withvalue
[attr*=value]
- Selects elements that have theattr
attribute with a value containing the substringvalue
- It may help to note that
^
and$
are the symbols for the beginning and end of a string, in RegExp respectively - If you want to match attribute values case-insensitively you can use the value
i
before the closing bracket- For example,
[attr^="value" i]
would matchvalue
,Value
,VALUE
, etc.
- For example,
- For more advanced matching of attribute values, you can use these substring match selectors
- Object serialization is the process of converting an object's state to a string from which it can later be restored
JSON.stringify()
andJSON.parse()
serialize and restore JavaScript objects
- JSON is a subset of JS syntax, and it can't represent all JS values
- Objects, arrays, strings, finite numbers,
true
,false
, and null are supported and can be serialized and restored NaN
,Infinity
,-Infinity
are not supported and will be serialized tonull
- Date objects are serialized to ISO-formatted date strings (see the
Date.toJSON()
function), butJSON.parse()
leaves these in string form and does not restore the original Date object - Function, RegExp, and Error objects and the
undefined
value cannot be serialized or restored JSON.stringify()
serializes only the enumerable own properties of an object
- Objects, arrays, strings, finite numbers,
- All JS objects (except those explicitly created without a prototype) inherit properties from Object.prototype
- These inherited properties are primarily methods, and because they are universally available they are of particular interest to JS programmers
- The
toString()
method takes no arguments; it returns a string that represents the value of the object on which it is invoked- JS invokes this method of an object whenever it needs to convert the object to a string
- This occurs, for example, when you use the + operator to concatenate a string with an object or when you pass an object to a method that expects a string
- The
<head>
element contains machine-readable information (metadata) about the document, like its title, scripts, and style sheets - The
<header>
element represents introductory content, typically a group of introductory or navigational aids- It may also have a logo, a search form, an author name, and other elements
- The header has identical meaning to the site-wide banner, unless nested within sectioning content
- In this case the
<header>
element is not a landmark - The
banner
ARIA role is intended to be used in the context of a site-wide header, such as a masthead- Unless a
<header>
is a descendant of an<aside>
,<footer>
,<article>
, or<nav>
, it is considered a site-wide header
- Unless a
- Attribute Selectors
- These selectors enable the selection of an element based on the presence of an attribute alone, or on various
matches against the value of the attribute
[attr]
, examplea[title]
matches elements with anattr
attribute[attr=value]
, examplea[href="https://www.example.com"]
matches elements with anattr
that is exactlyvalue
[attr~=value]
, examplea[rel~="external"]
matches elements with exactly theattr
, or contains the attribute in its space separated list of values[attr|=value]
, examplea[lang|="en"]
matches elements with exactly theattr
, or with the attribute followed by a hyphen and more characters
- These selectors enable the selection of an element based on the presence of an attribute alone, or on various
matches against the value of the attribute
- A common operation in JS is to copy properties of one object to another object
- It is easy to do that with code like this
let target = {x: 1}, source = {y: 2, z: 3}; for (let key of Object.keys(source)) { target[key] = source[key]; } target // => {x: 1, y: 2, z: 3}
- Because this is a common operation, various JS frameworks have defined utility functions, often named
extend()
to perform this copying operation - In ES6, this ability comes as
Object.assign()
- For each source object, it copies enumerable own properties of that object (including Symbol-named ones) and assigns them to the target object
- It also copies properties with ordinary property get and set operations, so if a source has a getter or a target has a setter, they will be invoked during the copy, but will not be copied themselves
- If you wanted to copy default properties to an object only if the target did not have that existing property, you would NOT want to do this
Object.assign(o, defaults); // overwrites everything in o with defaults
- Instead, you would want to do this
o = Object.assign({}, defaults, o); // applies defaults to an empty object, then assigns existing properties from o last, overriding defaults
- You can also express this object-copy-and-override operation using spread operators
o = {...defaults, ...o}; // same as above
- Object serialization is the process of converting an object's state to a string from which is can later be restored
- The functions
JSON.stringify()
andJSON.parse()
serialize and restore JavaScript objects
- The
<form>
element is used to submit information to some aspect of an application (normally a remote server)- Pertinent attributes:
accept-charset
: specifies the character encodings that are to be used for the form submissionautocapitalize
: specifies whether the form should have autocapitalizationautocomplete
: specifies whether the form should have autocompletename
: the name of the form, must not be an empty string, and must be unique among all<form>
elementsrel
: controls the annotations and what kind of links the form creates- Annotations include
external
,nofollow
,opener
,noopener
, andnoreferrer
- Link types include
help
,prev
,next
,search
, andlicense
- Annotations include
- Attributes for form submission:
action
: the URL that processes the form submission. This can be overriden by aformaction
attribute on abutton
,<input type="submit"
or<input type="image">
element. This attribute is ignored whenmethod="dialog
is setenctype
: the encoding type that the form should use when submitting data. This can be overriden by aformenctype
attribute on abutton
,<input type="submit"
or<input type="image">
element. This attribute is ignored whenmethod="dialog
is set- If the value of the
method
ispost
, theenctype
attribute is the MIME type of the form submission. Possible values:application/x-www-form-urlencoded
: the default value if the attribute is not specifiedmultipart/form-data
: the value used for an<input type="file">
elementtext/plain
: a single line of text
- If the value of the
method
: the HTTP method to submit the form withpost
: form data is sent as the request bodyget
: form data is appended to theaction
URL with a?
separator. Use this method when the form has no side effectsdialog
: when the form is inside a<dialog>
, closes the dialog and causes a submit event to be fired on submission, without submitting data or clearing the form
novalidate
: Boolean attribute that indicates that the form should not be validated when submitted- It can be overriden by a
formnovalidate
attribute on abutton
,<input type="submit"
or<input type="image">
element
- It can be overriden by a
target
: indicates where to display the response after submitting the form. It is a name keyword for a browsing context (e.g., tab, window, or iframe)_self
: the response will be displayed in the same frame_blank
: the response will be displayed in a new window or tab_parent
: the response will be displayed in the parent frame_top
: the response will be displayed in the full body of the window_unfencedTop
: load the form response inside an embedded fenced frame into the top-level frame
- Pertinent attributes:
- The
<h1>
-<h6>
elements represent six levels of section headings<h1>
is the highest section level and<h6>
is the lowest- Each are block-level elements, starting on a new line and taking up the full width available in their containing block
- Heading information can be used by user agents to construct a table of contents for a document automatically
- Do not use heading elements to resize test. That's what CSS font-size is for
- Do not skip heading levels
- Avoid using multiple
<h1>
elements on a single page
- A common technique for users of screen reading software is to generate a list of sectioning content and use it to determine the page's layout
- Sectioning content can be labeled using a combination of the
aria-labelledby
andid
attributes, with a label concisely describing the purpose of the section. This is userful if there is more than one sectioning element on the same page
- A
Type Selector
(akaTag Name
orElement
selector selects a given element type- For example,
p
selects all<p>
elements
- For example,
- The
Universal Selector
selects everything in your document, or in a parent element if it is being chained , using as asterisk- You can use the universal selector to make your CSS easier to read. For example
article :first-child { margin-top: 0; }
- This could be confused with
article:first-child
, so it could also be written as:
article *:first-child { margin-top: 0; }
- The
Class Selector
selects elements with a specific class attribute- For example,
.example
selects all elements with `class="example"
- For example,
- The
ID Selector
selects elements with an id, denoted by#
- For example,
#example
selects the element withid="example"
- For example,
- You can check whether an object has a property with a given name using
in
operator - returns true if it has an own or inherited property with that namehasOwnProperty()
method - returns true if an object has an own property with that namepropertyIsEnumerable()
method - returns true if a property is an own property and is enumerable
let o = { x: 1 }; o.propertyIsEnumerable("x") // => true: o has an own enumerable property x o.propertyIsEnumerable("toString") // => false: toString is an inherited method Object.prototype.propertyIsEnumerable("toString") // => false: property is not enumerable
- or simply by querying the property
- The
for/in
loop iterates over all enumerable (either own or inherited) properties of a specified object - An alternative to using the
for/in
loop is getting an array of property names and then looping over them with afor/of
loop - The four functions you can use to get an array of property names are:
Object.keys()
- returns an array of the names of the enumerable own properties of an object- Does not include non-enumerable properties, inherited properties, or properties whose name is a Symbol
Object.getOwnPropertyNames()
works likeObject.keys()
but returns an array of the names of non-enumerable own properties as well, as long as their names are stringsObject.getOwnPropertySymbols()
returns an array of the names of the own properties of an object whose names are Symbols, whether or not they are enumerableReflect.ownKeys()
returns all own property names, both enumerable and non-enumerable, both string and Symbol
- The
footer
element represents a footer for its nearest ancestor sectioning content or sectioning root element - It typically contains information about the author of the section, copyright data, or links to related documents
- A
pseudo-class
selects an element which is in a specific state- For example, a
:hover
pseudo-class selects an element when the user hovers over it
- For example, a
- A
pseudo-element
selects a certain part of an element rather than the entire element- For example, a
p::first-line
pseudo-element selects the first line of a paragraph element
- For example, a
- Combinators:
- You can combine selectors in order to target elements that have a specific relationship to other elements
- E.g.
article > p { }
would select all<p>
elements that are direct children of an<article>
element
- The
delete
operator only deletes own properties, not inherited ones - To delete an inherited property, you must delete it from the prototype object in which it is defined. Doing this affects every object that inherits the property
- The delete expression evaluates to
true
if the delete succeeded or if the delete had no effect (such as deleting a nonexistent property) delete
also evaluates totrue
when used with an expression that is not a property access expressiondelete
does not remove properties that have a configurable attribute offalse
- In strict mode, attempting to delete a non-configurable property causes a
TypeError
- In non-strict mode,
delete
simply returnsfalse
when used on a non-configurable property
<figcaption>
represents a caption or legend describing the rest of the contents of its parent<figure>
element, providing the element an accessible description- The
<figure>
HTML element represents self-contained content, potentially with an optional caption, which is specified using the<figcaption>
element- Usually a
<figure>
is an image, illustration, diagram, code snippet, etc. that is referenced in the main flow, but that can be moved to another part of the document or to an appendix without affeecting the main flow
- Usually a
- With CSS selectors, you have type, class, and ID selectors
- You also have attribute selectors
- These give you different ways to select elements based on the presence of a certain attribute on an element
a[title] { font-size: 15px; }
- This would equate to selecting all elements with a title
- You can also make selections using selectors for every element with a specific attribute value:
a[href="https://www.example.com"] { color: red; }
- Property Access expressions do not throw an error if a property does not exist
- It does throw an error, however, ifyou try to access a project of an object that does not exist
let o = {x: 1};
o.y // => undefined
o.y.length // => TypeError: Cannot read property 'length' of undefined
- Fortunately, conditional property access (options chaining) can be used to avoid this error
let len = o.y?.length; // len is undefined if o.y does not exist
- An attempt to set a property on
null
orundefined
will cause a TypeError - Attempts to set properties on other values do not always success either
- Some properties are read-only and cannot be set
- Some objects do not allow the addition of new properties
- In strict mode, a TypeError is thrown whenever an attempt to set a property fails
- Outside of strict mode, these failures are usually silent
- Concisely describing when property assignment will fail is difficult, but intuitive
- An attempt to set a property
p
of an objecto
fails in these circumstances:o
has own propertyp
that is read-onlyo
has inherited propertyp
that is read-only: it is not possible to hide an inherited read-only property with an own property of the same nameo
does not have an own property p;o
does not inherit a propertyp
with a setter method ando
' sextensible
attribute isfalse
- The
<fieldset>
element is used to group several controls as well as labels<label>
within a web form
<form>
<fieldset>
<legend>Choose your favorite monster</legend>
<input type="radio" id="kraken" name="monster" value="K"/>
<label for="kraken">Kraken</label><br/>
<input type="radio" id="sasquatch" name="monster" value="S"/>
<label for="sasquatch">Sasquatch</label><br/>
<input type="radio" id="mothman" name="monster" value="M"/>
<label for="mothman">Mothman</label>
</fieldset>
</form>
- You can use a
<legend>
element to provide a caption for the<fieldset>
element - You can also provide a
disabled
attribute to the<fieldset>
element to disable all of the controls within it
- Web Fonts
- As discussed previously, you can describe a font family in CSS using the
font-family
property
p { font-family: "Times New Roman", Times, serif; }
- In addition to this method, you can also load fonts from the web using the
@font-face
rule
@font-face { font-family: "MyWebFont"; src: url("myfont.woff2"); }
- All major browsers support
WOFF/WOFF2
(Web Open Font Format versions 1 and 2) - The order of files provided will affect what gets loaded first
- So if you provide multiple files to be loaded to populate a web font, use
WOFF2
, thenWOFF
as a fallback - If you have to support older browsers, you should provide
EOT
(Embedded Open Type),TTF
(TrueType Font), and SVG web fonts for download
- As discussed previously, you can describe a font family in CSS using the
- If you are to assign property
x
to the objecto
, ando
already has a propertyx
, the property will be overwritten- If
o
inherits a propertyx
from its prototype chain, that inherited property is now hidden by the newly created own property with the same name
- If
- Property assignment examines the prototype chain only to determine whether the assignment is allowed
- If
o
inherits a read-only property namedx
for example, the assignment is not allowed
- If
- The fact that inheritance occurs when querying properties but not when setting them is a key feature of JavaScript because it allows us to selectively override inherited properties
- There is one exception to the rule that a property assignment either fails or creates or sets a property in the
original object
- If o inherits the property x, and that property is an accessor property with a setter method, then that setter method is called rather than creating a new property x in o
- Note, however, that the setter method is called on the object o, not on the prototype object that defines the property, so if the setter method defines any properties, it will do so on o, and it will again leave the prototype chain unmodified
- The
<embed>
element is used to embed external content at the specific point in the document.- This content is provided by an external application or other source of interactive content such as a browser plug-in
- Most modern browsers have deprecated and removed support for browser plug-ins, so relying upon
<embed>
is not wise for the average user's browser - It has the following notable attributes:
height
: the displayed height of the resource, in CSS pixelswidth
: the displayed width of the resource, in CSS pixelssrc
: the URL of the resource being embeddedtype
: the MIME type of the resource
- A MIME type is a two-part identifier for file formats and format contents transmitted on the Internet
- Stands for Multipurpose Internal Mail Extensions
- The first part is the type, and the second part is the subtype
- For example, the MIME type for HTML is
text/html
- The MIME type for a JPEG image is
image/jpeg
- The MIME type for a PDF document is
application/pdf
- The
<fencedframe>
element represents a nested browsing context, embedding another HTML page into the current one- They are very similar to
<iframes>
, except that:- Communication between frame content and embedded site is restricted
- It can access cross-site data, but only in a very specific set of controlled circumstances that preserve user privacy
- It can't be manipulated or have its data accessed via regular scripting (e.g. reading or setting the source URL)
- It content can only be embedded via specific APIs
- The frame can't access the embedding context's DOM, not can the embedding context access the frame's DOM
- Notable attributes include:
allow
: specifies a Permissions Policy for the `width
,height
- The only features that can be enabled by a policy inside fenced frames are the specific features designed to be
used inside fenced frames:
- Protected Audience API
- attribution-reporting
- private-aggregation
- shared-storage
- shared-storage-select-url
- Shared Storage API
- attribution-reporting
- private-aggregation
- shared-storage
- shared-storage-select-url
- Protected Audience API
- Focusing across frame boundaries is limited. User initiated actions such as a click or a tab can do so, as there
is no fingerprinting risk there
HTMLElement.focus()
is prohibited, however, because a malicious script could use a series of such calls to leak inferred information across the boundary
- They are very similar to
- Styling Links:
- Link States: by taking advantage of the different states that links can be in, you can style them effectively
:link
pseudo class will select any link that has a destination (not just a named anchor):visited
pseudo class will select any link that has been visited:hover
pseudo class will select any link that is being hovered over:active
pseudo class will select any link that is being activated:focus
pseudo class will select any link that is currently focused
- The default link styles can be turned off/changed using the following CSS properties:
color
cursor
outline
- Link States: by taking advantage of the different states that links can be in, you can style them effectively
Object.create()
creates a new object, using the first argument as the prototype of that object:
let o1 = Object.create({x: 1, y: 2}); // o1 inherits properties x and y
o1.x + o1.y // => 3
- You can pass
null
to create a new object that does not have a prototype, but if you do this, the newly created object will not inherit anything, not even basic methods liketoString()
(which means it won't work with the + operator either)
let o2 = Object.create(null); // o2 inherits no props or methods.
- If you want to create an ordinary empty object (like the object returned by
{}
ornew Object()
), passObject.prototype
toObject.create()
let o3 = Object.create(Object.prototype); // o3 is like {} or new Object().
- One use case for creating a prototype chain is that a library method might unintentionally augment the values in the original object. Instead, you can pass in your object as a prototype of the new object, which will guard against accidental modifications
let x = {x: "don't change this value"};
library.function(Object.create(o));
- Javascript objects are associative arrays (like a hash map or dictionary)
- In C, C++, Java, and similarly strongly type languages, an object can only have a fixed number of properties, and the names of these properties must be defined in advance
- Since JS is a loosely typed language, this rule does not apply
- When you use the
.
operator to access a property of an object, the name of the property is expressed as an identifier- Identifiers must be typed literally into your JavaScript program; they are not a datatype, so they cannot be manipulated by the program
- On the other hand, when you access a property of an object with teh
[]
array notation, the name of the property is expressed as a string- Strings are JS datatypes, so they can be manipulated by the program
- Basically, these values can be handled at runtime, while the dot operator is more strict and requires identifiers, not strings
- The
<div>
element is the generic container for flow content- The
<div>
should only be used when no other semantic elements (like<article>
or<nav>
are appropriate)
- The
- The
<dl>
or Description List element encloses a list of groups of terms- The
<dt>
or description term element is used to define the term being defined - The
<dd>
or description details element is used to define the description, definition, or value for the preceding term - Tip:
- It can be handy to define a key-value separator in the CSS, such as:
dt::after { content: ": "; }
- The
- The
<dt>
or Description Term element specifies a term in a description or definition list- Must be used inside of a
<dl>
element
- Must be used inside of a
- The
<em>
or Emphasis element marks text that has stress emphasis- This is semantically different from the
<i>
or<cite>
elements, which are used for other types of emphasis
- This is semantically different from the
- Controlling List Counting
- Sometimes you might want to:
- Start from a number other than 1
- Count Backwards
- Count in steps of more than 1
- HTML and CSS have some tools to help
- Check
index.html
for example - Add
start
attribute to the list element to start from a number besides 1 - Add
reversed
attribute to the list element to start from the final number and count backwards - Add
value
attributes with different numbers to list item elements in order to count in steps of more than 1
- Check
- Sometimes you might want to:
- All objects in JS have a second object (called a prototype) tied to them
- Any object created with the
new
keyword inherits the prototype of the constructor function- e.g.
let o = new Object();
will inherit the prototype of theObject
constructor, orObject.prototype
- e.g.
- All objects created from Object literals will inherit
Object.prototype
- Almost all objects have a prototype, but only a relatively small number of objects have a prototype property
- It is these objects with prototype properties that define the prototypes for all other objects
Object.prototype
is one of the rare objects in JS that has no prototype- Other prototype objects are normal objects that do have a prototype
- Most built-in constructors (and most user-defined constructors) have a prototype that inherits
from
Object.prototype
- e.g.,
Date.prototype
inherits fromObject.prototype
- So, an object created by
new Date()
will inherit fromDate.prototype
andObject.prototype
- This linked series of prototype objects is called a Prototype Chain
- So, an object created by
- e.g.,
- Chapter 9 will describe how to set Class constructors up to assign object prototypes for instances created by the constructor
- Wrap-up of the HTML dialog element today
- Styling lists in CSS is much like styling any other text, with some unique properties
- The three types of lists in CSS are:
- Unordered lists (
<ul>
) - Ordered lists (
<ol>
) - Definition lists (
<dl>
)
- Unordered lists (
- List-Specific Styles
- These properties can be set on
<ul>
and<ol>
elementslist-style-type
: The type of bullet or numbering usedlist-style-position
: The position of the bullet or numbering, whether inside or outside the list itemlist-style-image
: An image to use as the bullet or numbering
- These properties can be set on
- Any value in Javascript that is not a string, a number, a Symbol, or
true
,false
,null
, orundefined
is an object - A property name on an Object can be any string, including the empty string (or any Symbol)
- The value may be any Javascript value, or it may be a getter or setter function (or both)
- An
own property
refers to a non-inherited property - In addition to its name and value, each property has three property attributes:
- The writable attribute specifies whether the value of the property can be set
- The enumerable attribute specifies whether the property name is returned by a
for/in
loop - The configurable attribute specifies whether the property can be deleted and whether its attributes can be altered
- Many of JS's built-in objects have properties that are read-only, non-enumerable, or non-configurable
- By default, however, all properties of the objects you create are writable, enumerable, and configurable
- Today, I am practicing the usage of dialogs in the
index.html
file attached
- The
outline
andborder
properties in CSS have different properties- The border is added to the inside of the element, while outline is added to the outside of the element
- The CSS selector
x + y
will select the first instance of ay
following anx
element.- This is the adjacent sibling selector
- Unlike statements, declarations in JS code don't necessarily "make things happen"
- Rather, they provide structure for the code and are run before code is actually executed
- These declarations include
let
,var
,const
,class
,function
,import
, andexport
- You've already learned much about the
let
,var
,const
, andfunction
declarations class
is on the wayimport
andexport
are both used to link to modules in JS- A module is a file of Javascript code with its own global namespace, completely independent of all other modules
- Values within modules are private and cannot be accessed by external modules unless they've been explicitly exported
- The export keyword is sometimes used in addition to other declarations
- When a module exports only a single value, this is typically done with the special form
export default
export const TAU = 2 * Math.PI; export function magnitude(x,y) { return Math.sqrt(x*x + y*y); } export default class Circle { /* class definition omitted here */ }
- The
debugger
directive is used to tell the interpreter to pause execution and enter the debugger- This is useful for debugging code, as it allows you to inspect the state of the program at that point
- This acts very similarly to a
breakpoint
set with your developer tools - It is only available when the developer tools are open
- Often used in conjunction with breakpoints, which are set in the developer tools
- Not a statement in the strict sense, but rather a directive to the interpreter
- Not supported in all browsers, and should not be used in production code
- The
use strict
directive is used to enable strict mode in JavaScript- Strict mode is a way to opt in to a restricted variant of JavaScript
- It catches common coding errors and makes it easier to write "secure" JavaScript
- It is a string literal, and must be the first statement in a script or function
- It is not a statement, but a directive to the interpreter
- It is supported in all modern browsers
strict mode
has the following key differences withnon-strict mode
:- The
with
statement is not allowed - All variables must be declared before they are used
- All functions invoked as functions (rather than as methods) have a
this
value ofundefined
- In non-strict mode, the
this
value would be the global object
- In non-strict mode, the
- Assignments to non-writable properties and attempts to create new properties on non-extensible objects throw
a
TypeError
- In non-strict mode, these assignments fail silently
- Code passed into
eval
is executed in its own scope, rather than the caller's scope - The Arguments object in a function holds a static copy of the values of the arguments passed to the function
- In non-strict mode, the Arguments object has a magical behavior in which elements of the array and named function parameters both refer to the same value
- The
delete
operator throws aSyntaxError
when used on a non-configurable property- In non-strict mode, the
delete
operator returnsfalse
when used on a non-configurable property
- In non-strict mode, the
- It is a Syntax Error for an object literal to define two properties of the same name
- Octal Integers (beginning with a 0 and not followed by an x) are not allowed
- Identifiers
eval
andarguments
are treated as reserved words, and you cannot change their value- You cannot assign a value to their identifiers, declare them as variables, use them as function names, use
them as function parameter names, or use them as the identifier of a
catch
block
- You cannot assign a value to their identifiers, declare them as variables, use them as function names, use
them as function parameter names, or use them as the identifier of a
- The ability to examine the call stack is restricted
arguments.caller
andarguments.callee
are not allowed, and both throw aTypeError
within a strict mode function
- The
- The
<dialog>
represents a modal or non-modal dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow- Modal dialog boxes interrupt interaction with the rest of the page, while non-modal dialog boxes allow interaction with the rest of the page
- Javascript should be used to display the
<dialog>
element- Use the
.showModal()
method to display a modal dialog box - Use the
.show()
method to display a non-modal dialog box - A dialog box can be closed using the
.close()
method - Modal dialogs can also be closed by pressing the
esc
key
- Use the
- The
tabindex
attribute must not be used on the<dialog>
element - The
open
attribute is a boolean attribute that controls whether the dialog box is displayed- It's recommended to use the
.show()
or.showModal()
methods to display the dialog box - If a dialog is opened using the
open
attribute, it will be displayed as a non-modal dialog box
- It's recommended to use the
- HTML
<form>
elements can be used to close a dialog if they have themethod="dialog"
attribute set, or if the button used to submit the form has theformmethod="dialog"
attribute set
- The
line-height
property sets the height of each line of text - Similarly, you can set the
letter-spacing
andword-spacing
properties to adjust the space between characters and words, respectively
- Labeled break statements can allow you to break out of a deeply nested loop. Here's an example
let matrix = getData(); // get a 2D array of data from somewhere
// Now sum all the numbers in the matrix
let sum = 0, success = false;
// Start with a labeled statement that we can break out of if errors occur
computeSum: if (matrix) {
for (let x = 0; x < matrix.length; x++) {
let row = matrix[x];
if (!row) break computeSum;
for (let y = 0; y < row.length; y++) {
let cell = row[y];
if (isNaN(cell)) break computeSum;
sum += cell;
}
}
success = true;
}
// The break statements jump here. If we arrive here with success == false then there was somthing wrong with the matrix
we
were
given.
// Otherwise, sum contains the sum of all cells of the matrix
- The
continue
statement is used to skip the rest of the body of a loop and jump back to the top of the loop to begin a new iteration- In the case of a
for
loop, the increment expression is evaluated before the loop condition is tested - In the case of a
while
loop, the loop condition is tested before the loop body is executed - Here's an example:
- In the case of a
for (let i = 0; i < data.length; i++) {
if (!data[i]) continue; // Skip null and undefined values
total += data[i];
}
- The
return
statement is used to make the interpreter jump from a function invocation back to the code that invoked it - The
yield
statement is much like the return statement but is used only in ES6 generator functions to produce the next value in the generated sequence of values without actually returning.- In order to understand the
yield
, you must understand iterators and generators
- In order to understand the
- The
throw
statement is used to throw an exception, which is a signal that an error or other unusual condition has occurred- The
throw
statement requires a single argument, which is the value of the exception that is thrown - The
throw
statement is typically used in conjunction with thetry/catch/finally
statement
- The
- The
finally
statement is used to specify a block of code that will be executed after atry
orcatch
block, regardless of whether an exception is thrown- If any part of the
try
block is executed, thefinally
block will also be executed - This statement is often used to clean up resources, such as closing files or network connections
- If any part of the
- The
<dfn>
element is used to indicate a term being defined.- It should be used to indicate the term being defined, not the definition itself
- The ancestor of the
<dfn>
element should be a<p>
,<section>
,<article>
, or<aside>
element that contains the full definition of the elemtn - Or it can be used with
<dd>/<dt>
elements in a<dl>
element
- The
text-align
property is used to position horizontal alignment of text within its parent container- The
text-align
property can have one of the following values:left
,right
,center
,justify
,start
,end
,match-parent
,initial
,inherit
- The
text-align
property is inherited by child elements - The
text-align
property only affects inline-level and inline-block elements - The
text-align
property does not affect block-level elements - The
text-align
property does not affect table elements - The
text-align
property does not affect flex items
- The
- Another form of statement in JS is a
jump
statement- The
break
statement makes the interpreter jump to the end of a loop or other statement - The
continue
statement makes the interpreter skip the rest of the body of a loop and jump back to the top of a loop to begin a new iteration - The
return
statement makes the interpreter jump from a function invocation back to the code that invoked it and also supplies the value for the invocation - The
throw
statement is a kind of interim return from a generator function- It is designed to work with
try/catch/finally
statements
- It is designed to work with
- The
- Furthermore, any statement may be labeled by preceiding it with an identifier and a colon:
identifier: statement
- This is useful for nested loops, where you can break out of the inner loop by referencing the outer loop
- The
<dd>
element provides the description, definition, or value for the preceding term<dt>
in a description list<dl>
- This is called the description details element
- The
<del>
element is used to indicate that text has been deleted from a document- This is typically displayed with a strikethrough
- The
cite
attribute can be used to provide a URL to the source of the deletion - The
datetime
attribute can be used to provide a machine-readable date and time for the deletion - This could be used to show changes, similar to the
<ins>
element
- In terms of font-size, a
<p>
tag will be set with a default value of16px
by default - Using
em
can be tricky when you're setting the font-size of a parent element, as it will be relative to the parent element - Using
rem
is a better choice, as it will be relative to the root element, which is the<html>
element font-style
is the property used to turn italic text on or offfont-weight
is the property used to set the weight of the fonttext-transform
allows you to set your font to be transformednone
: prevents any transformationlowercase
,uppercase
,capitalize
full-width
: converts the text to full-width characters that are written inside a fixed width square
text-decoration
is the property used to set the decoration of the textnone
,underline
,overline
,line-through
,blink
text-shadow
allows you to apply drop shadows to your text, setting the horizontal and vertical offsets, blur radius, and color
- The
for/in
loop iterates over the properties of an object- It will iterate over all enumerable properties of an object, including inherited properties
- The
for/in
loop is not recommended for use with arrays, as it will iterate over the indices of the array, as well as any other enumerable properties - The
for/of
loop is recommended for use with arrays, as it will only iterate over the values of the array - In addition to built-in methods, many of the built-in properties of objects are non-enumerable
- All properties and methods defined by your code are enumerable by default
- The
for/in
loop will iterate over all enumerable string-named properties, whether they are inherited up the prototype chain or not
- You will learn more about enumerable properties later
-
The
<data>
element is used to provide a machine-readable version of the content within it<p>New Products:</p>
- Mini Ketchup
- Jumbo Ketchup
- Mega Jumbo Ketchup
- The
<datalist>
element is used to provide a list of predefined<option>
elements within another control- The
<datalist>
element is used in conjunction with the<input>
element to provide a list of predefined options for the user to choose from - The
<datalist>
is given a unique id, which is then referenced by thelist
attribute of the<input>
element - This can be used for autocomplete functionality, or to provide a list of options for the user to choose from
- The
- Today, I start the CSS grids assessment. See
index.html
andstyles.scss
for details
- Because strings are iterated by Unicode codepoint, not by UTF-16 character,
- The string "I❤JS" has a length of 5, but would be iterated as 4 characters
- Sets are also iterable in a very predictable, simple way
- Maps are slightly different because they are iterated not by key or value, but by key/value pairs
- Here's an example of Map iteration:
let m = new Map([[1, "one"]]); for(let [key, value] of m) { key // => 1 value // => "one" }
- The
for/await
loop was introduced in ES2018 and will be covered later, but here's an exampleasync function printStream(stream) { for await (let chunk of stream) { console.log(chunk); } }
- The
<col>
element defines one or more columns in a column group represented by its parent<colgroup>
element- It's only valid as a child of a
<colgroup>
element that has no span attribute defined - An example:
<table> <caption> Superheros and sidekicks </caption> <colgroup> <col /> <col span="2" class="batman" /> <col span="2" class="flash" /> </colgroup> <tr> <td></td> <th scope="col">Batman</th> <th scope="col">Robin</th> <th scope="col">The Flash</th> <th scope="col">Kid Flash</th> </tr> <tr> <th scope="row">Skill</th> <td>Smarts, strong</td> <td>Dex, acrobat</td> <td>Super speed</td> <td>Super speed</td> </tr> </table>
- Here, a
<col>
element is used to group them and assign custom classes, for styling
- It's only valid as a child of a
- The
<colgroup>
element is used to define a group of columns within a table- The
span
attribute specifies the number of columns the<colgroup>
element should span. - It defaults to 1 and must not be present if there are any
<col>
elements as children - The
<colgroup>
element should always appear within a table, after any<caption>
elements but before any<thead>
,<tbody>
,<tfoot>
, or<tr>
elements
- The
- The ability to add subgrids enables even more flexibility within this layout model
- Check the accompanying
index.html
andstyles.scss
files for a full example
- A
for/of
loop works on any iterable object in JS- This includes Arrays, Strings, Sets, and Maps
- In order to iterate over an object, you must use
- A
for/in
loop - The
Object.keys()
,Object.values()
, orObject.entries()
methods
- A
- You can destructure an object in a
for/of
loop like soconst obj = {a: 1, b: 2, c: 3} for (const [key, value] of Object.entries(obj)) { console.log(key, value) }
- The
<caption>
element is used to define a table caption- This provides an accessible description.
- It should be the first child of a
<table>
element
- The
<cite>
element is used to define the title of a work- This is typically used for a book, movie, song, or other creative work
- It should be used to provide a citation to the work
- This is normally used inside of a
<blockquote>
or<q>
element - Most browsers will style the
<cite>
element with italics, but you can override this with CSS
- The
<code>
element is used to define a piece of computer code- This is normally formatted using the user agent's monospace font
- In addition to setting the
grid-column
andgrid-row
properties, you can also usegrid-template-areas
to define the layout of different sections - Check the
index.html
/styles.scss
files for a full example, but here's an example:
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
grid-template-columns: 1fr 3fr;
gap: 20px;
}
header {
grid-area: header;
}
article {
grid-area: content;
}
aside {
grid-area: sidebar;
}
footer {
grid-area: footer;
}
- Explicitly, the
for
loop syntax is
for (initialize; test; increment) {
statement
}
- An interesting way to compare it to a
while
loop:
initialize;
while (test) {
statement;
increment;
}
- Most
for
loops are numeric, but they can be used to iterate over many different types of data structures:
function tail(o) {
for (; o.next; o = o.next) /* empty */ ;
return o;
}
- The
<canvas>
element uses either the canvas scripting API or the WebGL API to draw graphics and animations - It uses the global attributes, and some noticeable ones are:
height
: The height of the canvaswidth
: The width of the canvas
- Unlike the
<img>
element, the<canvas>
element requires the closing tag - iOS devices notably limit maximum canvas size to 4,096 x 4,096 pixels, whereas most other browsers allow 10,000 x 10,000 pixels
- Using the
OffscreenCanvas
API, you can create a canvas that is not visible in the DOM, but can be used to render images offscreen - It is good practice to include alternative text within the canvas to describe what is happening on the canvas
- For more detailed description of using the
Offscreen Canvas
API and theCanvas
API
- You can specify an item's placement within the grid using
the
grid-column-start
,grid-column-end
,grid-row-start
, andgrid-row-end
properties - These are often shortened to
grid-column
andgrid-row
properties - For example:
-
.item { grid-column: 1 / 3; grid-row: 1 / 3; }
- This will place the item in the first column, spanning two columns, ending after the 3rd, and in the first row, spanning two rows, ending after the 3rd
else if
is not actually a statement in proper JS, and is instead an idiom used by programmers to make these nested conditionals more legible- A
switch
statement in JS looks like this:
switch (expression) {
case value1: // starting point 1
// code block
break;
case value2: // starting point 2
// code block
break;
default: // final starting point
// code block
}
- It's also worth noting that the
===
operator is used to check equality in this context The purpose of thesecase
statements is to provide a starting point for the code block to execute, and thebreak
statement is used to exit theswitch
statement
- The
<button>
attribute is used to define a button- It inherits the global attributes
- Notable attributes include
autofocus
,disabled
, andtype
- When the button is part of a form, the
type
attribute can besubmit
,reset
, orbutton
- The
submit
type will submit the form data to the server, and is the default type if thetype
attribute is not specified - If your buttons are not for submitting form data to a server, be sure to set their
type
attribute tobutton
- Otherwise, the default behavior of the button will be to submit the form data to the server, possibly destroying the current state of teh document
- The
- If a button is attached to a form, the following attributes help direct this call:
formaction
: The URL that processes the form data when the form is submittedformenctype
: The encoding type for the form dataformmethod
: The HTTP method used to submit the form dataformnovalidate
: A Boolean attribute that specifies that the form data should not be validated when submittedformtarget
: The target window or frame where the form data is submittedname
: The name of the button, which is submitted with the form datavalue
: The value of the button, which is submitted with the form dataform
: The form element id that the button is associated with
- For accessibility, it's best practice to include text along with any icon within a button, to ensure cultural or technological gaps in understanding can be overcome by the user
- Firefox will add a small dotted border around a button when it is focused, but this can be removed with the following
CSS:
button::-moz-focus-inner { outline: none; }
- If you set a
grid-auto-rows
value to `100px' but want to make sure than any overflown text in a row would still display - In this case, simply use the
minmax()
function to set a minimum and maximum height for the row - For example:
.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-auto-rows: minmax(100px, auto);
}
- In this case, the row will be at least 100px tall, but will expand to fit the content if it is larger than 100px
- You can also configure a value that allows as many columns as will fit, using a combination of
auto-fit
andminmax()
- For example:
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-rows: minmax(100px, auto);
gap: 20px;
}
- The comma operator (
,
) is used to evaluate any left-hand operands, then return the value of the right-hand-most operand - An example would be
i = 0, j = 0, k = 2;
// you could also write something like
i = 0, j = 0, k = someVal === 2 // in this case, the comma operator discards the left operand values and returns '
someVal
' assigned to k for comparison to the number 2
- The most common example of the comma operator is in a
for
loop, where multiple variables are used, and operands with side effects exist on both sides of the comma
for (let i = 0, j = 1; i < 10, j < 5; i++, j++) {
console.log(i, j)
}
- Expressions are evaluated to produce a value, but Statements are executed to make something happen
- The
<body>
element represents the content of an HTML document.- There can only be one body element
- In addition to the global attributes, the body element has the following:
onafterprint
: function to call after the user has printed the doconbeforeprint
: function to call before the user prints the doconbeforeunload
: function to call before the doc is unloadedonblur
: function to call when the element loses focusonerror
: function to call when an error occursonfocus
: function to call when the element gets focusonhashchange
: function to call when there has been a change in the anchor part of the URLonlanguagechange
: function to call when the user changes the language of the pageonload
: function to call when the element is finished loadingonmessage
: function to call when the element receives a messageonoffline
: function to call when the browser starts to work offlineononline
: function to call when the browser starts to work onlineonpopstate
: function to call when the window's history changesonredo
: function to call when the document performs a redoonresize
: function to call when the document view is resizedonstorage
: function to call when the storage area has changedonundo
: function to call when the document performs an undoonunload
: function to call when the document is being unloaded
- The
<br>
element is used to insert a line break in text- The
<br>
element is an empty element, which means it does not have a closing tag - This element is meant to break up a paragraph, like a poem or a speech, where specific line breaks are necessary
- Never adjust the margins on a
<br>
element, and instead adjust theline-height
property of the parent element - There are accessibility concerns associated with the
<br>
element, as it can be misused to create a new paragraph, when a<p>
element should be used instead - For the purpose of screen readers and accessibility, it is recommended not to use a
<br>
element to create a new paragraph
- The
- You can repeat all or part of a track listing using the CSS
repeat()
function - E.g.
.container {
display: grid;
grid-template-columns: repeat(3, 100px);
gap: 20px;
}
- Explicit grids are created using
grid-template-columns
and `grid-template-rows - Implicit grids extends the defined explicit grid when content is placed outside of that grid, such as into the rows by drawing additional grid lines
- By default, tracks created in the grid are auto-sized, which means they're large enough to contain their content
- You can also give them a size using
grid-auto-rows
andgrid-auto-columns
- Using
grid-auto-columns
withgrid-template-columns
will not overwrite the explicit grid
- The
eval
function is used to evaluate a string as JavaScript- Generally, the
eval
function will use the variable environment of the code that calls it - This means that the
eval
function can access variables in the calling code, reassign them, etc. - It can also create new variables in that scope using the
var
variable declaration keyword let
andconst
variables are block-scoped, so they will not be accessible outside theeval
function- If the
eval
is aliased and called by any other name, its scope will be treated as global scope, and any local variables or functions from the calling scope will not be accessible within theeval
code
- Generally, the
const geval = eval
let x = "global", y = "global"
function f() {
let x = "local"
eval("x += 'changed';")
return x;
}
function g() {
let y = "local"
geval("y += 'changed';")
return y;
}
console.log(f(), x); // Local variable changed: prints "localchanged global"
console.log(g(), y); // Global variable changed: prints "local globalchanged"
-
The notable difference is the context in which the eval function is called, and the scope in which it is executed in each case
-
The
delete
operator is used to remove a property from an index or object- The
delete
operator returnstrue
if the property is successfully deleted, andfalse
otherwise - If the property is non-existent,
delete
will returntrue
- If the property is non-configurable,
delete
will returnfalse
- The
let obj = {a: 1, b: 2, c: 3}
delete obj.a // true
delete obj.d // true
delete obj // false
let arr = [1, 2, 3]
delete arr[0] // true
delete arr[3] // true
delete arr // false
console.log(arr) // [empty, 2, 3]
console.log(arr.length) // 3, because the array still has 3 elements, this is called a "sparse array"
- The
<bdo>
or Bi-directional Text Override element is used to override the Unicode bidirectional algorithm- This is useful when you want to display text in a different direction than the surrounding text
- The
dir
attribute is used to specify the direction of the text - The
dir
attribute can have one of three values:ltr
,rtl
, orauto
- The
ltr
value specifies that the text should be displayed from left to right - The
rtl
value specifies that the text should be displayed from right to left - The
auto
value specifies that the text should be displayed in the direction of the surrounding text - The main difference between the
bdi
andbdo
elements is that thebdi
element isolates the text from its surrounding text, while thebdo
element overrides the Unicode bidirectional algorithm
<h1>Famous seaside songs</h1> <p>The English song "Oh I do like to be beside the seaside"</p> <p>Looks like this in Hebrew: <span dir="rtl">אה, אני אוהב להיות ליד חוף הים</span></p> <p>In the computer's memory, this is stored as <bdo dir="ltr">אה, אני אוהב להיות ליד חוף הים</bdo></p>
- The
<blockquote>
element is used to define a block of text that is quoted from another source- You can use the
cite
attribute to specify the source of the quotation - You can also use a
<cite>
element to specify the title of the source - See the
index.html
file to see how you can use a footer to cite the source of the quote - Also keep in mind that you can use a
<q>
element to define a short inline quotation
- You can use the
- Grids, grids, grids
- The
grid-template-columns
property is used to define the number and size of columns in a grid container - Here, you can define the size of each column using a length, a percentage, or a fraction of the available space
- To add space across both access of the grid, you can specify the gap property:
.container { display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 25px; }
- Alternatively,
column-gap
androw-gap
properties also specify gap space
- The
- The assignment operator
=
has right-to-left associativity which means that the rightmost expression is evaluated first- This is why you can chain assignments like
let a = b = c = 5
- The rightmost expression is evaluated first, and then assigned to the next variable to the left
- This is also why you can chain assignments with different types of variables
- For example,
let a = b = 'hello'
will assign the string'hello'
tob
, and then assignb
toa
- This is why you can chain assignments like
- Also, the assignment operator might be nested inside more complex logic, like
(a = b) === 0
- In this case, the assignment operator is evaluated first, and then the comparison operator is evaluated
- The
<bdi>
element is used to tell a browser about bi-directional text- This is useful when you have text in multiple languages, or text that is mixed with numbers
- The
<bdi>
element isolates the text from its surrounding text, so that the browser can display it correctly - For example:
-
<p>Here is some text in English: <bdi>שלום</bdi></p>
- The
display
property in CSS is used to determine how an element is displayed- The
display
property is used to determine the layout of an element, and how it interacts with other elements on the page - The
display
property is one of the most important properties in CSS, and is used to control the layout of a web page- The
block
value makes an element a block-level element, which means it will take up the full width of its container, and will start on a new line - The
inline
value makes an element an inline-level element, which means it will only take up as much width as it needs, and will not start on a new line - The
inline-block
value makes an element an inline-block element, which means it will take up as much width as it needs, but will start on a new line - The
flex
value makes an element a flex container, which means it will lay out its children in a flex layout - The
grid
value makes an element a grid container, which means it will lay out its children in a grid layout - The
none
value makes an element invisible, and it will not take up any space on the page - The
table
value makes an element a table element, which means it will lay out its children in a table layout - The
flow-root
value makes an element a block-level element, and establishes a new block formatting context
- The
- The
- The
instanceof
operator checks if an object is an instance of a class- It returns
true
if the object is an instance of the class, andfalse
otherwise - It can also be used to check if an object is an instance of a subclass
- It can also be used to check if an object is an instance of an interface
- Interesting, it's not quite the same thing as
typeof
, which checks the type of a variable
- It returns
- For example, if you were to declare
x = 2
andy = new Number(2)
, thenx instanceof Number
would returnfalse
, whiley instanceof Number
would returntrue
- This is because
x
is a primitive number, whiley
is an instance of theNumber
class - The difference between a primitive number and an instance of the
Number
class is that theNumber
class has methods and properties that can be accessed - Here's a code block from JS The Definitive Guide (p. 173) to further explain how the
instanceof
operator works:
let d = new Date(); // Create a new object with the Date() constructor
d instanceof Date // => true: d was created with Date()
d instanceof Object // => true: all objects are instances of Object
d instanceof Number // => false: d is not a Number object
let a = [1, 2, 3]; // Create an array with array literal syntax
a instanceof Array // => true: a is an array
a instanceof Object // => true: all arrays are objects
a instanceof RegExp // => false: arrays are not regular expressions
- The
<base>
element specifies the base URL to use for all relative URLs in a document- The
<base>
element must have anhref
attribute, which specifies the base URL, or atarget
attribute, which specifies the default target for all hyperlinks and forms in the document - The
<base>
element must be placed inside the<head>
element - The
<base>
element is supported by all major browsers - A document's used base URL can be accessed by scripts with
Node.baseURI
. If the document has no elements, then baseURI defaults tolocation.href
- The
- In a
display: grid
context, you can usefr
, or fractional units to take up a given proportion of the available space - For example:
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
}
- The
in
operator expects a lefthand argument that is a string, symbol, or can evaluate to a string, and a righthand side argument that is an Object - The
in
operator will returntrue
if the lefthand argument is a property of the righthand object, andfalse
otherwise - For objects, this is rather intuitive:
let obj = {a: 1, b: 2, c: 3} console.log('a' in obj) // true console.log('d' in obj) // false
- For arrays, the
in
will return true if the passed in string/symbol is a valid index of the array.- So the "index" is treated like a property in this case
- It does not evaluate array values
let arr = [1, 2, 3] console.log('0' in arr) // true console.log('1' in arr) // true console.log(`3` in arr) // false, because the array only has indices 0, 1, and 2
- The
<b>
element is a stylistic element that provides bold formatting to text- It is no longer recommended, with either
<strong>
or<span>
with CSSfont-weight
styling being preferred - Here's where the docs get nitpicky:
- The
<strong>
element indicates text of certain importance - The
<em>
element indicates text of certain emphasis - The
<mark>
element indicates text with certain relevance (highlighting)
- The
- If there is no semantic importance, emphasis, or relevance, then the
<span>
element with CSS styling is recommended
- It is no longer recommended, with either
- Font stacks enable you to create fall-backs if a web-font fails to load
- The
font-family
property can take a comma-separated list of font names, with the browser trying each font in order
p {
font-family: "Trebuchet MS", Verdana, sans-serif;
}
- In this case, the browser will first try to load "Trebuchet MS", then "Verdana", and finally any sans-serif font
- The shift left operator
<<
shift the bits of a number to the left, filling empty bits with 0's- This is effectively the same as multiplying by 2
- The shift right operator
>>
shifts the bits of a number to the right, filling the empty bits with the sign bit (0 for positive numbers, 1 for negative numbers)- This is effectively the same as dividing by 2, but always rounding down
- In a strict equality check,
NaN
is no equal to itself.- A good shorthand way is to use the global
isNaN()
function or to check isx !== x
- A good shorthand way is to use the global
- Also, in a strict equality check,
0
is equal to-0
- The
<article>
element is a semantic element that defines a self-contained piece of content that could be distributed and reused independently- It could be a blog post, a forum post, a news article, or a comment
- The
<article>
element is a block-level element, and will typically be displayed in a normal font - The
<article>
element is a semantic element, and should be used to provide meaning to the content - The
<article>
element is supported by all major browsers
- The
<aside>
element is a semantic element that defines content that is tangentially related to the content around it- It could be a sidebar, a pull quote, a glossary, or a related article
- The
<aside>
element is a block-level element, and will typically be displayed in a normal font - The
<aside>
element is a semantic element, and should be used to provide meaning to the content - The
<aside>
element is supported by all major browsers
- The
justify-items
property is ignored in a flex container, as it only applies to grid containers - Instead, justifying items in a flex container is done with the
justify-content
propertystart
,end
,center
,space-between
,space-around
,space-evenly
,stretch
,safe
,unsafe
- The increment and decrement operators have a pre- and post- versions, which return the value before or after increment/decrement
- For example:
let x = 5
let y = x++ // y == 5, x == 6
let z = ++x // z == 7, x == 7
- Basically the pre- or post- defines if the change to the original will happen pre- or post- the assignment to
the
lval
in question - Remember, all increment/decrement operators must use
lval
, so must be a- Variable
- Array item
- Object property
- The
<area>
element is only used within an image map (<map>
) element in order to allow for clickable areas - It will normally use a
shape
andcoords
attribute to define the clickable area - Here's an example from the docs site:
<map name="infographic"> <area shape="poly" coords="129,0,260,95,129,138" href="https://developer.mozilla.org/docs/Web/HTTP" target="_blank" alt="HTTP" /> <area shape="poly" coords="260,96,209,249,130,138" href="https://developer.mozilla.org/docs/Web/HTML" target="_blank" alt="HTML" /> <area shape="poly" coords="209,249,49,249,130,139" href="https://developer.mozilla.org/docs/Web/JavaScript" target="_blank" alt="JavaScript" /> <area shape="poly" coords="48,249,0,96,129,138" href="https://developer.mozilla.org/docs/Web/API" target="_blank" alt="Web APIs" /> <area shape="poly" coords="0,95,128,0,128,137" href="https://developer.mozilla.org/docs/Web/CSS" target="_blank" alt="CSS" /> </map> <img usemap="#infographic" src="/media/examples/mdn-info.png" alt="MDN infographic" />
- A block-level element always starts on a new line, taking up the entire space availab to it along the main-axis ( x-axis for English text)
- An inline-level element only takes up as much space as it needs, and does not start on a new line. A span is an exampel of an inline element.
- Here is code from the CSS Docs demonstrating the differences
-
<h1>Basic document flow</h1> <p> I am a basic block level element. My adjacent block level elements sit on new lines below me. </p> <p> By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height. </p> <p> We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both. </p> <p> Inline elements <span>like this one</span> and <span>this one</span> sit on the same line along with adjacent text nodes, if there is space on the same line. Overflowing inline elements will <span>wrap onto a new line if possible (like this one containing text)</span>, or just go on to a new line if not, much like this image will do: <img src="long.jpg" alt="snippet of cloth" /> </p>
- In JS, an
lval
is a value that can legally be on the left-side of an assignment expression- This includes variables, properties of objects, and elements of arrays
- The
<address>
HTML element indicates that the enclosed HTML provides contact information for a person or people, or for an organization- The
address
element is a block-level element, and will typically be displayed in an italic font - The
address
element is a semantic element, and should be used to provide meaning to the content - The
address
element is supported by all major browsers
- The
- Although it formats equivalently as using an
<i>
or<em>
tag, the<address>
tag is more semantically correct - No attributes for this elements beyond the global attributes
- By default, all flex-items have a
order
property of 0 - Increased order property means an item comes later in the order of items
-
article { order: 1; } article:nth-of-type(3) { order: 2; }
- This will give the third article a later order than the other articles
-
- Operators in JS do have an order of operation (like PEMDAS)
- We call this operator precedence (which operator is evaluated first) and operator associativity (which operator is evaluated first in the case of operators with the same precedence)
- Generally, access operators and invocation operators take top precedence
- Mult/Division operators take precedence over Add/Subtract operators
- Use parentheses to ensure the order of operations you want
- The
??
, or Nullish Coalescing Operator in JS returns its right-hand side operand when its left-hand side operand is null or undefined- Unlike the
||
operator, the??
operator doesn't coerce its left-hand side operand to a boolean - Therefore:
let x = null let y = x ?? 'default' // y == 'default' x = 0 y = x ?? 'default' // y == 0, since 0 is not null or undefined x = false y = x ?? 'default' // y == false, since false is not null or undefined
- Unlike the
- The
<abbr>
or abbreviation element is used to mark up an abbreviation or acronym- The
title
attribute is used to provide the full expansion of the abbreviation - The
title
attribute is also used to provide a tooltip when the user hovers over the abbreviation - The first time using an abbreviation on a page, it's a good idea to use the
<abbr>
element to fully expand it - Only extends the global attributes, and has no specific attributes of its own
- The
<abbr>
element is a semantic element, and should be used to provide meaning to the content - Supported by all major browsers
- The
- Within a flex container, you can assign flex values to each flex-item
-
article { flex: 1; } article:nth-of-type(3) { flex: 2; }
- This will give the third article twice the space of the other articles
-
- In a regular Property Access Expression (like
expression.property
orexpression[expression]
): - We either use a dot followed by a valid identifier (cannot be a number, reserved keyword, or start with a number or special character)
- Or we use an expression to access a property, which is evaluated to a string literal or symbol
- In either case, accessing a property that doesn't exist will return
undefined
- Optional Chaining allows the ability to access deeply nested properties without throwing an error if a property
doesn't exist
- It's denoted by a
?.
after the object or array, and will returnundefined
if the property doesn't exist - It's especially useful when working with APIs, where the data structure may not be consistent
- It's also useful when working with user input, where the data may not be complete
- It's denoted by a
- The
<a>
or "anchor" tag is used to create hyperlinks to other web pages, files, locations within the same page, email addresses, or any other URL\ - The
href
indicates the destination of the link- Acceptable alternative link formats include:
- Telephone numbers with
tel:
URLs - Email addresses with
mailto:
URLs - SMS text messages with
sms:
URLs
- Telephone numbers with
- Acceptable alternative link formats include:
hreflang
specifies the language of the linked resource - allowed values are the same as the globallang
attributeping
is a space-separated list of URLs to which, when the link is followed, post requests with the bodyping
will be sent- These are typically used for trackers, analytics, and other monitoring purposes
referrerpolicy
specifies how much of the referrer information should be sent when following the linkno-referrer
: TheReferer
header will not be sentno-referrer-when-downgrade
: TheReferer
header will not be sent to a less secure destinationorigin
: Only the origin of the document will be sent (its scheme/protocol, host and port)origin-when-cross-origin
: The full URL will be sent if the destination is the same origin, otherwise only the origin will be sentsame-origin
: The full URL will be sent if the destination is the same origin, otherwise noReferer
header will be sentstrict-origin
: The full URL will be sent if the destination is the same origin, otherwise only the origin will be sentstrict-origin-when-cross-origin
: The full URL will be sent if the destination is the same origin, otherwise only the origin will be sentunsafe-url
: The full URL will be sent, regardless of the destination
rel
specifies the relationship between the current document and the linked documenttarget
specifies where to open the linked document_blank
: Opens the linked document in a new window or tab_self
: Opens the linked document in the same frame as it was clicked_parent
: Opens the linked document in the parent frame_top
: Opens the linked document in the full body of the windowframename
: Opens the linked document in a named frame
- You can also link to sections below with an
href
of#section-name
, where the id is set to another section - Using an
<a>
tag with atarget="_blank"
attribute will open the link in a new tab, with some security considerations- The new tab or window will often have access to the original page, through the
window.opener
property - In a "Tabnabbing" attack, the new tab will change its location to a phishing site, while the original page is still open
- In a "Reverse Tabnabbing" attack, the original (legitimate) page have its location changed to a phishing site, as
the new tab accesses the
window.opener
property - Many browsers have implemented security measures to prevent these attacks, but it's still a good idea to be aware
of the risks, and use
noopener
andnoreferrer
attributes to prevent these attacks
- The new tab or window will often have access to the original page, through the
- If you had a flex container and wanted to ensure that overflowing elements in your flex direction will wrap onto a
following row/column, you can set
flex-wrap: wrap
- So, if you wanted to distribute child div's along a row with following rows for any extra children, you could write:
flex-direction: row; flex-wrap: wrap;
- Conversely, you can also simply set:
flex-flow: row wrap;
- While
null
is a reserved keyword representing the null value, undefined
is a property of the global object representing the absence of a value
- The
draggable
element is useful for creating drag-and-drop functionality in web applications - In addition to setting draggable to true or false, you have to set the
ondragstart
handler for the source element - Finally, you have to handle
ondragover
andondrop
events for the target element(s), since their default behavior is normally not to accept drag events - Pertinent YT vid here: https://www.youtube.com/watch?v=hCsuyZHlUtY
- More about the Drag and Drop API: https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API
-
The flexbox model is one-dimensional, meaning it deals with one dimension at a time
- You're either formatting rows or columns, not both at the same time
-
There is the
main-axis
and thecross-axis
- The
main-axis
is the axis along which the flex items are laid out - The
cross-axis
is the axis perpendicular to the main axis
- The
-
You can define the direction of the main axis with the
flex-direction
propertyrow
,row-reverse
,column
,column-reverse
-
The area of a document that is laid out using flexbox is called a
flex container
- To create a flex container, set the area's
display
property toflex
or `inline-flex
- To create a flex container, set the area's
-
The contents of a flex container will (by default) behave in the following ways:
flex-direction
is set torow
- Items start from the start edge of the main axis
- Items do not stretch on the main dimension, but can shrink
- Items stretch on the cross dimension to fill the container
- The flex-wrap property is set to
nowrap
- Flex items will always remain in a single row or column, overflowing their container if their combined width/height exceeds the containing element width/height.
- Object/Array Destructuring
- Destructuring is a great way to streamline variable assignment off of one source object or array
- Array Destructuring
// very easy if you want to assign variables with the same names as their indices const arr = [1, 2, 3] const [a, b, c] = arr console.log(a, b, c) // 1, 2, 3 let [x,y] = [1]; // x == 1; y == undefined [x,y] = [1,2,3]; // x == 1; y == 2 [,x,,y] = [1,2,3,4]; // x == 2; y == 4 let [x, ...y] = [1,2,3,4]; // y == [2,3,4]
- Object Destructuring
// very easy if you want to assign variables with the same names as their properties const obj = {a: 1, b: 2, c: 3} const {a, b, c} = obj console.log(a, b, c) // 1, 2, 3 // you can also assign variables with different names than their properties const obj2 = {d: 4, e: 5, f: 6} const {d: x, e: y, f: z} = obj2 console.log(x, y, z) // 4, 5, 6 // or destructure functions off of objects for tighter code const {sin, cos, tan} = Math const {floor, ceil, round} = Math // you can even destructure any iterable object, including strings! let [first, ...rest] = "Hello"; // first == "H"; rest == ["e","l","l","o"]
- Array Destructuring
- Destructuring is a great way to streamline variable assignment off of one source object or array
- Audio Elements
<audio>
- The
<audio>
element has no intrinsic visual output of its own unless the controls attribute is specified, in which case the browser's default controls are shown - If you attribute multiple
<source>
elements to an<audio>
element, the browser will choose the first one it can play - Audio elements do not inherently support subtitles or captions (WebVTT)
- You either need to use a
<video>
element or a JavaScript library to add subtitles
- You either need to use a
- There are a number of events emitted by the
<audio>
element, including:onplay
,onpause
,onvolumechange
,onseeking
,onseeked
,onended
,oncanplay
,oncanplaythrough
,onloadedmetadata
,onloadeddata
,onwaiting
,onplaying
,onstalled
,onsuspend
,onabort
,onerror
- The
- The
css justify-content
property defines how the browsers sets the spaces between and around content items along the main (x) axis of a flex containerstart',
end,
center,
space-between,
space-around,
space-evenly,
stretch,
safe,
unsafe`
- The
justify-items
property sets the default alignment for items inside a grid container along the inline (x) axis - The
justify-self
property sets the alignment of an item within its containing grid or flexbox, overriding thejustify-items
property if it's presentauto
,stretch
,center
,start
,end
,flex-start
,flex-end
,baseline
,safe
,unsafe
- You can include multiple variables, multiple loop conditions, and even multiple increment/decrement operators inside
of a
for
loopfunctional = () => { for (let i =1, x = 7; i < 100 && (i % x !== 0); i++, j--) { console.log(i) } }
- Here, we can declare two variables and set two conditions for the loop to run, we could also include multiple
- The
<nav>
element is used to define a set of navigation links - Common examples of navigation sections are menus, tables of contents, and indexes
- The
<nav>
element is intended only for major block of navigation links - Links do not need to be present exclusively inside of a
<nav>
element - A footer may contains links outside of a nav element
- A nav could be used for providing a navbar, or a table of contents within the body of a document
- The
align-content
property sets the distribution of space between and around content items along a flexbox's cross axis, or a grid or block-level element's block axisstart
,end
,center
space-between
,space-around
,space-evenly
,stretch
safe
,unsafe
- safety resets alignment to thestart
value to prevent data loss in the case of overflow, butunsafe
honors the alignment value
- The
align-items
property sets thealign-self
for all direct children as a group - The
align-self
property sets the alignment of an item within its containing flexbox or gridauto
,stretch
,center
,start
,end
,flex-start
,flex-end
,baseline
,safe
,unsafe
- SO Link to more specifically describe how these properties work together: https://stackoverflow.com/questions/31250174/css-flexbox-difference-between-align-items-and-align-content
- Converting Objects to primitive values in JS is very complicated and dependent on the source object
- For instance, a
Date
object has both a numeric and a string representation. Which is its true primitive value? - All Objects converted to a Boolean are true, except for the special cases of
null
andundefined
-
The Prefer-String Algorithm
- First tries the
toString
method, returning this primitive value (even if it is not a string) - If
toString
returns a non-primitive value, it triesvalueOf
method - If
valueOf
returns a non-primitive value, it returns aTypeError
- First tries the
-
The Prefer-Number Algorithm
- First tries the
valueOf
method, returning this primitive value - Next, tries
toString
method - Else, returns a
TypeError
- First tries the
-
The No-Preference Algorithm
- This algorithm depends on the class of the object being converted
- If the object is a Date, it uses the
Prefer-String
algorithm - For any other object, it uses the
Prefer-Number
algorithm
-
This behavior explains why
Number([])
returns 0- First, it tries the
valueOf
method, which returns an empty array, not a primitive value - Next, it tries the
toString
method, which returns an empty string ''
is a primitive value that evaluates to zero as it's converted to a number
- First, it tries the
-
This behavior explains why
Number(['99'])
returns 99- First, it tries the
valueOf
method, which returns an array with a single element - Next, it tries the
toString
method, which returns a string with a single element '99'
is a primitive value that evaluates to 99 as it's converted to a number
- First, it tries the
-
- The
<input type="password"/>
input type "password" can be used to obfuscate user input in a form - Its attributes include:
- value
- maxlength
- minlength
- pattern - a Regex pattern specifying the input format required for form validation
- placeholder
- readonly
- size - the character width of the input field
- autocomplete - whether the browser will allow autocomplete in the field
- on - allow browser/password manager to input passwords
- off - don't allow
- current-password - allow password manager to enter existing passwords only
- new-password - allow password manager to enter new passwords only
- The outline property is a shorthand for the 3 outline properties:
- outline-color - defaults to either invert or currentColor, depending on browser compatibility
- outline-width - defaults to medium if unspecified
- outline-style - defaults to none if unspecified
- 8 other styles to be used for aesthetic sugar
- Instead of manually setting each property, the outline property can be used to set all three at once
outline:
5
px solid red
;
- The global functions
parseInt()
andparseFloat()
can be used to converted strings with leading numbers into either integers or floating point numbers
parseInt('34 tribes') // returns 34
parseFloat('3.14 pies') // returns 3.14
parseInt('3.14 pies') // returns 3
parseFloat('.14') // return 0.14, because the first character is NaN
parseInt('.14') // returns NaN, because integers can't start with '.'
parseFloat('$14') // returns NaN, because numbers can't start with '$'
tabIndex
is a global attribute attributable to almost all HTML elements (besides<dialog>
)- It defines whether an element is focusable by sequential tab navigation
- May still be focusable using clicks or the
focus()
method
- May still be focusable using clicks or the
- The nearest positive value to zero is focused first, followed by sequentially higher positive values, then zero
- Any negative tabindex value will never be focused
<input tabIndex="0">Last</input>
<input tabIndex="-1">Not tabbable </input>
<input tabIndex="2">Second</input>
<input tabIndex="1">First</input>
<input tabIndex="-3">Not tabbable</input>
- The difference between
em
andrem
units are thatem
refers to an element's parent's font size, while arem
refers to the root element's (the HTML document's) font size
-
- The unary + operator
(+x)
will convert a value to a number (equivalent ofNumber(x)
) - JS Symbols
- The unary + operator
- Numbers have a toString method that accepts a radix (or base) as an argument and returns a number in Base Radix
let n = 17;
let binary = "0b" + n.toString(2); // binary == "0b10001"
let octal = "0o" + n.toString(8); // octal == "0o21"
let hex = "0x" + n.toString(16); // hex == "0
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>