JavaScript cookbook
Generate an array with a predetermined number of elements
Use the Array.from()
method and pass as the 1st argument an object with a length property: { length: <desired array length> }
Array.from({ length: 5 }, () => 'arrCont')
// [ "arrCont", "arrCont", "arrCont", "arrCont", "arrCont" ]
Generate a random number
function rNum(l) {
return Math.floor(Math.random() * l) + 1;
}
Where l
sets an upper limit.
Create & use a constructor function
Constructor functions let let us define a blueprint for an object, and generate new instances of that object with varying parameters. For example:
// we define the blueprint for our reusable object. notice the capital "M"!
function MovieDbEntry (title, director, year, genre) {
// we create the object's properties and map them to the constructor's parameters
this.movieTitle = title;
this.movieDirector = director;
this.movieYear = year;
this.movieGenre = genre;
// we can even add built-in methods
this.logMovie = function() {
console.log(
'Added new movie!\n' +
title + ', by ' + director + ', year ' + year
);
}
}
We can now create instances of our object, with the new
keyword.
var movie_01 = new MovieDbEntry('Apocalypse Now', 'Francis Ford Coppola', 1979, 'Drama, War');
The data type is, as we might expect, an object:
console.log('typeof(movie_01): ' + typeof(movie_01));
// typeof(movie_01): object
If we print our newly-generated obj to the console, we can see its parent constructor, as well as the object's properties and values
console.log(movie_01);
/*
MovieDbEntry {
movieTitle: 'Apocalypse Now',
movieDirector: 'Francis Ford Coppola',
movieYear: 1979,
movieGenre: 'Drama, War',
logMovie: [Function] }
*/
If we try to access one of the obj's properties, we can see they have been mapped to the constructor's parameters:
console.log('movie_01.movieTitle: ' + movie_01.movieTitle);
// movie_01.movieTitle: Apocalypse Now
Finally, we can execute our built-in method:
// executing a method
movie_01.logMovie();
/*
Added new movie!
Apocalypse Now, by Francis Ford Coppola, year 1979
*/
Print to the console with rich output
console.table()
prints tabular outputconsole.dir()
prints extended info (?)
Access the keycode of a pressed key
Use .keyCode
, a property of the "event" object;
MDN: "The KeyboardEvent.keyCode read-only property represents a system and implementation dependent numerical code identifying the unmodified value of the pressed key"
Send requests to a server
Use XMLHttpRequest objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This is a predefined JS object and constructor. […] XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment. link
var sendRequest = {
queryServer() {
let request = new XMLHttpRequest();
// note: .open "Initializes a request"
// we feed the API request URI to the XMLHttpRequest() method
request.open("GET", uri, true);
// .onload is an event handler
request.onload = () => {
// code
};
// .onerror is an event handler
request.onerror = () => {
// code
}
// .send "Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent."
request.send();
}
};
Enable the debugger in dev tools
Add debugger;
inside the code you want to debug; this will enable a step-by-step execution of the code.
Concatenate elements of an array
Use .join()
; "The join() method joins all elements of an array (or an array-like object) into a string."
var charPool = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
console.log(charPool);
// w/o string separator
var joinedElems = charPool.join();
// a,b,c,d,e,f,g,h,i
// w/ an empty string separator
joinedElems = charPool.join('');
// abcdefghi
// w/ a non-empty string separator
joinedElems = charPool.join('-');
// a-b-c-d-e-f-g-h-i
console.log(joinedElems);
Convert a string to a number
Use .parseInt()
var myVar = "999";
console.log(`Now it's a string… > ${typeof(myVar)}: ${myVar}`);
// Now it's a string… > string: 999
var varConvert = parseInt(myVar);
console.log(`And now it's a number! > ${typeof(varConvert)}: ${varConvert}`);
// And now it's a number! > number: 999
Add an event listener to a DOM element
Use addEventListener(event, callback)
;
MDN: The EventTarget.addEventListener() method adds the specified EventListener-compatible object to the list of event listeners for the specified event type on the EventTarget on which it's called. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).
let domTarget = document.querySelector('ul');
domTarget.addEventListener('click', (e) => {
// callback function, which passes an "event" object
});
Also consider calling a function directly from a DOM element, with the onclick=""
attribute.
// Instead of this:
var inputButton = document.getElementById('input-button');
inputButton.addEventListener('click', () => { // callback });
// consider this:
// HTML
<button id="input-button" onclick="functionHere()">Click me</button>
Append a child element to a DOM element
Use .appendChild
var domTarget = document.getElementById('list-container');
var generatedElem = document.createElement('li');
domTarget.appendChild(generatedElem);
Set the text content of a DOM element
Use .textContent
var domTarget = /* select a DOM elem */
domTarget.textContent = '' /* enter text content */
Toggle a class on a DOM element
const el = document.querySelector('body');
el.classList.toggle('selected');
Add, remove, toggle a class on a DOM element
Use .className
var domTarget = /* select a DOM elem */
domTarget.className = '' /* enter a class */
Or:
.classList.add()
.classList.remove()
.classList.toggle()
MDN: The Element.classList is a read-only property which returns a live DOMTokenList collection of the class attributes of the element."* Methods: .add('string'), .remove('string'), etc
Add/edit an ID to a DOM element
var domTarget = /* select a DOM elem */
domTarget.id = '' /* enter an ID */
Generate a DOM element
Intro
var addListItem = document.createElement('li');
Set the contents of a DOM element
With .innerHTML
, we remove all of element's children, parse the content string and assign the resulting nodes as children of the element. This property provides a simple way to completely replace the contents of an element.
element.innerHTML = content;
Get the value entered in an input element
var getInput = document.getElementById('input-form');
var formData = "";
formData = (getInput.value);
If we need the value as a number, we can use: .valueAsNumber
.
Perform operations on all elements of an array
With .forEach
One of the methods available is .forEach()
, which is an higher-order function -- takes another function (callback) as an argument. The callback automatically receives the array elements' values and indexes as parameters.
var myArray = ["lorem", "ipsum", "dolor"];
myArray.forEach((arrayElem, arrayElemIndex) => {
console.log(`${arrayElemIndex} | ${arrayElem}`);
});
// 0 | lorem
// 1 | ipsum
// 2 | dolor
With .map()
map()
(Array.prototype.map) calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.
// the same example applies
var myArray = ["lorem", "ipsum", "dolor"];
myArray.map((arrayElem, arrayElemIndex) => {
console.log(`${arrayElemIndex} | ${arrayElem}`);
});
// 0 | lorem
// 1 | ipsum
// 2 | dolor
Set an element's value to its opposite
Use the bang !
operator:
var myVar = true;
myVarOpposite = !myVar;
console.log(myVarOpposite); // false
Useful methods
There are different ways to select a DOM element:
document.querySelector()
Use .querySelector(elem[attr])
;
Returns the first Element within the document that matches the specified selector, or group of selectors.
The element can then be assigned, like this:
// selecting a CSS class
var docClass = document.querySelector('.css-class');
// selecting an HTML elem
var docClass = document.querySelector('header');
// selecting an HTML elem w/ a particular attribute
var docClass = document.querySelector('img[width=150]');
document.querySelectorAll();
Returns all elements with a given class.
document.getElementById()
var myVar = document.getElementById('elem-with-id');
Remove an array element
Use .splice()
, passing array index and number of increments.
var myArray = ["lorem", "ipsum", "dolor"];
myArray.splice(0, 1);
console.log(myArray); // [ 'ipsum', 'dolor' ]