Giacomo Balli profile picture
Giacomo Balli
The Mobile Guy

Over two decades of experience at your service.
I help business owners make better decisions.

Let's Chat LinkedIn

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.

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

See javascript add 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

See javascript concat

javascript merge arrays

See javascript concat

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

See javascript year month day

	
	

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);
	

See javascript go to url

	
	

javascript open new tab

	
	

	
	

javascript preventdefault

	
	

javascript prompt

	
	

javascript queryselector

	
	

javascript queryselectorall

	
	

javascript queryselectorall foreach

	
	

javascript redirect

	
	

javascript reload page

	
	

javascript remove class

	
	

javascript to refresh page

	
	

javascript who has focus

	
	

javascript window open

	
	

javascript window width

	
	

javascript window.location

	
	

javascript yes no confirm

	
	

javascript yes no dialog

	
	

javascript yesterday

	
	

javascript yesterday's date

	
	

javascript zindex

	
	

javascript zoom image

	
	

javascript zoom image on hover

	
	

javascript confirm

	
	

javascript console

	
	

File

can javascript access local files

	
	

can javascript read a file

	
	

can javascript write to a file

	
	

javascript write to file

	
	

Functions

are javascript callbacks asynchronous

	
	

can javascript return multiple values

	
	

javascript arrow function

	
	

javascript async await

	
	

javascript await

	
	

javascript can a function call itself

	
	

javascript default parameters

	
	

javascript try catch

	
	

javascript wait

	
	

javascript wait 1 second

	
	

javascript wait for function to finish

	
	

javascript wait for promise

	
	

General

javascript can create cookies

	
	

javascript can react to events

	
	

are javascript and ecmascript the same thing

	
	

are javascript and java the same

	
	

can javascript be used for hacking

	
	

can javascript be used for machine learning

	
	

can javascript be used to make apps

	
	

can javascript be used to make games

	
	

can javascript call python

	
	

can javascript change css

	
	

can javascript make apps

	
	

can javascript read cookies

	
	

can javascript replace php

	
	

javascript backtick

	
	

javascript banana

	
	

javascript can be coded in html

	
	

javascript can be used to validate

	
	

javascript can boolean be null

	
	

javascript can change html attribute value

	
	

javascript can change html content

	
	

javascript can hide html elements

	
	

javascript copy to clipboard

	
	

javascript hoisting

	
	

javascript int to string

	
	

javascript is date

	
	

javascript is defined

	
	

javascript is empty

	
	

javascript is function

	
	

javascript is integer

	
	

javascript is nan

	
	

javascript is not a function

	
	

javascript is not defined

	
	

javascript is not null

	
	

javascript is null

	
	

javascript is null or empty

	
	

javascript is number

	
	

javascript is numeric

	
	

javascript is object

	
	

javascript is string

	
	

javascript is undefined

	
	

javascript isnan

	
	

javascript let vs var

	
	

javascript localstorage

	
	

javascript log to console

	
	

javascript print to console

	
	

javascript promise

	
	

javascript setinterval

	
	

javascript settimeout

	
	

javascript sleep

	
	

javascript throw error

	
	

javascript to array

	
	

javascript to boolean

	
	

javascript to float

	
	

javascript to int

	
	

javascript to json

	
	

javascript to number

	
	

javascript to string

	
	

javascript undefined

	
	

javascript undefined check

	
	

javascript url decode

	
	

javascript url encode

	
	

javascript use strict

	
	

javascript validate email

	
	

javascript validator

	
	

javascript variable types

	
	

javascript vs jquery

	
	

javascript when document ready

	
	

javascript when to use semicolon

	
	

javascript when to use var

	
	

javascript who called function

	
	

javascript who fired event

	
	

javascript without brackets

	
	

javascript without parentheses

	
	

javascript without semicolons

	
	

javascript write to console

	
	

what javascript cannot do

	
	

what javascript framework should i use

	
	

what javascript library should i use

	
	

when javascript code is executed

	
	

when javascript is executed

	
	

when javascript return undefined

	
	

when javascript variable is undefined

	
	

where javascript should be placed

	
	

are javascript variables global

	
	

Keys

javascript keyboard events

	
	

javascript keyboard input

	
	

javascript keycode list

	
	

javascript keycode to char

	
	

javascript keycodes

	
	

javascript keydown

	
	

javascript keydown event

	
	

javascript keylogger

	
	

javascript keypress

	
	

javascript keypress event

	
	

javascript keyup

	
	

Loops

javascript for of index

	
	

javascript for of vs for in

	
	

javascript foreach

	
	

javascript for each in array

	
	

javascript for each loop

	
	

javascript for in

	
	

javascript for in array

	
	

javascript for loop

	
	

javascript for loop array

	
	

javascript for loop break

	
	

javascript loop through array

	
	

javascript loop through object

	
	

javascript while loop

	
	

Numbers

javascript without decimal

	
	

javascript zero pad

	
	

javascript convert string to number

	
	

javascript math.random

	
	

javascript math.round

	
	

javascript number to string

	
	

javascript parsefloat

	
	

javascript parseint

	
	

javascript random

	
	

javascript random number

	
	

javascript random number between

	
	

javascript round

	
	

javascript to the power of

	
	

javascript tofixed

	
	

Objects

javascript hasownproperty

	
	

javascript map

	
	

javascript map function

	
	

javascript merge objects

	
	

javascript parse json

	
	

javascript xml to json

	
	

javascript xml to string

	
	

are javascript objects iterable

	
	

are javascript objects ordered

	
	

can javascript object keys be numbers

	
	

javascript json to csv

	
	

javascript key value

	
	

javascript key value array

	
	

javascript key value map

	
	

javascript key value pair

	
	

Strings

javascript replace

	
	

javascript replace all

	
	

javascript to camelcase

	
	

javascript to lower

	
	

javascript to lowercase

	
	

javascript to title case

	
	

javascript to uppercase

	
	

javascript trim

	
	

javascript uppercase

	
	

javascript uppercase first letter

	
	

javascript variable in string

	
	

are javascript strings immutable

	
	

javascript if string contains

	
	

javascript join two strings

	
	

javascript lowercase

	
	

javascript quotes in string

	
	

javascript split

	
	

javascript string contains

	
	

javascript string interpolation

	
	

javascript string length

	
	

javascript string replace

	
	

javascript string to int

	
	

javascript substring