Dealing with Dates in JavaScript
You can also work with and modify dates and time with JavaScript. This is the next chapter in the JavaScript cheat sheet.
Setting Dates
Date()
— Creates a new date object with the current date and timeDate(2017, 5, 21, 3, 23, 10, 0)
— Create a custom date object. The numbers represent a year, month, day, hour, minutes, seconds, milliseconds. You can omit anything you want except for a year and month.Date("2017-06-23")
— Date declaration as a string
Pulling Date and Time Values
getDate()
— Get the day of the month as a number (1-31)getDay()
— The weekday as a number (0-6)getFullYear()
— Year as a four-digit number (yyyy)getHours()
— Get the hour (0-23)getMilliseconds()
— The millisecond (0-999)getMinutes()
— Get the minute (0-59)getMonth()
— Month as a number (0-11)getSeconds()
— Get the second (0-59)getTime()
— Get the milliseconds since January 1, 1970getUTCDate()
— The day (date) of the month in the specified date according to universal time (also available for day, month, full year, hours, minutes etc.)parse
— Parses a string representation of a date and returns the number of milliseconds since January 1, 1970
Set Part of a Date
setDate()
— Set the day as a number (1-31)setFullYear()
— Sets the year (optionally month and day)setHours()
— Set the hour (0-23)setMilliseconds()
— Set milliseconds (0-999)setMinutes()
— Sets the minutes (0-59)setMonth()
— Set the month (0-11)setSeconds()
— Sets the seconds (0-59)setTime()
— Set the time (milliseconds since January 1, 1970)setUTCDate()
— Sets the day of the month for a specified date according to universal time (also available for day, month, full year, hours, minutes etc.)
DOM Mode
The DOM is the Document Object Model of a page. It is the code of the structure of a webpage. JavaScript comes with a lot of different ways to create and manipulate HTML elements (called nodes).
Node Properties
attributes
— Returns a live collection of all attributes registered to an elementbaseURI
— Provides the absolute base URL of an HTML elementchildNodes
— Gives a collection of an element’s child nodesfirstChild
— Returns the first child node of an elementlastChild
— The last child node of an elementnextSibling
— Gives you the next node at the same node tree levelnodeName
—Returns the name of a nodenodeType
— Returns the type of a nodenodeValue
— Sets or returns the value of a nodeownerDocument
— The top-level document object for this nodeparentNode
— Returns the parent node of an elementpreviousSibling
— Returns the node immediately preceding the current onetextContent
— Sets or returns the textual content of a node and its descendants
Node Methods
appendChild()
— Adds a new child node to an element as the last child nodecloneNode()
— Clones an HTML elementcompareDocumentPosition()
— Compares the document position of two elementsgetFeature()
— Returns an object which implements the APIs of a specified featurehasAttributes()
— Returns true if an element has any attributes, otherwise falsehasChildNodes()
— Returns true if an element has any child nodes, otherwise falseinsertBefore()
— Inserts a new child node before a specified, existing child nodeisDefaultNamespace()
— Returns true if a specified namespaceURI is the default, otherwise falseisEqualNode()
— Checks if two elements are equalisSameNode()
— Checks if two elements are the same nodeisSupported()
— Returns true if a specified feature is supported on the elementlookupNamespaceURI()
— Returns the namespace URI associated with a given nodelookupPrefix()
— Returns a DOMString containing the prefix for a given namespace URI if presentnormalize()
— Joins adjacent text nodes and removes empty text nodes in an elementremoveChild()
— Removes a child node from an elementreplaceChild()
— Replaces a child node in an element
Element Methods
getAttribute()
— Returns the specified attribute value of an element nodegetAttributeNS()
— Returns string value of the attribute with the specified namespace and namegetAttributeNode()
— Gets the specified attribute nodegetAttributeNodeNS()
— Returns the attribute node for the attribute with the given namespace and namegetElementsByTagName()
— Provides a collection of all child elements with the specified tag namegetElementsByTagNameNS()
— Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespacehasAttribute()
— Returns true if an element has any attributes, otherwise falsehasAttributeNS()
— Provides a true/false value indicating whether the current element in a given namespace has the specified attributeremoveAttribute()
— Removes a specified attribute from an elementremoveAttributeNS()
— Removes the specified attribute from an element within a certain namespaceremoveAttributeNode()
— Takes away a specified attribute node and returns the removed nodesetAttribute()
— Sets or changes the specified attribute to a specified valuesetAttributeNS()
— Adds a new attribute or changes the value of an attribute with the given namespace and namesetAttributeNode()
— Sets or changes the specified attribute nodesetAttributeNodeNS()
— Adds a new namespaced attribute node to an element
Working with the User Browser
Besides HTML elements, JavaScript is also able to take into account the user browser and incorporate its properties into the code.
Window Properties
closed
— Checks whether a window has been closed or not and returns true or falsedefaultStatus
— Sets or returns the default text in the status bar of a windowdocument
— Returns the document object for the windowframes
— Returns all<iframe>
elements in the current windowhistory
— Provides the History object for the windowinnerHeight
— The inner height of a window’s content areainnerWidth
— The inner width of the content arealength
— Find out the number of<iframe>
elements in the windowlocation
— Returns the location object for the windowname
— Sets or returns the name of a windownavigator
— Returns the Navigator object for the windowopener
— Returns a reference to the window that created the windowouterHeight
— The outer height of a window, including toolbars/scrollbarsouterWidth
— The outer width of a window, including toolbars/scrollbarspageXOffset
— Number of pixels the current document has been scrolled horizontallypageYOffset
— Number of pixels the document has been scrolled verticallyparent
— The parent window of the current windowscreen
— Returns the Screen object for the windowscreenLeft
— The horizontal coordinate of the window (relative to the screen)screenTop
— The vertical coordinate of the windowscreenX
— Same asscreenLeft
but needed for some browsersscreenY
— Same asscreenTop
but needed for some browsersself
— Returns the current windowstatus
— Sets or returns the text in the status bar of a windowtop
— Returns the topmost browser window
Window Methods
alert()
— Displays an alert box with a message and an OK buttonblur()
— Removes focus from the current windowclearInterval()
— Clears a timer set withsetInterval()
clearTimeout()
— Clears a timer set withsetTimeout()
close()
— Closes the current windowconfirm()
— Displays a dialogue box with a message and an OK and Cancel buttonfocus()
— Sets focus to the current windowmoveBy()
— Moves a window relative to its current positionmoveTo()
— Moves a window to a specified positionopen()
— Opens a new browser windowprint()
— Prints the content of the current windowprompt()
— Displays a dialogue box that prompts the visitor for inputresizeBy()
— Resizes the window by the specified number of pixelsresizeTo()
— Resizes the window to a specified width and heightscrollBy()
— Scrolls the document by a specified number of pixelsscrollTo()
— Scrolls the document to specified coordinatessetInterval()
— Calls a function or evaluates an expression at specified intervalssetTimeout()
— Calls a function or evaluates an expression after a specified intervalstop()
— Stops the window from loading
Screen Properties
availHeight
— Returns the height of the screen (excluding the Windows Taskbar)availWidth
— Returns the width of the screen (excluding the Windows Taskbar)colorDepth
— Returns the bit depth of the color palette for displaying imagesheight
— The total height of the screenpixelDepth
— The color resolution of the screen in bits per pixelwidth
— The total width of the screen
JavaScript Events
Events are things that can happen to HTML elements and are performed by the user. The programming language can listen for these events and trigger actions in the code. No JavaScript cheat sheet would be complete without them.
Mouse
onclick
— The event occurs when the user clicks on an elementoncontextmenu
— User right-clicks on an element to open a context menuondblclick
— The user double-clicks on an elementonmousedown
— User presses a mouse button over an elementonmouseenter
— The pointer moves onto an elementonmouseleave
— Pointer moves out of an elementonmousemove
— The pointer is moving while it is over an elementonmouseover
— When the pointer is moved onto an element or one of its childrenonmouseout
— User moves the mouse pointer out of an element or one of its childrenonmouseup
— The user releases a mouse button while over an element
Keyboard
onkeydown
— When the user is pressing a key downonkeypress
— The moment the user starts pressing a keyonkeyup
— The user releases a key
Frame
onabort
— The loading of a media is abortedonbeforeunload
— Event occurs before the document is about to be unloadedonerror
— An error occurs while loading an external fileonhashchange
— There have been changes to the anchor part of a URLonload
— When an object has loadedonpagehide
— The user navigates away from a webpageonpageshow
— When the user navigates to a webpageonresize
— The document view is resizedonscroll
— An element’s scrollbar is being scrolledonunload
— Event occurs when a page has unloaded
Form
onblur
— When an element loses focusonchange
— The content of a form element changes (for<input>
,<select>
and<textarea>
)onfocus
— An element gets focusonfocusin
— When an element is about to get focusonfocusout
— The element is about to lose focusoninput
— User input on an elementoninvalid
— An element is invalidonreset
— A form is resetonsearch
— The user writes something in a search field (for<input="search">
)onselect
— The user selects some text (for<input>
and<textarea>
)onsubmit
— A form is submitted
Drag
ondrag
— An element is draggedondragend
— The user has finished dragging the elementondragenter
— The dragged element enters a drop targetondragleave
— A dragged element leaves the drop targetondragover
— The dragged element is on top of the drop targetondragstart
— User starts to drag an elementondrop
— Dragged element is dropped on the drop target
Clipboard
oncopy
— User copies the content of an elementoncut
— The user cuts an element’s contentonpaste
— A user pastes the content in an element
Media
onabort
— Media loading is abortedoncanplay
— The browser can start playing media (e.g. a file has buffered enough)oncanplaythrough
— The browser can play through media without stoppingondurationchange
— The duration of the media changesonended
— The media has reached its endonerror
— Happens when an error occurs while loading an external fileonloadeddata
— Media data is loadedonloadedmetadata
— Metadata (like dimensions and duration) are loadedonloadstart
— The browser starts looking for specified mediaonpause
— Media is paused either by the user or automaticallyonplay
— The media has been started or is no longer pausedonplaying
— Media is playing after having been paused or stopped for bufferingonprogress
— The browser is in the process of downloading the mediaonratechange
— The playing speed of the media changesonseeked
— User is finished moving/skipping to a new position in the mediaonseeking
— The user starts moving/skippingonstalled
— The browser is trying to load the media but it is not availableonsuspend
— The browser is intentionally not loading mediaontimeupdate
— The playing position has changed (e.g. because of fast forward)onvolumechange
— Media volume has changed (including mute)onwaiting
— Media paused but expected to resume (for example, buffering)
Animation
animationend
— A CSS animation is completeanimationiteration
— CSS animation is repeatedanimationstart
— CSS animation has started
Other
transitionend
— Fired when a CSS transition has completedonmessage
— A message is received through the event sourceonoffline
— The browser starts to work offlineononline
— The browser starts to work onlineonpopstate
— When the window’s history changesonshow
— A<menu>
element is shown as a context menuonstorage
— A Web Storage area is updatedontoggle
— The user opens or closes the<details>
elementonwheel
— Mouse wheel rolls up or down over an elementontouchcancel
— Screen-touch is interruptedontouchend
— User’s finger is removed from a touch-screenontouchmove
— A finger is dragged across the screenontouchstart
— A finger is placed on the touch-screen
Errors
When working with JavaScript, different errors can occur. There are several ways of handling them:
try
— Lets you define a block of code to test for errorscatch
— Set up a block of code to execute in case of an errorthrow
— Create custom error messages instead of the standard JavaScript errorsfinally
— Lets you execute code, after try and catch, regardless of the result
Error Name Values
JavaScript also has a built-in error object. It has two properties:
name
— Sets or returns the error namemessage
— Sets or returns an error message in a string from
The error property can return six different values as its name:
EvalError
— An error has occurred in theeval()
functionRangeError
— A number is “out of range”ReferenceError
— An illegal reference has occurredSyntaxError
— A syntax error has occurredTypeError
— A type error has occurredURIError
— AnencodeURI()
error has occurred
Explicit Conversions
The simplest way to perform an explicit type conversion is to use the Boolean(), Number()
, and String()
functions.
Any value other than null
or undefined
has atoString()
method.
n.toString(2);
binary
n.toString(8);
octal
n.toString(16);
hex
let n = 123456.789;
n.toFixed(0)
“123457”
n.toFixed(5)
“123456.78900”
n.toExponential(3)
“1.235e+5”
n.toPrecision(7)
“123456.8”
n.toPrecision(10)
parseInt("3 blind mice")
3
parseFloat(" 3.14 meters")
3.14
parseInt("-12.34")
-12
parseInt("0xFF")
255
Types, Values, and Variables
Links
Resource
URL
MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript
Run Snippets
https://developers.google.com/web/tools/chrome-devtools/javascript/snippets
Explicit Conversions
The simplest way to perform an explicit type conversion is to use the Boolean(), Number()
, and String()
functions.
Any value other than null
or undefined
has atoString()
method.
n.toString(2);
binary
n.toString(8);
octal
n.toString(16);
hex
let n = 123456.789;
n.toFixed(0)
“123457”
n.toFixed(5)
“123456.78900”
n.toExponential(3)
“1.235e+5”
n.toPrecision(7)
“123456.8”
n.toPrecision(10)
parseInt("3 blind mice")
3
parseFloat(" 3.14 meters")
3.14
parseInt("-12.34")
-12
parseInt("0xFF")
255
parseInt("0xff")
255
parseInt("-0XFF")
-255
parseInt("0.1")
0
parseInt(".1")
NaN: integers can’t start with “.”
parseFloat("$72.47")
NaN: numbers can’t start with “$”
Supply Radix
parseInt("11", 2)
3
parseInt("ff", 16)
255
parseInt("077", 8)
63
Conversion Idioms
x + ""
String(x)
+x
Number(x)
x-0
Number(x)
!!x
Boolean(x)
Destructuring Assignment
let [x,y] = [1,2];
let x=1, y=2
[x,y] = [x + 1,y + 1];
x = x + 1, y = y + 1
[x,y] = [y,x];
Swap the value of the two variables
Destructuring assignment makes it easy to work with functions that return arrays of values:
let [r,theta] = toPolar(1.0, 1.0);
function toPolar(x, y) {
return [Math.sqrt(x*x+y*y), Math.atan2(y,x)];
}
Variable destructuring in loops:
let o = { x: 1, y: 2 };
for(const [name, value] of Object.entries(o)) {
console.log(name, value); // Prints "x 1" and "y 2"
}
Note: The Object.entries()
method returns an array of a given object's own enumerable string-keyed property [key, value]
pairs, in the same order as that provided by a for...in
loop. (The only important difference is that a for...in
loop enumerates properties in the prototype chain as well).
The list of variables on the left can include extra commas to skip certain values on the right
[,x,,y] = [1,2,3,4];
x == 2; y == 4
Note: the last comma does not stand for a value.
To collect all unused or remaining values into a single variable when destructuring an array, use three dots (...)
before the last variable name on the left-hand side
let [x, ...y] = [1,2,3,4];
y == [2,3,4]
let [first, ...rest] = "Hello";
first == “H”; rest ==[“e”,”l”,”l”,”o”]
Destructuring assignment can also be performed when the righthand side is an object value.
let transparent = {r: 0.0, g: 0.0, b: 0.0, a: 1.0};
let {r, g, b} = transparent;
r == 0.0; g == 0.0; b == 0.0
const {sin, cos, tan} = Math;
sin=Math.sin, cos=Math.cos, tan=Math.tan
Expressions and Operators
In JavaScript, the values null
and undefined
are the only two values that do not have properties. In a regular property access expression using . or [], you get a TypeError
if the expression on the left evaluates to null
or undefined
. You can use ?.
and ?.[]
syntax to guard against errors of this type.
You can also invoke a function using ?.()
instead of ()
.
With the new ?.()
invocation syntax, if the expression to the left of the ?.
evaluates to null
or undefined
, then the entire invocation expression evaluates to undefined
and no exception is thrown.
Write the function invocation using ?.(),
knowing that invocation will only happen if there is actually a value to be invoked
function square(x, log) {
log?.(x); // Call the function if there is one
return x * x;
}
Note that expression x++
is not always the same as x = x + 1
.The ++
operator never performs string concatenation: it always converts its operand to a number and increments it. If x is the string "1", ++x
is the number 2, butx + 1
is the string "11".
JavaScript objects are compared by reference, not by value. An object is equal to itself, but not to any other object. If two distinct objects have the same number of properties, with the same names and values, they are still not equal. Similarly, two arrays that have the same elements in the same order are not equal to each other.
NaN
value is never equal to any other value, including itself! To check whether a value x
is NaN
, use x !==
, or the global isNaN()
function.
If both values refer to the same object, array, or function, they are equal. If they refer to different objects, they are not equal, even if both objects have identical properties.
Evaluating Expressions
JavaScript has the ability to interpret strings of JavaScript source code, evaluating them to produce a value.
eval("3+2")
Because of security issues, some web servers use the HTTP “Content-Security-Policy” header to disableeval()
for an entire website.
First-Defined (??)
The first-defined operator ??
evaluates to its first defined operand: if its left operand is not null
and not undefined
, it returns that value.
a ?? b
is equivalent to (a !== null && a !== undefined) ? a : b
??
is a useful alternative to ||.
The problem with this idiomatic use is that zero, the empty string, and false are all falsy
values that may be perfectly valid in some circumstances. In this code example, if maxWidth
is zero, that value will be ignored. But if we change the ||
operator to ??
, we end up with an expression where zero is a valid value.
let max = maxWidth || preferences.maxWidth || 500;
let max = maxWidth ?? preferences.maxWidth ?? 500;
delete Operator
Deleting an array element leaves a “hole” in the array and does not change the array’s length. The resulting array is sparse.
void Operator
Using the void
operator makes sense only if the operand has side effects.
let counter = 0;
const increment = () => void counter++;
increment()
undefined
counter
1