Javascript FAQ
This is a collection of quick answers to the most searched questions regarding javascript.
I will leave out purely subjective topics and further details.
Table of Contents
AJAX
javascript XMLHttpRequest aka XHR
XHR, short for XMLHttpRequest, is the modern foundation to implement an interaction between a web page (your frontend) and a server (your backend).
javascript XMLHttpRequest GET
To perform a basic request you need just a few lines of code.
var url="http://giacomoballi.com/xhrTest"; //the URL you wish to retrieve var req = new XMLHttpRequest(); req.open("GET",url,true); //true tells XHR to perform in an asynchronous fashion req.onload = function(evt){ //handle the response, make sure to account for potential errors resp=JSON.parse(evt.target.responseText); console.log(resp); } req.send(null);
javascript XMLHttpRequest POST
When you need to pass specific values to your backend, and query parameters will not suffice, you can also perform a POST request.
This behaves like submitting a form.
var params="fname=John&lname=Doe"; var url="http://giacomoballi.com/xhrTest"; var req = new XMLHttpRequest(); req.open("POST",url,true); req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.onload = function(evt){ //handle the response, make sure to account for potential errors resp=JSON.parse(evt.target.responseText); console.log(resp); } req.send(params);
javascript XMLHttpRequest headers
XMLHttpRequest headers are essential when you need additional functionality.
As we already noticed above, we need to set the Content-Type header in order to successfully submit a POST request.
Sometimes, you may need additional information from your server. In this case you can query the response headers.
var url="https://amazon.com"; var req = new XMLHttpRequest(); req.open("GET",url,true); req.onload = function(evt){ //handle the response, make sure to account for potential errors var headers=req.getAllResponseHeaders(); //headers is a multiline string headers=headers.trim().split(/[\r\n]+/); //create an array with all headers var headersObject={}; for (h in headers){ //convert all headers to JSON object var thisHeader=headers[h].split(': '); headersObject[thisHeader[0]]=thisHeader[1]; } console.log("Amazon headers",headersObject); } req.send(null);
javascript fetch api
Fetch is an updated way of using XHR. It performs the same actions but it makes it easier to handle because it natively supports Promises.
The basic XHR GET example we used above can easily be re-written using fetch. Personally I find it more limiting but it is certainly subjective.
fetch('http://giacomoballi.com/xhrTest') .then(function(response) { response.json().then(function(data) { console.log(data); }); }) .catch(function(err) { console.log('Fetch Error', err); });
Arrays
javascript pop
Javascript pop allows you to quickly remove the last element of an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var lastElement = fruits.pop(); //"Mango"
javascript last element in array
A quick and dirty way of getting the last element of an array is pop as we mentioned above. However, this is dirty because you're also modifying the original array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var lastElement = fruits.pop(); //"Mango"
The better way of doing this is to simply access the last element by its index:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var lastElement = fruits[fruits.length - 1]; //"Mango"
Finally, almost just to prove a point, you can also use slice:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var lastElement = fruits.slice(-1)[0]; //"Mango"
javascript slice
Javascript slice allows you to extract one or more consecutive elements from an array (just like splice).
splice() changes the original array whereas slice() doesn't but both of them return an array object.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var subset = fruits.slice(1,3);
javascript splice
Javascript splice allows you to extract one or more consecutive elements from an array (just like slice).
splice() changes the original array whereas slice() doesn't but both of them return an array object.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var subset = fruits.splice(1,3);
javascript remove element from array
As it often happens in programming, there are different ways of doing this. The context usually defines which ones is best for each different case.
You can use:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length=2; //remove elements after the first two fruits.pop(); //removes the last element fruits.shift(); //removes the first element fruits.slice(1,3); //removes from index 1 to 3, does not modify original array fruits.splice(1,3); //removes from index 1 to 3, modifies original array var filtered = fruits.filter(function(value, index, arr){ //remove elements based on custom filter return value != "Apple"; });
javascript push
Javascript push to array might be the most common javascript array command. It allows you to quickly add an element to the end of an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi");
javascript sort
For basic sorting purposes, you can simply call sort() on your array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); //["Apple", "Banana", "Mango", "Orange"];
javascript reverse array
You can easily reverse the order of elements in an array (this does not necessarily mean descending if it wasn't previously sorted).
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse(); //["Mango", "Apple", "Orange", "Banana"]; fruits.sort(); //["Apple", "Banana", "Mango", "Orange"]; fruits.reverse(); //["Orange", "Mango", "Banana", "Apple"];
javascript unique array
Until ES6, there was no builtin method to filter out duplicate elements from an array.
function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var a = ["Banana", "Orange", "Banana", "Mango", "Banana", "Apple", "Mango"]; var unique = a.filter( onlyUnique ); // ["Banana", "Orange", "Mango", "Apple"]
javascript unshift
You can add new elements to the beginning of an array by concatenating or using unshift.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple");
javascript value in array
To check if a specific value is contained in a list of elements you call indexOf.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var a = fruits.indexOf("Apple"); //2
are javascript arrays dynamic
Yes, javascript arrays are dynamic. You can freely change both the size and type of data.
are javascript arrays immutable
No, javascript array are not immutable.
are javascript arrays ordered
Not by default. You can easily manipulate arrays but they are not automatically ordered (as opposed to JSON).
javascript add to array
As it often happens in programming, there are different ways of doing this. The context usually defines which ones is best for each different case.
You can use:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); //add at the end fruits[]="Kiwi"; //add at the end fruits.unshift("Lemon","Pineapple"); //add at the beginning fruits.splice( 0, 0, "Lemon"); //add at the beginning fruits.concat(["Lemon","Pineapple"]); //add at the end
javascript append to array
javascript array contains
See javascript add to array
In ES7 you can also use includes().
javascript array filter
You can easily define your own filtering rules in Javascript.
function onlyUnique(value, index, self) { return value.substring(0,1)=="B"; } var a = ["Banana", "Orange", "Mango", "Apple"]; var unique = a.filter( onlyUnique ); // ["Banana"]
javascript array find
The easiest way to find a value in an array is indexOf. However, if you need more flexibility, you can look into find.
Remember just like indexOf, find will return only the first match.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var found = fruits.find(function(element) { return element.substring(0,1)=="B"; });
javascript array map
map generates a new array after applying a function to every element of the array.
function celsius_to_fahrenheit(temp) { var fh = (temp * 1.8) + 32; return fh; } var celsiusTemps = [10, 16, 20, 24, 32]; var fhTemps = celsiusTemps.map(celsius_to_fahrenheit);
javascript array to string
toString returns a string with all the array values separated by commas.
If you need more flexibility look into join.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.toString();
javascript concat
concat is used to join two or more arrays.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var veggies = ["Tomato", "Spinach", "Kale"]; var dinner = fruits.concat(veggies);
javascript empty array
You can empty or flush an array in different ways:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits=[]; //set to a nee empty list fruits.length=0; //delete existing elements fruits.splice(0,fruits.length);
javascript endswith
endsWith() (added in ES6) determines whether a string ends with the specified string.
var str="I love hamburgers for dinner."; str.endsWith("dinner"); //false, notice the "." 😉
javascript explode
The Javascript equivalent of PHP's explode() is split().
var str="I love hamburgers for dinner."; str.split(" "); //["I","love","hamburgers","for","dinner."]
javascript flatten array
You can flatten an array (turn it into a string) by calling toString. If you need more flexibility look into join().
var dinner = ["I","love","hamburgers","for","dinner."]; dinner.join(" "); //"I love hamburgers for dinner."
javascript get last element of array
In Javascript there isn't a universal index referencing the last element of an array as you would find in PHP or Python.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var lastElement= fruits[fruits.length-1];
javascript is array
You can check if a variable is an array by calling isArray.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; Array.isArray(fruits); //true
javascript join two arrays
javascript merge arrays
Conditionals
javascript or statement in if
An or operator in javascript is represented by ||
if (fruit == "Banana" || fruit == "Strawberry"){ makeSmoothie(); }
javascript question mark colon
A question mark in javascript indicates a ternary conditional. The colon is used to separate what is return depending whether the condition is met.
function getDiscount(isMember) { return (isMember ? "20%" : "5%"); }
javascript switch
When you need to check a variable against multiple values, instead of implementing a long if statement you can use switch.
switch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; }
javascript ternary
See javascript question mark colon
Date
javascript date to string
new Date().toDateString(); // new Date().toString(); //
javascript get current date
The Date() constructor returns an object with the current date using the browser's timezone.
new Date().toDateString(); //
javascript get current time
The Date() constructor returns an object with the current date using the browser's timezone.
var now = new Date(); var time = now.getHours() + ":" + now.getMinutes(); //
javascript timestamp
The Javascript timestamp is an integer that represents the number of milliseconds elapsed since January 1 1970.
var timestamp = Date.now(); var timestamp = new Date().getTime(); var timestamp = new Date().valueOf();
javascript unix timestamp
The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1 1970.
var timestamp = Date.now(); var timestamp = new Date().getTime(); //same as above var timestamp = new Date().valueOf(); //same as above timestamp = Math.floor(timestamp / 1000);
javascript year month day
var now = new Date(); var str = now.getFullYear() + "-" + (now.getMonth()+1) + "-" + now.getDate(); //months start at 0
javascript years between two dates
var birthday = new Date("2015-03-25"); var now = new Date(); var age = now.getFullYear() - birthday.getFullYear();
javascript yyyy-mm-dd
javascript yyyy-mm-dd to date
var birthday = new Date("2015-03-25");
javascript yyyymmddhhmmss
var now = new Date(); var str = now.getFullYear() + "-" + (now.getMonth()+1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
DOM
javascript get attribute
var img = document.querySelector("img"); var src = img.getAttribute("src");
javascript get current url
var url=location.href;
javascript get element by class
var buttons = document.body.getElementsByClassName("button");
javascript get element by id
var container = document.body.getElementById("container");
javascript get input value
var value=document.querySelector("input[name=email]").value;
javascript get url parameter
function getUrlParams() { var vars = {}; if (location.href.match(/\?/)){ var params = location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); } return vars; }
javascript go to url
var newUrl = "http://giacomoballi.com"; location.href = newUrl;
javascript has class
hasClass was introduced by jQuery, not natively supported in Javascript but you can easily replicate it.
var element = document.querySelector("input[name=email]"); function hasClass(el,class){ return el.className.indexOf(class)!=-1?true:false; }
javascript hide element by id
document.getElementById("container").style.display="none";
javascript innerhtml
document.getElementById("container").innerHTML="Hello!";
javascript is checkbox checked
var element = document.querySelector("input[type=checkbox]"); console.log("Checkbox checked: " + element.checked);