Home › JavaScript Tutorial › All commands
All commands
Every command of this course: name, detailed description, syntax and example code.
Every command used in this course, with its name, a detailed description, the syntax and an example.
const let console.log addEventListener setTimeout setInterval push map filter JSON.stringify JSON.parse querySelectorconst
Definition: Declares a variable that cannot be reassigned.
Syntax:
const name = value;
Example:
const pi = 3.14;
console.log(pi);let
Definition: Declares a variable that can change. It lives inside its block.
Syntax:
let name = value;
Example:
let n = 1;
n = n + 1;
console.log(n);console.log
Definition: Prints a value for debugging.
Syntax:
console.log(value);
Example:
console.log("Sum:", 2 + 3);addEventListener
Definition: Runs a function when an event happens on an element.
Syntax:
element.addEventListener("event", function);Example:
document.body.addEventListener("click", function(){
console.log("clicked");
});setTimeout
Definition: Runs a function once after a delay in milliseconds.
Syntax:
setTimeout(function, ms);
Example:
setTimeout(function(){ console.log("later"); }, 1000);setInterval
Definition: Runs a function again and again every given milliseconds.
Syntax:
setInterval(function, ms);
Example:
var i = 0;
var t = setInterval(function(){
console.log(++i);
if (i === 3) clearInterval(t);
}, 500);push
Definition: Adds an item to the end of an array.
Syntax:
array.push(item);
Example:
const a = [1, 2];
a.push(3);
console.log(a);map
Definition: Builds a new array by transforming each item.
Syntax:
array.map(function);
Example:
console.log([1, 2, 3].map(function(x){ return x * 2; }));filter
Definition: Builds a new array with only the items that pass a test.
Syntax:
array.filter(function);
Example:
console.log([1, 2, 3, 4].filter(function(x){ return x % 2 === 0; }));JSON.stringify
Definition: Converts an object into JSON text.
Syntax:
JSON.stringify(value);
Example:
console.log(JSON.stringify({a: 1, b: [2, 3]}));JSON.parse
Definition: Converts JSON text back into an object.
Syntax:
JSON.parse(text);
Example:
console.log(JSON.parse('{"a":1}').a);querySelector
Definition: Finds the first element that matches a CSS selector.
Syntax:
document.querySelector("selector");Example:
document.querySelector("#o").textContent = "Found me";if
Definition: if , else if and else run code depending on a condition.
Syntax:
if
Example:
if (hour < 12) msg = "Good morning"; else if (hour < 18) msg = "Good afternoon";
else
Definition: if , else if and else run code depending on a condition.
Syntax:
else
Example:
else if (hour < 18) msg = "Good afternoon"; else msg = "Good evening";
clearInterval
Definition: setInterval repeats, and clearInterval stops it.
Syntax:
clearInterval
Example:
if (n === 10) clearInterval(id);
↗ Timers
submit
Definition: Listen for the submit event, call preventDefault() to stop the page reloading, then check the values and show a clear message.
Syntax:
submit
Example:
f.addEventListener("submit", e => {preventDefault()
Definition: Listen for the submit event, call preventDefault() to stop the page reloading, then check the values and show a clear message.
Syntax:
preventDefault()
Example:
e.preventDefault();
class
Definition: A class creates objects with shared methods.
Syntax:
class
Example:
class Counter {try
Definition: try / catch keeps one error from stopping the whole script.
Syntax:
try
Example:
try { JSON.parse("{bad json"); }catch
Definition: try / catch keeps one error from stopping the whole script.
Syntax:
catch
Example:
catch (err) { out += "\ncaught: " + err.name; }script
Definition: Put code in a script element or load a file with src .
Syntax:
script
Example:
<!-- <script src='app.js' defer></script> -->
src
Definition: Put code in a script element or load a file with src .
Syntax:
src
Example:
<!-- <script src='app.js' defer></script> -->
defer
Definition: Add defer to run after the page is parsed.
Syntax:
defer
Example:
<!-- <script src='app.js' defer></script> -->
onclick
Definition: Event attributes like onclick also hold code.
Syntax:
onclick
Example:
<button onclick='o.textContent='Clicked''>Attribute</button>
textContent
Definition: textContent or innerHTML write into the page, console.log writes to the developer console, and alert opens a dialog.
Syntax:
textContent
Example:
a.textContent='Plain text';
innerHTML
Definition: textContent or innerHTML write into the page, console.log writes to the developer console, and alert opens a dialog.
Syntax:
innerHTML
Example:
b.innerHTML='<b>Bold</b> via innerHTML';
for
Definition: for counts, while repeats while true, for...of walks values.
Syntax:
for
Example:
for(let i=1;i<=3;i++)t+='for '+i+'\n'; for(const c of 'JS')t+=c+' ';
↗ JS loops
while
Definition: for counts, while repeats while true, for...of walks values.
Syntax:
while
Example:
let n=3;while(n>0){t+='while '+n+'\n';n--;}↗ JS loops
length
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
length
Example:
o.textContent=[s.length,s.toUpperCase(),s.slice(0,5),s.includes('World'),s.replace('World','JS'),s.split(' ')].join('\n');slice
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
slice
Example:
o.textContent=[s.length,s.toUpperCase(),s.slice(0,5),s.includes('World'),s.replace('World','JS'),s.split(' ')].join('\n');toUpperCase
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
toUpperCase
Example:
o.textContent=[s.length,s.toUpperCase(),s.slice(0,5),s.includes('World'),s.replace('World','JS'),s.split(' ')].join('\n');includes
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
includes
Example:
o.textContent=[s.length,s.toUpperCase(),s.slice(0,5),s.includes('World'),s.replace('World','JS'),s.split(' ')].join('\n');replace
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
replace
Example:
o.textContent=[s.length,s.toUpperCase(),s.slice(0,5),s.includes('World'),s.replace('World','JS'),s.split(' ')].join('\n');split
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
split
Example:
o.textContent=[s.length,s.toUpperCase(),s.slice(0,5),s.includes('World'),s.replace('World','JS'),s.split(' ')].join('\n');trim
Definition: Common methods: length , slice , toUpperCase , includes , replace , split , trim , padStart .
Syntax:
trim
Example:
const s=' Hello World '.trim();
toFixed
Definition: Use toFixed , parseInt , parseFloat , Number() and check isNaN .
Syntax:
toFixed
Example:
o.textContent=[0.1+0.2,(0.1+0.2).toFixed(2),parseInt('42px'),Number('abc'),isNaN('abc'),(1234.5).toLocaleString()].join('\n');parseInt
Definition: Use toFixed , parseInt , parseFloat , Number() and check isNaN .
Syntax:
parseInt
Example:
o.textContent=[0.1+0.2,(0.1+0.2).toFixed(2),parseInt('42px'),Number('abc'),isNaN('abc'),(1234.5).toLocaleString()].join('\n');Number()
Definition: Use toFixed , parseInt , parseFloat , Number() and check isNaN .
Syntax:
Number()
Example:
o.textContent=[0.1+0.2,(0.1+0.2).toFixed(2),parseInt('42px'),Number('abc'),isNaN('abc'),(1234.5).toLocaleString()].join('\n');isNaN
Definition: Use toFixed , parseInt , parseFloat , Number() and check isNaN .
Syntax:
isNaN
Example:
o.textContent=[0.1+0.2,(0.1+0.2).toFixed(2),parseInt('42px'),Number('abc'),isNaN('abc'),(1234.5).toLocaleString()].join('\n');var
Definition: var lives in the whole function.
Syntax:
var
Example:
function f(){var a='function';if(true){let b='block';var c='var leaks';}return a+' '+c+' '+typeof b;}↗ JS scope
getFullYear
Definition: Read parts with getFullYear , getMonth (0-11) and getDay .
Syntax:
getFullYear
Example:
o.textContent=[d.getFullYear(),d.getMonth()+1,d.toLocaleDateString('en-IN',{dateStyle:'full'}),d.toISOString()].join('\n');↗ JS dates
getMonth
Definition: Read parts with getFullYear , getMonth (0-11) and getDay .
Syntax:
getMonth
Example:
o.textContent=[d.getFullYear(),d.getMonth()+1,d.toLocaleDateString('en-IN',{dateStyle:'full'}),d.toISOString()].join('\n');↗ JS dates
toLocaleDateString
Definition: Format with toLocaleDateString .
Syntax:
toLocaleDateString
Example:
o.textContent=[d.getFullYear(),d.getMonth()+1,d.toLocaleDateString('en-IN',{dateStyle:'full'}),d.toISOString()].join('\n');↗ JS dates
sort
Definition: push , pop , slice , sort , find , filter , map and reduce cover most work.
Syntax:
sort
Example:
o.textContent=[a.sort((x,y)=>x-y),a.map(x=>x*2),a.filter(x=>x>3),a.reduce((s,x)=>s+x,0),a.indexOf(4)].join('\n');reduce
Definition: push , pop , slice , sort , find , filter , map and reduce cover most work.
Syntax:
reduce
Example:
o.textContent=[a.sort((x,y)=>x-y),a.map(x=>x*2),a.filter(x=>x>3),a.reduce((s,x)=>s+x,0),a.indexOf(4)].join('\n');Set
Definition: A Set ignores duplicates.
Syntax:
Set
Example:
const s=new Set([1,2,2,3,3,3]);s.add(4);
↗ JS sets
add
Definition: Use add , has , delete and size .
Syntax:
add
Example:
const s=new Set([1,2,2,3,3,3]);s.add(4);
↗ JS sets
has
Definition: Use add , has , delete and size .
Syntax:
has
Example:
o.textContent='Unique: '+[...s]+' size '+s.size+' has 2? '+s.has(2);
↗ JS sets
size
Definition: Use add , has , delete and size .
Syntax:
size
Example:
o.textContent='Unique: '+[...s]+' size '+s.size+' has 2? '+s.has(2);
↗ JS sets
forEach
Definition: forEach for arrays, for...in for object keys, Object.entries for pairs, and entries() for index + value.
Syntax:
forEach
Example:
[10,20].forEach((v,i)=>t+=i+':'+v+' ');
entries()
Definition: forEach for arrays, for...in for object keys, Object.entries for pairs, and entries() for index + value.
Syntax:
entries()
Example:
for(const [i,v] of ['x','y'].entries())t+='\n'+i+v;
Math.round
Definition: Math.round , floor , ceil , max , min , sqrt , pow , PI and random .
Syntax:
Math.round
Example:
o.textContent=[Math.round(4.6),Math.floor(4.9),Math.max(3,8,1),Math.sqrt(81),Math.PI.toFixed(3),1+Math.floor(Math.random()*6)+' (dice)'].join('\n');↗ JS math
floor
Definition: Math.round , floor , ceil , max , min , sqrt , pow , PI and random .
Syntax:
floor
Example:
o.textContent=[Math.round(4.6),Math.floor(4.9),Math.max(3,8,1),Math.sqrt(81),Math.PI.toFixed(3),1+Math.floor(Math.random()*6)+' (dice)'].join('\n');↗ JS math
max
Definition: Math.round , floor , ceil , max , min , sqrt , pow , PI and random .
Syntax:
max
Example:
o.textContent=[Math.round(4.6),Math.floor(4.9),Math.max(3,8,1),Math.sqrt(81),Math.PI.toFixed(3),1+Math.floor(Math.random()*6)+' (dice)'].join('\n');↗ JS math
sqrt
Definition: Math.round , floor , ceil , max , min , sqrt , pow , PI and random .
Syntax:
sqrt
Example:
o.textContent=[Math.round(4.6),Math.floor(4.9),Math.max(3,8,1),Math.sqrt(81),Math.PI.toFixed(3),1+Math.floor(Math.random()*6)+' (dice)'].join('\n');↗ JS math
PI
Definition: Math.round , floor , ceil , max , min , sqrt , pow , PI and random .
Syntax:
PI
Example:
o.textContent=[Math.round(4.6),Math.floor(4.9),Math.max(3,8,1),Math.sqrt(81),Math.PI.toFixed(3),1+Math.floor(Math.random()*6)+' (dice)'].join('\n');↗ JS math
random
Definition: Math.round , floor , ceil , max , min , sqrt , pow , PI and random .
Syntax:
random
Example:
o.textContent=[Math.round(4.6),Math.floor(4.9),Math.max(3,8,1),Math.sqrt(81),Math.PI.toFixed(3),1+Math.floor(Math.random()*6)+' (dice)'].join('\n');↗ JS math
test
Definition: A pattern like /[a-z]+@[a-z]+/i works with test , match and replace .
Syntax:
test
Example:
o.textContent=[/[0-9]{5}/.test(t),t.match(/[0-9]{5}/g),t.replace(/[0-9]/g,'#'),/hello/i.test('HELLO')].join('\n');match
Definition: A pattern like /[a-z]+@[a-z]+/i works with test , match and replace .
Syntax:
match
Example:
o.textContent=[/[0-9]{5}/.test(t),t.match(/[0-9]{5}/g),t.replace(/[0-9]/g,'#'),/hello/i.test('HELLO')].join('\n');g
Definition: Flags: g global, i ignore case.
Syntax:
g
Example:
o.textContent=[/[0-9]{5}/.test(t),t.match(/[0-9]{5}/g),t.replace(/[0-9]/g,'#'),/hello/i.test('HELLO')].join('\n');i
Definition: A pattern like /[a-z]+@[a-z]+/i works with test , match and replace .
Syntax:
i
Example:
o.textContent=[/[0-9]{5}/.test(t),t.match(/[0-9]{5}/g),t.replace(/[0-9]/g,'#'),/hello/i.test('HELLO')].join('\n');typeof
Definition: Check with typeof .
Syntax:
typeof
Example:
o.textContent=v.map(x=>typeof x).join(', ')+'\nArray? '+Array.isArray([]);finally
Definition: try runs risky code, catch handles the error, finally always runs and throw raises your own error.
Syntax:
finally
Example:
try{throw new Error('Custom');}catch(e){t+=e.message+'\n';}finally{t+='finally ran';}throw
Definition: try runs risky code, catch handles the error, finally always runs and throw raises your own error.
Syntax:
throw
Example:
try{throw new Error('Custom');}catch(e){t+=e.message+'\n';}finally{t+='finally ran';}console.table
Definition: Use console.log , console.table , console.error , breakpoints and the debugger statement.
Syntax:
console.table
Example:
console.table([{a:1,b:2},{a:3,b:4}]);console.error
Definition: Use console.log , console.table , console.error , breakpoints and the debugger statement.
Syntax:
console.error
Example:
console.error('Something went wrong');debugger
Definition: Use console.log , console.table , console.error , breakpoints and the debugger statement.
Syntax:
debugger
Example:
// debugger; // pauses when DevTools is open
at()
Definition: , at() and Object.groupBy .
Syntax:
at()
Example:
o.textContent=[u?.a?.b,u?.x?.y,[1,2,3].at(-1),typeof structuredClone].join('\n');parentElement
Definition: Use parentElement , children , firstElementChild , nextElementSibling , closest() and querySelectorAll .
Syntax:
parentElement
Example:
o.textContent='Next: '+t.nextElementSibling.textContent+', parent: '+t.parentElement.id+', items: '+l.children.length;
children
Definition: Use parentElement , children , firstElementChild , nextElementSibling , closest() and querySelectorAll .
Syntax:
children
Example:
o.textContent='Next: '+t.nextElementSibling.textContent+', parent: '+t.parentElement.id+', items: '+l.children.length;
nextElementSibling
Definition: Use parentElement , children , firstElementChild , nextElementSibling , closest() and querySelectorAll .
Syntax:
nextElementSibling
Example:
o.textContent='Next: '+t.nextElementSibling.textContent+', parent: '+t.parentElement.id+', items: '+l.children.length;
innerWidth
Definition: window gives size ( innerWidth ), location , history , navigator , screen and timers.
Syntax:
innerWidth
Example:
o.textContent=[innerWidth+' x '+innerHeight,navigator.language,screen.width+' wide screen',matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'].join('\n');navigator
Definition: window gives size ( innerWidth ), location , history , navigator , screen and timers.
Syntax:
navigator
Example:
o.textContent=[innerWidth+' x '+innerHeight,navigator.language,screen.width+' wide screen',matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'].join('\n');screen
Definition: window gives size ( innerWidth ), location , history , navigator , screen and timers.
Syntax:
screen
Example:
o.textContent=[innerWidth+' x '+innerHeight,navigator.language,screen.width+' wide screen',matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'].join('\n');fetch(url)
Definition: fetch(url) returns a promise.
Syntax:
fetch(url)
Example:
fetch('https://jsonplaceholder.typicode.com/todos/1')json()
Definition: Check response.ok , then call json() .
Syntax:
json()
Example:
.then(r=>{if(!r.ok)throw new Error(r.status);return r.json();})IntersectionObserver
Definition: Beyond the DOM, browsers offer IntersectionObserver , Clipboard, Geolocation, Notifications, Web Storage, URL and FormData .
Syntax:
IntersectionObserver
Example:
o.textContent=[u.hostname,u.searchParams.get('y'),'IntersectionObserver' in window,'clipboard' in navigator].join('\n');URL
Definition: Beyond the DOM, browsers offer IntersectionObserver , Clipboard, Geolocation, Notifications, Web Storage, URL and FormData .
Syntax:
URL
Example:
const u=new URL('https://site.com/a?x=1&y=2');Temporal
Definition: Temporal replaces many problems of Date : time zones, immutability and calendars.
Syntax:
Temporal
Example:
if(typeof Temporal!=='undefined'){o.textContent=Temporal.Now.plainDateISO().add({days:10}).toString();}
else{o.textContent='Temporal is not available in this browser yet. Use Date for now.';}Date
Definition: Temporal replaces many problems of Date : time zones, immutability and calendars.
Syntax:
Date
Example:
else{o.textContent='Temporal is not available in this browser yet. Use Date for now.';}bind
Definition: bind fixes this .
Syntax:
bind
Example:
const hi=function(g){return g+', '+this.name;}.bind({name:'Ada'});this
Definition: bind fixes this .
Syntax:
this
Example:
const hi=function(g){return g+', '+this.name;}.bind({name:'Ada'});Object.entries
Definition: Object.entries lists pairs, getters compute values and Object.freeze locks an object.
Syntax:
Object.entries
Example:
o.textContent=[first,Object.keys(rest),p.full,Object.entries(q).length,Object.isFrozen(q)].join('\n');Object.freeze
Definition: Object.entries lists pairs, getters compute values and Object.freeze locks an object.
Syntax:
Object.freeze
Example:
const q={...p,age:36};Object.freeze(q);async
Definition: async functions use await to pause until it resolves, and try/catch handles failure.
Syntax:
async
Example:
async function run(){await
Definition: async functions use await to pause until it resolves, and try/catch handles failure.
Syntax:
await
Example:
const a=await wait(500,'first'); const [b,c]=await Promise.all([wait(300,'second'),wait(300,'third')]);
export
Definition: Mark a script with type='module' , then export from one file and import in another.
Syntax:
export
Example:
// math.js: export const add=(a,b)=>a+b;
import
Definition: Mark a script with type='module' , then export from one file and import in another.
Syntax:
import
Example:
// main.js: import {add} from './math.js';Proxy
Definition: A Proxy wraps an object and traps reads and writes.
Syntax:
Proxy
Example:
const p=new Proxy({},{Reflect
Definition: Reflect performs the default action.
Syntax:
Reflect
Example:
set(t,k,v){if(typeof v!=='number')throw new TypeError('numbers only');return Reflect.set(t,k,v);}Uint8Array
Definition: Typed arrays such as Uint8Array and Float32Array store numbers compactly and wrap values to their range.
Syntax:
Uint8Array
Example:
const a=new Uint8Array(3);a[0]=255;a[1]=256;a[2]=-1;
Float32Array
Definition: Typed arrays such as Uint8Array and Float32Array store numbers compactly and wrap values to their range.
Syntax:
Float32Array
Example:
const f=new Float32Array([0.1,0.2]);
requestAnimationFrame
Definition: Use requestAnimationFrame to redraw each frame and move shapes a little each time.
Syntax:
requestAnimationFrame
Example:
function f(){g.clearRect(0,0,280,100);g.fillStyle='tomato';g.beginPath();g.arc(x,50,16,0,7);g.fill();x=(x+2)%280;requestAnimationFrame(f);}XMLHttpRequest
Definition: XMLHttpRequest is the old API; fetch is the modern one.
Syntax:
XMLHttpRequest
Example:
const x=new XMLHttpRequest();
↗ JS AJAX
details
Definition: Many tasks need no script: details for toggles, dialog , popover , required validation and CSS :target .
Syntax:
details
Example:
<details><summary>Open me</summary>Hidden content, no JavaScript.</details>
popover
Definition: Many tasks need no script: details for toggles, dialog , popover , required validation and CSS :target .
Syntax:
popover
Example:
<div id='p' popover style='padding:12px'>Also no JavaScript</div>
Example code
<p id="o"></p>
<script>
const name = "Ada";
let age = 36;
age = age + 1;
document.getElementById("o").textContent = name + " is " + age;
</script>