functionfunc(){variable=value;// implicitly declared as a global variablevarvariable=value;// local variable}vara=10;// a is 10letb=10;// b is 10{varx=2,a=2;// a is 2lety=2,b=2;// b is 2}// a is 2, b is 10// x can NOT be used here// y CAN be used here
Constants
Hard-coded values are UPPERCASE and snake_case, camelCase otherwise. const CONSTANT = value;
Data Types
Number, String, Boolean, etc are built-in global objects. They are not types. Do not use them for type checking.
letnumber=10;//integer numbersnumber=15.7;//floating point numbersnumber=Infinity;//mathematical infinitynumber=-Infinity;number=1234567890123456789012345678901234567890n;//BigInt, value > 2^53, "n" at the endnumber="text"/2;//NaN --> not a number.
letstring="text";letstring$='text';letstring_=`text ${expression}`;//string interpolation (needs backticks)string.length;// length of the stringletchar=string.charAt(index);// extraction of a single character by positionstring[index];// char extraction by property accessletindex=string.indexOf(substring);// start index of substring in string
Property access is unpredictable:
does not work in IE7 or earlier
makes strings look like arrays (confusing)
if no character is found, [ ] returns undefined, charAt() returns an empty string
Is read only: string[index] = "value" does not work and gives no errors
typeofx;//returns the type of the variable x as a stringtypeof(x);//returns the type of the variable x as a string
The result of typeof null is "object". That's wrong.
It is an officially recognized error in typeof, kept for compatibility. Of course, null is not an object.
It is a special value with a separate type of its own. So, again, this is an error in the language.
String(value);//converts value to stringNumber(value);//converts value to a numberNumber(undefined);//--> NaNNumber(null);//--> 0Number(true);//--> 1Number(false);//--> 0Number(String);//Whitespace from the start and end is removed. If the remaining string is empty, the result is 0. Otherwise, the number is "read" from the string. An error gives NaN.Boolean(value);//--> trueBoolean(0);//--> falseBoolean("");//--> falseBoolean(null);//--> falseBoolean(undefined);//--> falseBoolean(NaN);//--> false//numeric type checking the moronic waytypeofvar_=="number";// typeof returns a string with the name of the type
// basic forfor(begin;condition;step){}for(varvariableiniterable){}// for/in statement loops through the properties of an objectfor(letvariableiniterable){}// instantiate a new variable at each iteration// for/of statement loops through the values of an iterable objects// for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.for(varvariableofiterable){}for(letvariableofiterable){}// instantiate a new variable at each iteration// foreach (similar to for..of)iterable.forEach(()=>{/* statements */});
Break & Continue statements
break; exits the loop. continue; skip to next loop cycle.
letarray=[];// empty arrayletarray=["text",3.14,[1.41]];// array declaration and initializationarray.length;// number of items in the arrayarray[index];// access to item by indexarray[index]=item;// change or add item by indexarray.push(item);//add item to arrayarray.pop();// remove and return last itemarray.join("separator");// construct a string from the items of the array, separated by SEPARATORarray.find(item=>condition);// returns the value of the first element in the provided array that satisfies the provided testing functionarray.fill(value,start,end);// fills an array with the passed value// https://stackoverflow.com/a/37601776array.slice(start,end);// RETURN list of items between indexes start and end-1array.splice(start,deleteCount,[items_to_add]);// remove and RETURN items from array, can append a list of items. IN PLACE operation
letarray=[items];// execute an operation on each item, producing a new arrayarray.map(function);array.map(()=>operation);array.filter(()=>condition);// return an items only if the condition is true// execute a reducer function on each element of the array, resulting in single output valuearray.reduce((x,y)=>...);
// arraysletarray1=[1,2,3,4,5,6];letarray2=[7,8,9,10];letcopy=[...array1];// shallow copyletcopyAndAdd=[0,...array1,7];// insert all values in new arrayletmerge=[...array1,...array2];// merge the arrays contents in new array// objectsletobj={prop1:value1,prop2:value2};letclone={...obj,prop:value};// shallow copy, and update copy propletcloneAndAdd={prop0:value0,...obj,prop3:value3};// stringsletalphabet="abcdefghijklmnopqrstxyz"letletters=[...alphabet];// alphabet.split("")//function argumentsletfunc=(arg1=val1,arg2=val2)=>expression;letargs=[value1,value2];func(arg0,...args);
letdict={FirstName:"Chris","one":1,1:"some value"};// add new or update propertydict["Age"]=42;// direct property by name// because it's a dynamic languagedict.FirstName="Chris";
letvariable=value;// object literalletobj={property:value,variable,// same as variable: variable[property]:value// dynamic prop nameobject:{...},method:function(){// code herethis.propertyName;// reference to object property inside the object}method;()=>{obj.propertyName;// this is undefined here, use full object name}};// access to property (non existant properties will return Undefined)obj.property;// dot notationobj["property"];// array notation// property modification (will add property if missing)obj.property=value;// dot notationobj["property"]=value;// array notationobj.func();//method accessdeleteobj.propertyName;// delete propertyObject.keys(obj);// list of all property namesObject.entries(obj);// list contents as key-value pairs
Constructors and object instances
JavaScript uses special functions called constructor functions to define and initialize objects and their features.
Notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods.
// constructor function definitionfunctionClass(params){this.property=param;this.method=function(params){/* code here */}}letobj=newClass(params);// object instantiationletobj=newObject();// creates empty objectletobj=newObject({// JSON});
Prototypes
Prototypes are the mechanism by which JavaScript objects inherit features from one another.
JavaScript is often described as a prototype-based language; to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.
An object's prototype object may also have a prototype object, which it inherits methods and properties from, and so on.
This is often referred to as a prototype chain, and explains why different objects have properties and methods defined on other objects available to them.
If a method is implemented on an object (and not it's prototype) then only that object will heve that method and not all the ones that come from the same prototype.
// constructor functionfunctionObj(param1,...){this.param1=param1,...}// method on the objectObj.prototype.method=function(params){// code here (operate w/ this)}letobj=newObj(args);// object instantiationobj.method();// call method from prototype
classDerivedObjextendsObj{constructor(param1,param2,...){super(param1);// use superclass constructorthis.param2=param2;}newFunc(){}}letdobj=DerivedObj();dobj.newFunc();
letobj={property:value,...}let{var1,var2}=obj;// extract values from object into variableslet{property:var1,property2:var2}=obj;// extract props in variables w/ specified nameslet{property:var1,var2=default_value}=obj;// use default values if object has less then expected props
// param1, param2, ... are the arguments passed to the function (IE9+)lettimerId=setTimeout(func[,milliseconds,param1,param2,...]);// wait milliseconds before executing the code (params are read at execution time)// works in IE9lettimerId=setTimeout(function(){func(param1,param2);},milliseconds);// Anonymous functions with argumentslettimerId=setTimeout(function(arg1,...){// code here},milliseconds,param1,...);clearTimeout(timerId)// cancel execution// example of multiple consecutive schedulesletlist=[1,2,3,4,5,6,7,8,9,10,"A","B","C","D","E","F","G","H","I","J",-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]functionuseTimeout(pos=0){setTimeout(function(){console.log(list[pos]);pos+=1;// update value for next callif(pos<list.length){// recursion exit conditionuseTimeout(pos);// schedule next call with new value}},1_000,pos);}useTimeout();
// let instantiates a new variable for each iterationfor(leti=0;i<3;++i){setTimeout(function(){console.log(i);},i*100);}// output: 0, 1, 2for(vari=0;i<3;++i){setTimeout(function(){console.log(i);},i*100);}// output: 3, 3, 3
letobj={prop:value,method1:function(){/* statement */}method2:function(){letself=this// memorize context inside method (otherwise callback will not know it)setTimeout(function(){/* code here (uses self) */})}}// betterletobj={prop:value,method1:function(){/* statement */}method2:function(){setTimeout(()=>{/* code here (uses this) */})// arrow func does not create new scope, this context preserved}}
Intervals
Function runs regularly with a specified interval. JavaScript is Single Threaded.
// param1, param2, ... are the arguments passed to the function (IE9+)lettimerId=setInterval(func,milliseconds[,param1,param2,...]);// (params are read at execution time)// works in IE9lettimerId=setInterval(function(){func(param1,param2);},milliseconds);// Anonymous functions with argumentslettimerId=setInterval(function(arg1,...){// code here},milliseconds,param1,...);clearTimeout(timerId);// cancel execution
DateTime
A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.
There are generally 4 types of JavaScript date input formats:
// constructorsnewDate();newDate(milliseconds);newDate(dateString);newDate(year,month,day,hours,minutes,seconds,milliseconds);// accepts parameters similar to the Date constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.Date.UTC(year,month,day,hours,minutes,seconds,milliseconds);//static methodsDate.now();// returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.// methodsletdate=newDate();date.toSting();// returns a string representing the specified Date objectdate.toUTCString();date.toDateString();date.toTimeString();// method returns the time portion of a Date object in human readable form in American English.// get datedare.getMonth();date.getMinutes();date.getFullYear();// set datedate.setFullYear(2020,0,14);date.setDate(date.getDate()+50);// parse valid datesletmsec=Date.parse("March 21, 2012");letdate=newDate(msec);
Note: Firefox 68 and later define the origin of a page opened using a file:/// URI as unique. Therefore, other resources in the same directory or its subdirectories no longer satisfy the CORS same-origin rule. This new behavior is enabled by default using the privacy.file_unique_origin preference.
// exporting individual fracturesexportdefaultfunction(){}// one per moduleexportfunc=()=>expression;// zero or more per module// Export listexport{name1,name2,…,nameN};// Renaming exportsexport{variable1asname1,variable2asname2,…,nameN};// Exporting destructured assignments with renamingexportconst{name1,name2:bar}=o;// re-exportexport{func}from"other_script.js"
importdefault_func_alias,{funcasalias}from"./module.js";// import default and set aliasimport{defaultasdefault_func_alias,funcasalias}from"./module.js";// import default and set alias// use imported functionsdefault_func_alias();alias();