Javascript tutorial

December 28th, 2021 - Vincent Luciani
The tables below will help you to rehearse Javascript's most useful functionalities. Use the quick links below to jump directly to the type of information you are interested in.
Choose a chapter below:

Handling strings

Get the part of a string within a string. How it worksFirst character in string has start=0
myString.substring(start, afterend)

Example with str="hello"
str.substring(4, 5) returns "o"
Check if a string is part of array of stringsvar n=myarrayofstrings.includes(stringtosearch);
If condition: string is inside a stringif (myArray.indexOf(myStringToFind) > -1){
Split string in pieces with a separatorvar myArray=new Array();
Pad string with leading characters ( for example zeroes )myString.padStart(mytargetstringlength, mycharacter);
Split string in pieces with a separatorvar myValues=myString.split(mySeparator);
Convert a number to a stringmyNumber.toString();
Convert a string to an integerparseInt(myString)
Concatenate a string, using a mix of string variables and hard coded text and a carriage return at the endvar myString=`${variable1}: ${variable2}hardcoded text
Transform a string using a regular pattern. For example replace five first letters by "test"mystring.replace(/^[a-zA-Z]{5}/g,"test");
Find, within string mystring, a string between the text "myvariable=" (with lazy matching) and either & or the end of the string, and get only the found string mystring.replace(/.*myvariable=(.*?)($|&.*)/g, '$1');
Shortcut for [a-zA-Z0-9_] \w
Shortcut for [^a-zA-Z0-9_] \W
Several word separated by -, take the second wordmyString.replace(/(\w*)-(\w*)-(\w*)=.*/g, '$2')
Shortcut for [0-9]\d
Regular expression: which characters need escape. + * ? ( ){}/
Take off tabulation and carriage return from a stringmyString.replace(/(\t|\n)/g, '')

Handling Arrays

Get the length of an arraymyArray.length
Add an element to an arraymyArray.push(myValue)
Concatenate elements of an array to make a string, with a separator between each elementmyArray.join(mySeparator)
Get the last element and delete itvar lastElement=myArray.pop();
Get the first element and delete itvar firstElement=myArray.shift();
Make the sum of all items in an array using a reducer.const myReducer=(x, y)=> x+ y;
console.log(myArray.reduce(myReducer ));
Sorting an array of object using one of the objects property. For example sort by the value of a when var myArrayOfObjects=[{a:3,b:2},{a:1,b:3},{a:2,b:1}];myArrayOfObjects.sort(function(x, y){
return (x.a - y.a)
Take off a certain number of elements from an array at a certain position. How does it work.myArray.splice(x,y)
This takes off, starting from position x (we count starting from 0), y elements.

var myArray=["0","1","2","3","4","5"];;

["0", "3", "4", "5"]
At position x (starting from 0) in an array, take off 2 elements and instead put "a","b","c"myArray.splice(x,2,"a","b","c")

For example:
var myArray=["0","1","2","3","4","5"];
["0", "a", "b", "c", "3", "4", "5"]
If condition: string is part of the arrayif (myArray.indexOf(myStringToFind) > -1){
If condition : nth element of the array is not definedif ( isNaN(myArray[n]) ){
Build and access a two-dimensional array (example with two lines and three columns)var myArray=[];
In a two dimension array, get the number of lines and the number of columns var numberOfLines=resultArray.length;
var numberOfColumns=resultArray[0].length;
Sort an arraymyArray.sort();
Sort an array of objects using a custom comparison: sort object using string field id containing a numberfullData.sort(function(a, b){return (a.myDateField - b.myDateField);});

Example: sorting by the field id
var myArray=[{id:"2",test:"1"},{id:"1",test:"3"}];
myArray.sort(function(a, b)
{return (parseInt( - parseInt(;});
sort an array of objects using a custom comparison: sort object using date field myDateFieldfullData.sort(function(a, b){return a.myDateField - b.myDateField)});

var myDate=new Date();
var previousDate=new Date(myDate.getTime());
previousDate.setDate(myDate.getDate() - 1);

var myArray=[{id:"2",myDateField:myDate},{id:"1",myDateField:previousDate}];

myArray.sort(function(a, b){return (a.myDateField - b.myDateField);});
Convert a list of object to another list, using a function to modify each element in the listvar myFunction=function(input){
return ....
Convert a list of object to another list, multiplying an element of each object by twovar myFunction=function(inputObject){
var resultObject=inputObject;
resultObject .variableToChange=inputObject.variableToChange*2;
return resultObject ;

Take a list of objects and filter it, keeping only elements for which a variable in the object is equal to somethingresultList=inputList.filter(oneObject=>{
if (oneObject.myElement=="myvalue"){
return true;
return false;
loop through an array, executing a function on each itemarray.forEach(myFunction);
function myFunction(item, index)


The index is not useful to get access the item as "item" gives the current item in the loop. It can be used for other purpose like showing the item number.
var myArray=["a","b","c"];

function myFunction(item, index)


Asynchronous / synchronous

Call an asynchronous function from a synchronous function, react in case of success and failure.myAsyncFunction(myParams).then(value=>{

}, reason=>{


If myAsyncFunction throws an error, in the example above, console.log(reason) will be called. If certain cases in myAsyncFunction correspond to a critical failure (for example it calls an API that returns a 404 code), then throw an error using throw "myerror".
Otherwise you do not need to use try catch in myAsyncFunction, as the error will be caught in the part console.log(reason) and reason will contain the error (except if you want to get the stack trace also, or log more details in a log file).

You can have a synchronous function1 calling function11, function12, function13, .. and these functions calling other functions. A synchronous function like function1 is compulsory when answering to an API call. In that case :
- have an intermediary asynchronous function ( a wrapper ) calling function11, function 12, ... using await (it can also run some functions in parallell using await Promise.all. This function is called using the technique above (with .then).
- have all other functions be asynchronous (and calling each other using await). If one of these functions is calling a third party function, find an asynchronous version of this function ( for example fetch when calling an API)
have asynchronous functions until the very "end": so in that case function2 and function3 would be asynchronous calling await, and only function1 would be using then

Call an asynchronous function A from an asynchronous function B and return a result coming from function B.var myParentFunction=async function(parameters){
let myresult=await myChildFunction(parameters.myparam);
return myresult;
Call two asynchronous functions from an asynchronous function in parallel and return a concatenation of their result only once both actions are completedlet myresult1=await myModule.myFunction(input1);
let myresult2=await myModule.myFunction(input2);

let myFinalResult=await Promise.all([myresult1 , myresult2]);

return JSON.stringify(myresult1)+"|"+JSON.stringify(myresult2);
Asynchronous function to execute a get http requestconst response=await fetch(url)
let jsonResults=await response.json();

if (jsonResults && jsonResults.myParameterInsideTheResult){

isLoaded: true,
items: jsonResults

isLoaded: true,
totalHits: 0
Get something else than the json object with fetchresponse.text: to access raw text.
response.formData: to access FormData.
response.blob: to access a Blob Object.
response.arrayBuffer: to access an Array Buffer
Asynchronous function to post http request var myJSONBody={"param_a":"value a","param_b":10,"param_c":message};
response=await fetch("/test",{
method: "POST",
headers:{'Content-Type': 'application/json'},
body: JSON.stringify(myJSONBody)

Create a function returning a promisevar myFunction=async (myInput)=>{
return new Promise(
function (resolve, reject){
.... happy path .....
...... sad path .....

myFunctionWithPromise=async (myInput)=>{
return new Promise(
function (resolve, reject){
if (message){
}, 2000, myInput);

Use this technique only if you are creating some logic that causes waiting and you are not calling any other function to do that. If any other cases:
- find the asynchronous version of this function and use await to call it (see: call an asynchronous function from another asynchronous function).
- declare the function as async but build it without using a promise:
var myParentFunction=async function(parameters){
let myresult=await myChildFunction(parameters.myparam);
return myresult;
Have a synchronous function return a value, when this synchronous function needs the output from an asynchronous function to build this valueThat cannot be, because the synchronous function will exit as soon as he called the asynchronous function, not waiting for this asynchronous function to end. So you must transform this synchronous function in an asynchronous one using await : var myvalue=await childfunction(param);return myvalue. Then in the main program (synchronous), you will call it like this (value will give the returned value):

}, reason=>{


ECMA script

Declare a variable which value will not changeconst myvariable=myvalue;
Declare a variable which value will changelet myvariable
Arrow function syntaxconst myfunction=(var1,var2)=>{
return var1 + var2;

in case of one variable:
const myfunction=var1=>{
return var1

in case of no variable:
const myfunction=()=>{
return something;

in case of only one statement:
const myfunction=a=> a * 2;
Do not put a reserved word instead of a
When the statement is in one line like this, there is no need for a return statement. This function will return a * 2.
Test you js fileCreate the test file with extension .mjs. Call it using node myTestFile.mjs
Declare a function in another fileIn the file where the function is defined (the file will have the same name as the function):
const myfunction=function(inputparam){
export default myfunction;

In the file calling the function:
import myfunction from './pathtofilewithfunction';

As you export default, the shortcut name can be different from the function name
Declare several functions in another fileIn the file where the functions are defined
export const myfunction=...
export const myparameter=....

In the file calling the functions:
import{myfunction,myparameter}from './pathtofilewithfunctions';

Convert string to number, even if the string has leading zeroes
( for example convert "001" to 1 )
Loop through a list of objectsfor (const oneElement of myListOfElements){

.... oneElement.myParameter ....

Add a list to another listmyresultinglist=[...mysecondlist, ...myfirstlist]
Add a dictionary inside another dictionarymyresultingobj={
mynewparam: mynewvalue

const myObject={a:16,b:62};
const newObject={
If an object has several parameters, change only one parameter, leaving the other parameters untouchedmyresultobj={


Get list of all parameters in an object, and access each ones valuefor(var key in objects){

var value=objects[key];

Second way:

var keys=Object.keys(myObject);

for (var i=0;i < keys.length;i++){

access parameter from an object using its name + deep dive insidevar myvalue=myobject[myParameterName];

In casee of sub parameter :
var myObject={x: 1, y: 2, z:{a: 31, b:32, c: 33}};
var myResult=myObject['z']['a']
access an objects parameter using a calculated namevar myvalue=myobject[myParameterName];
Loop through elements in an objectfor (var key in myObject){

object with private membersfunction myObject(parameters){

var myparameter="parametervalue";

var myFunction=function()
object with public membersfunction myObject()

call object from another file<script type="text/javascript" src="pathofthefilecontainingtheobject.js"></script>

var result=new myObject(myParameters);
Create an empty object ( to which you will be able to assign parameters with values)var myObject={};

Date and time

Execute function after 5000ms and then every 5000ms, with parameters var intervalID=setInterval(myCallbackFunction, 500, 'Parameter 1', 'Parameter 2');

function myCallbackFunction(a, b)
// Your code here
// Parameters are purely optional.

Interrupt a function running every x msvar intervalID=setInterval(myCallBackFunction, 500);

Set interval and clear interval inside a class, being able to access class members inside the callback functionthis.myInterval=setTimeout(this.myCallBackFunction.bind(this), 4000);

Wait for x millliseconds before executing a functionvar myTimer=setTimeout(myCallbackFunction, 5000, 'Parameter 1', 'Parameter 2');

function myCallbackFunction(a, b)
// Your code here
// Parameters are purely optional.

Cancel the waiting of x milliseconds clearTimeout(myTimer);
Get the current time in seconds (to be able to calculate a time difference in seconds)var startTime=new Date().getTime() / 1000;
var newTime=new Date().getTime() / 1000;

Time passed is calculated just like this:
var timePassed=newTime - startTime;
Initialize a date with year, month, day, hour, minute, secondmyDate=new Date(myYear, myMonth, myDay);
Initialize a date with year, month, daymyDate=new Date(myYear, myMonth, myDay, myHour, myMinute, mySeconds);
Get the date in US formatmydate.toLocaleString('en-US');
Get the date in French formatmydate.toLocaleString('fr-FR');
Get the month in English from a datemydate.toLocaleString('en-US',{month: 'long'});
Get the month in French from a datemydate.toLocaleString('fr-FR',{month: 'long'});
Get the year from a datemydate.getFullYear();
Get the day number from a date in 2 digitsmydate.toLocaleString('en-US',{day: '2-digit'});
Get the day with the weekday in English, the year and day as a numeric and the month as a long month number in Englishconst options={
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',

Get current date ( today ) in the format YYYY-MM-DDvar currentDateTime=new Date();
var currentDate=currentDateTime.getFullYear().toString().padStart(2,'0')+'-'+(currentDateTime.getMonth()+1).toString().padStart(2,'0')+'-'+currentDateTime.getDate().toString().padStart(2,'0');
Get current date and time at midnightvar myDate=new Date();
Yesterdays date at midnightvar myDate=new Date();
var previousDate=new Date(myDate.getTime());
previousDate.setDate(myDate.getDate() - 1);
24 hours agovar newDate=myCurrentDate;
var previous=new Date(newDate.getTime());


get an api key google for authenticationGo to the Google Cloud Platform Console ( and click on the console button on the top right)
Click the project drop-down and select or create the project for which you want to add an API key.
Click the menu button (hamburger icon on top left) and select APIs & Services > Credentials.
On the Credentials page, click + Create credentials > API key.
The API key created dialog displays your newly created API key.
Click Close.
The new API key is listed on the Credentials page under API keys.
(Remember to restrict the API key before using it in production.)
In Authorized JavaScript origins, for production, you must use port 443 as it is https:
Authorized redirect URIs (example):
Assign a parameter in the if statement to be able to reuse it const textValue="test";
let textParameter;

if (textParameter=textValue==="test"){

In a loop, execute actions every n iterationsfor ....
if ( intervalCount%n==0){

Example with execution every 3 iterations:
for (var i=0;i<20;i++){
if (i%3==0){

Create a real random functionfunction getRandomNumber(min,max){

var randomSeed=Math.random();

if ( (Math.floor( 1000 * randomSeed ) % 2)==0)
randomNumber=Math.floor( (max - min) * randomSeed + min );
randomNumber=Math.ceil( (max - min) * randomSeed + min );
return randomNumber;

Round a numberMath.round(myNumber)
For loop ( to loop for example on an array of size n )for (var i=0;i < n;i++){
Assign a value, giving a default if the value is nullmyvalue=myinputvalue || mydefaultvalue;
Convert to base 64var encodedData=btoa(stringToEncode);
Return several variable from one functionvar myResult=myFunction();

var myFunction=function(){

var myFunction=function(){
var param1="test";
var param2="test2";

var myResult=myFunction();

Prevent the screen from sleeping In javascript:
function preventSleep()

function allowSleep()


<video id="video" width="1px" height="1px" controls>

Your browser does not support the video tag.

Get the mutted blank file here:
Train javascript online
select javascript and console, deselect the rest
Being able to go to function definition even if the function is outside the fileput jsconfig.json at root of folder when source code (even if empty)
Debug application running on chrome on the phone from your desktopOpen the Developer Options setting on your Android Device (about phone).
a. On the phone, go to settings, then "About Phone"
b. Tap "Build number" (completely at the end) SEVEN times. Once the developer option is activated, you will see a message, “You are now a developer!

Then settings, system (option at the end), advanced, developer options, check USB debugging.

On the phone, on chrome, click on number showing there are several tabs opened, (same line as url, share button, the number is within a white box with black rounded borders. Then click on the three dots and close all tabs.

Then navigate to the application you want to debug

Connect the phone to the computer with a charger (USB)
On desktop, on chrome, go to chrome://inspect/#devices
Accept confirmation message on the phone (several times)
if necessary, take off USB and put it back again.

After a while, under Remote target, you should see the name of your phone and a line corresponding to the app you are debugging.

On this line, click on inspect or inspect fallback.
You will see a new window exactly as if you were using chrome developer tool with the site running on your mobile
javascript pass by reference or valuePrimitive type variables (integer, string,...) passed by value.
Arrays and Objects :

Passed by value if you assign a value to the object inside the function:
myObject={myparam: "paramvalue"};

var myFunction=function(inputObject){
inputObject={myparam: "newvalue"}

var test=myFunction(myObject);

Passed by reference if you assign a value to a property of the object inside the function:
myObject={myparam: "paramvalue"};

var myFunction=function(inputObject){

var test=myFunction(myObject);

DOM manipulation

Execute javascript code only once the components described in the HTML page are loaded in the DOMInside a script tag:
put your code here
Change the style on an HTML element. For example style element "display" to "block"document.getElementById("myElementID").style.display='block';
Change the style on an HTML element to make the element disapeardocument.getElementById("myElementID").style.display='none';
Change the style on an HTML element to hide the elementdocument.getElementById("myElementID").style.visibility='hidden';
Change the style on an HTML element to show the elementdocument.getElementById("myElementID").style.visibility='visible';
Change the text in an HTML divdocument.getElementById("myElementID").innerHTML="my text"
Get the width of the browser window without the scrolling bar (if present)window.innerWidth
Focus on an element of the web pagedocument.getElementById("myElementID").focus();
Get all elements with a given class name and get the attribute of one of the elementsIn HTML:
<.... class="myClass" myAttribute="myvalue">

In the script:
var testElements=document.getElementsByClassName('myClass');

Get the value of an HTML element of type numbervar result=document.getElementById("myElementID").value;
Get the URL of the current page ( page from which the javascript script is executed )var currentURL=window.location.href;
Get parameters from the urlvar;
var urlParams=new URLSearchParams(queryString);
var resultValue=urlParams.get('myparam');
Get the nth element of local storagevar result=localStorage.getItem(localStorage.key(i));
Put the cookie values in a arrayvar theCookiesArray=document.cookie.split(';');
React on a user pressing a key on the keyboardaddEventListener("keydown", function(e){
React on a user pressing Enter.addEventListener("keydown", function(e){
if ( e.keyCode==13 )
... do this ....

Implement an event listener that executes a function taking a parameter in input, and this parameter value is coming from outside the event listener declarationmyDiv.addEventListener('change', function(internalInputParam){
return function(){.... code using internalInputParam ..... )}

When the event happens, internalInputParam will take the value of inputParam.
If you put inputParam in both places in the code ( instead of internalInputParam and inputParam ) then you will receive a warning that the variable was already declared.
Implement a listener taking a value from input when the person is entering the input (at every key stroke).var myDiv=document.getElementById('my-div-id')
inputDiv.addEventListener('input', function (evt){
... this.value .....;
Implement a listener reacting on scrollingmyDiv.addEventListener('scroll',myFunction)

In myFunction, use window.innerHeight to know what is the inner height of the window and document.body.scrollTop to know how much the user scrolled down
Construct a function based on another function plus parameters (can be then used in a callback)var myFunction=otherFunction(param1value);

Then you can call it, using other parameters:
var myResult=myFunction(param2value);
Function to load a script from javascript, and go to next step only once the document loadsvar loadScript=function(scriptUrl,callback){
let myScript=document.createElement("script");
myScript.setAttribute("src", scriptUrl);
Add a class to a divmyDiv.classList.add("myclassname");
Remove a class from a divmyDiv.classList.remove("myclassname");
Add a class if not there and remove it if theremyDiv.classList.toggle("myclassname");
Returns true and adds the class if class does not exist
Returns false and removes the class if class exists
Cope with the case where some browsers are not dealing with addEventListener('click',...) if (myDiv.addEventListener)
Go to the beginning of the screenwindow.scrollTo(0, 0);
Access to a div's first childmydiv.firstChild
Scroll to a component of id myiddocument.getElementById("myid").scrollIntoView()
Set the attribute of a div. For example
myDiv.setAttribute("attributename", attributeValue);
Get the attribute from a div.myScript.getAttribute("attributename");
Create a DOM element of type divlet myDiv=document.createElement("div");
Delete all children from a parent divvar myParentDiv=document.getElementById("my-parent-div-id");

while (myParentDiv.hasChildNodes())


Add a canva to the HTML page<canvas id="my-canva-id" height="100%" width="100%">
Sorry, your browser does not support canvas.
Javascript to draw a rectangle on a canvavar myCanvaContainer=document.getElementById("my-canva-id");

Clear a rectange drawn on a canvacontext.clearRect(xposition,yposition,rectangleheight,rectanglewidth);
Javascript to draw a circle on a canvavar myCanvaContainer=document.getElementById("my-canva-id");


context.arc(xposition, yposition, radius, 0, totalangle);

With totalangle=2 * Math.PI to have the entire circle
Javascript to draw a line on a canvavar myCanvaContainer=document.getElementById("my-canva-id");
var context=myCanvaContainer.getContext("2d");
context.moveTo(startpositionx, startpositiony);
context.lineTo(endpositionx, endpositiony);
Insert an image on a canvacontext.drawImage(imageDiv,xposition,yposition);
Delete all elements from the canva and initialize the context at the end of the animationcontext=null;
while (myCanvaContainer.hasChildNodes())

You will still need clear functions if you want to remove elements from the display:
context.clearRect(0, 0, myCanvaContainer.width, myCanvaContainer.height);
Get the width of a canvacanva.width
Clear all elements in the canvacontext.clearRect(0, 0, myCanvaContainer.width, myCanvaContainer.height);
How to animate a canvavar myTimer=setInterval(myDrawingFunction, myRefreshIntervalInMilliseconds);
(this will call the draw function regularly)
Be careful to put the timer after the declaration of the myDrawingFunction
In the myDrawingFunction:
context.clearRect(0, 0, canvas.width, canvas.height);
(this is to clear the canva)
Then draw your elements. You can use increments to modify the xposition and yposition of each element drawn to make the element move
If you want to use multiple elements for your animation, use objects with position and function to draw it.

To stop the animation, use clearInterval(myTimer)

var canvaContainer=document.getElementById("my-canva-id");
var x=0;
var y=0;
var context=canvaContainer.getContext("2d");

var myDrawingFunction=function(){
context.clearRect(0, 0, canvaContainer.width, canvaContainer.height);

var myTimer=setInterval(myDrawingFunction, 1000

Audio and video

Play a sound without looping, with a certain volume.const myAudio=document.createElement("audio");
myAudio.setAttribute("src", "resources/my-audio-file.mp3"),
myAudio.setAttribute("id", "cheering-audio"),

var myAudio=document.getElementById("my-audio-div-id");
Start a video automatically going in a loopvar obj={"video":{
"value": "<iframe title='YouTube video player' type=\"text/html\" width='100%' height='100%' src='' frameborder='0' allowFullScreen></iframe>"


- you need to create a playlist with your video inside. Put the list identifier after list=
- you need to mute the video so that it starts automatically using &mute=1
This website is non commercial and does not register any of your personal data (no cookie, no statistics). The site and its content are delivered on an "as-is" and "as-available basis".