let age = 28; // Number
let name = "Joe"; // string
let name = { // object
firstName : "Joe",
lastName : "Smith"
};
let truth = true; // boolean
let sheets = [ "Linux", "Apache", "MySQL", "PHP" ]; // array
var a;
typeof a; // "undefined"
var a = null; // value null
var
- Can be reassigned but only accessed within a function. Variables defined with var move to the top when code is executed (hoisting)const
- Cannot be reassigned and not accessible before they appear within the codelet
- Similar to const, however, let variable can be reassigned but not re-declared
var a; // variable
var b = "good"; // string
var c = "Hi" + "" + "Joe"; // "Hi Joe"
var d = 1 + 2 + "4"; // "34"
var e = [8, 4, 3, 2]; // array
var f = true; // boolean
var g = /\s/; // RegEx (regular expression)
var h = function(){}; // function object
const PI = 3.141; // constant
var a = 1, b = 2, c = a + b; // multiple variables on one line
let y = 'zzz'; // block scope local variable
+
— Addition-
— Subtraction*
— Multiplication/
— Division(...)
— Grouping operator, operations within brackets are executed earlier than those outside%
— Modulus (remainder )++
— Increment numbers--
— Decrement numbers
==
— Equal to===
— Equal value and equal type!=
— Not equal!==
— Not equal value or not equal type>
— Greater than<
— Less than>=
— Greater than or equal to<=
— Less than or equal to?
— Ternary operator
&&
— Logical and||
— Logical or!
— Logical not
&
— AND statement|
— OR statement~
— NOT^
— XOR<<
— Left shift>>
— Right shift>>>
— Zero fill right shift
MAX_VALUE — The maximum numeric value representable in JavaScript MIN_VALUE — Smallest positive numeric value representable in JavaScript NaN — The “Not-a-Number” value NEGATIVE_INFINITY — The negative Infinity value POSITIVE_INFINITY — Positive Infinity value
toExponential
- Returns a string representing the Number object in exponential notationtoFixed
- formats a number using fixed-point notationtoPrecision
- returns a string representing the Number object to the specified precisiontoString
- returns a string representing the specifies Number objectvalueOf
- returns the wrapped primitive value of a number object
E
— Euler’s numberLN2
— The natural logarithm of 2LN10
— Natural logarithm of 10LOG2E
— Base 2 logarithm of ELOG10E
— Base 10 logarithm of EPI
— The number PISQRT1_2
— Square root of 1/2SQRT2
— The square root of 2
abs(x)
— Returns the absolute (positive) value of xacos(x)
— The arccosine of x, in radiansasin(x)
— Arcsine of x, in radiansatan(x)
— The arctangent of x as a numeric valueatan2(y,x)
— Arctangent of the quotient of its argumentsceil(x)
— Value of x rounded up to its nearest integercos(x)
— The cosine of x (x is in radians)exp(x)
— Returns e^x, where e is Eulers numberfloor(x)
— The value of x rounded down to its nearest integerlog(x)
— The natural logarithm (base E) of x of 1224max(x,y,z,...,n)
— Returns the number with the highest valuemin(x,y,z,...,n)
— Same for the number with the lowest valuepow(x,y)
— X to the power of yrandom()
— Returns a random number between 0 and 1round(x)
— The value of x rounded to its nearest integersin(x)
— The sine of x (x is in radians)sqrt(x)
— Square root of xtan(x)
— The tangent of an angle
'
— Single quote"
— Double quote\
— Backslash\b
— Backspace\f
— Form feed\n
— New line\r
— Carriage return\t
— Horizontal tabulator\v
— Vertical tabulator
charAt
- Returns the character at the specified indexcharCodeAt
— Gives you the unicode of character at that positionfromCharCode
— Returns a string created from the specified sequence of UTF-16 code unitsconcat
- Joins two or more strings, and returns a copy of the joined stringsreplace
- Searches for a match between a substring (or regex) and a string and replaces the matched substring with a new substringsearch
- Searches for a match between a regex and a string, and returns the position of the matchslice
- Extracts a part of a string and returns a new stringtrim
- Removes whitespace from both ends of a stringsubstr
- Extracts the character from a string, beginning at a specified start position, and through the specified number of charactersubstring
— Also similar to slice() but can’t accept negative indicestoLowerCase
- Converts a string to lowercase letterstoUpperCase
- Converts a string to uppercase lettersindexOf
— Provides the position of the first occurrence of a specified text within a stringlastIndexOf
— Same as indexOf() but with the last occurrence, searching backwardsmatch
— Retrieves the matches of a string against a search patternsplit
— Splits a string object into an array of strings at a specified positionvalueOf
— Returns the primitive value (that has no properties or methods) of a string object
concat
- Joins two or more arrays, and returns a copy of the joined arrayindexOf
- Search the array for an element and returns its positionjoin
- Joins all elements of an array into a stringpop
- Removes the last element of an array, and returns that elementreverse
- Reverses the order of the elements in an arrayshift
- Removes the first element of an array, and returns that elementsort
- Sorts the element of an arraytoString
- Converts an array to string, and returns the result
decodeURI
— Decodes a Uniform Resource Identifier (URI) created by encodeURI or similardecodeURIComponent
— Decodes a URI componentencodeURI
— Encodes a URI into UTF-8encodeURIComponent
— Same but for URI componentseval
— Evaluates JavaScript code represented as a stringisFinite
— Determines whether a passed value is a finite numberisNaN
— Determines whether a value is NaN or notNumber
—- Returns a number converted from its argumentparseFloat
— Parses an argument and returns a floating-point numberparseInt
— Parses its argument and returns an integer
if (condition) {
// what to do if condition is met
} else if (condition2) {
// what to do if condition2 is met
} else {
// what to do if condition is not met
}
// input is current day
switch (new Date().getDay()) {
case 6: // if (day == 6)
text = "Saturday";
break;
case 0: // if (day == 0)
text = "Sunday";
break;
default: // else...
text = "if no other matches";
}
let a = [1, 2, 3];
let sum = 0;
for (let i - 0; i <a.length; i++) {
sum += a[i];
}
console.log(sum);
let i = 1;
while (i < 100) {
i *= 2;
console.log(i + ", ");
}
var i = 1;
do (i < 100) {
i *= 2;
console.log(i + ", ");
} while (1 < 100);
for (let i = 0; i < 10; i++) {
if (i == 5) {
break;
}
console.log(i + ", ");
}
for (let i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
console.log(i + ", ");
}
getFullYear
- Returns the year of the specified date according to local timegetMonth
- Returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).getDate
- Returns the day of the month for the specified date according to local timegetHours
- Returns the hour for the specified date, according to local timegetMinutes
- Returns the minutes in the specified date according to local timegetSeconds
- Returns the seconds in the specified date according to local time
- Regular expressions are search patterns used to match character combinations in strings. The search pattern can be used for text search and text to replace operations.
e
— Evaluate replacementi
— Perform case-insensitive matchingg
— Perform global matchingm
— Perform multiple line matchings
— Treat strings as a single linex
— Allow comments and whitespace in the patternU
— Ungreedy pattern
[abc]
— Find any of the characters between the brackets[^abc]
— Find any character which is not in the brackets[0-9]
— Used to find any digit from 0 to 9[A-z]
— Find any character from uppercase A to lowercase z(a|b|c)
— Find any of the alternatives separated with |
.
— Find a single character, except newline or line terminator\w
— Word character\W
— Non-word character\d
— A digit\D
— A non-digit character\s
— Whitespace character\S
— Non-whitespace character\b
— Find a match at the beginning/end of a word\B
— A match not at the beginning/end of a word\0
— NUL character\n
— A new line character\f
— Form feed character\r
— Carriage return character\t
— Tab character\v
— Vertical tab character\xxx
— The character specified by an octal number xxx\xdd
— Character specified by a hexadecimal number dd\uxxxx
— The Unicode character specified by a hexadecimal number XXXX
n+
— Matches any string that contains at least one nn*
— Any string that contains zero or more occurrences of nn?
— A string that contains zero or one occurrence of nn{X}
— String that contains a sequence of X n’sn{X,Y}
— Strings that contain a sequence of X to Y n’sn{X,}
— Matches any string that contains a sequence of at least X n’sn$
— Any string with n at the end of it^n
— String with n at the beginning of it?=n
— Any string that is followed by a specific string n?!n
— String that is not followed by a specific string ni
- The DOM is the Document Object Model of a page. It represents the structure of a webpage. JS comes with a lot of different ways to create and manipulate HTML elements (called nodes).
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
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
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
- JavaScript is also able to take into account the user browser and incorporate its properties into the code.
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 as screenLeft but needed for some browsersscreenY
— Same as screenTop 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
alert
— Displays an alert box with a message and an OK buttonblur
— Removes focus from the current windowclearInterval
— Clears a timer set with setInterval()clearTimeout
— Clears a timer set with setTimeout()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
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
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
onkeydown
— When the user is pressing a key downonkeypress
— The moment the user starts pressing a keyonkeyup
— The user releases a key
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
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
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
oncopy
— User copies the content of an elementoncut
— The user cuts an element’s contentonpaste
— A user pastes the content in an element
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)
animationend
— A CSS animation is completeanimationiteration
— CSS animation is repeatedanimationstart
— CSS animation has started
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
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
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 the eval() functionRangeError
— A number is “out of range”ReferenceError
— An illegal reference has occurredSyntaxError
— A syntax error has occurredTypeError
— A type error has occurredURIError
— An encodeURI() error has occurred
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
// Result: a 50/50 change on returning true of false
Array.from({ length: 3 }, Math.random)
// [ 0.027519891180024736, 0.7477909353302613, 0.6261696776859895 ]
const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 12)));
// true (Tuesday)
console.log(isWeekday(new Date(2021, 0, 9)));
// false (Saturday)
Array.from({ length: 2 }, (v, i) => i)
// [ 0, 1 ]
const reverse = str => str.split('').reverse().join('');
reverse('hello world');
// 'DLROW OLLEH'
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
// Result: returns true or false depending on if tab is in view / focus
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// true
console.log(isEven(3));
// false
const isValidURL = (url) => {
try {
new URL(url);
return true;
} catch (error) {
return false;
}
};
isValidURL("https://dev.to");
// true
isValidURL("https//blah");
// false
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0)));
// 17:30:00
console.log(timeFromDate(new Date()));
// will log the current time (e. g. 16:07:06)
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
toFixed(15.912321213, 1); // 15.9
toFixed(15.912321213, 2); // 15.91
toFixed(15.912321213, 3); // 15.912
toFixed(15.912321213, 4); // 15.9123
toFixed(15.912321213, 5); // 15.91232
toFixed(15.912321213, 6); // 15.912321
const fromAgo = (date) => {
const ms = Date.now() - date.getTime();
const seconds = Math.round(ms / 1000);
const minutes = Math.round(ms / 60000);
const hours = Math.round(ms / 3600000);
const days = Math.round(ms / 86400000);
const months = Math.round(ms / 2592000000);
const years = Math.round(ms / 31104000000);
switch (true) {
case seconds < 60:
return `${seconds} second(s) ago"`;
case minutes < 60:
return `${minutes} minute(s) ago"`;
case hours < 24:
return `${hours} hour(s) ago"`;
case days < 30:
return `${days} day(s) ago`;
case months < 12:
return `${months} month(s) ago`;
default:
return `${years} year(s) ago`;
}
};
const createdAt = new Date(2020, 1, 7);
fromAgo(createdAt); // 1 year(s) ago
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement);
// Result: will return true if in focus, false if not in focus
const generatePath = (path, obj) =>
path.replace(/(\:[a-z]+)/g, (v) => obj[v.substr(1)]);
const route = "/api/:page/:id";
generatePath(route, {
page: "items",
id: 12855,
});
// /api/items/12855
let touchSupported = () => {
if ('ontouchstart' in window) {
return true;
} else if (typeof(window.DocumentTouch) !== 'undefined' && window.DocumentTouch && document instanceof window.DocumentTouch) {
return true;
}
return false;
}
console.log(touchSupported());
// Result: will return true if touch events are supported, false if not
let isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device
const getPathParams = (path, pathMap, serializer) => {
path = path.split("/");
pathMap = pathMap.split("/");
return pathMap.reduce((acc, crr, i) => {
if (crr[0] === ":") {
const param = crr.substr(1);
acc[param] = serializer && serializer[param]
? serializer[param](path[i])
: path[i];
}
return acc;
}, {});
};
getPathParams("/app/products/123", "/app/:page/:id");
// { page: 'products', id: '123' }
getPathParams("/items/2/id/8583212", "/items/:category/id/:id", {
category: v => ['Car', 'Mobile', 'Home'][v],
id: v => +v
});
// { category: 'Home', id: 8583212 }
const generatePathQuery = (path, obj) =>
path +
Object.entries(obj)
.reduce((total, [k, v]) => (total += `${k}=${encodeURIComponent(v)}&`), "?")
.slice(0, -1);
generatePathQuery("/person", { personname: "joe smith", personage: 40 });
// "/person?personname=joe%20smith&personage=40"
const getQueryParams = url =>
url.match(/([^?=&]+)(=([^&]*))/g).reduce((total, crr) => {
const [key, value] = crr.split("=");
total[key] = value;
return total;
}, {});
getQueryParams("/user?lastname=smith&userage=40");
// { lastname: 'smith', userage: '40' }
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll the browser to the top of the page
// NOTE: not supported on Internet Explorer
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 5.5