Home
Download

JavaScript Reference

? :
var i = 3;
console.log((i == 3) ? "three" : "not three");
three
`${}`
var s = "World";
console.log(`Hello ${s}`);
Hello World
AJAX
[hello.txt]
Hello

[ajax.html]
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "hello.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{ if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    console.log(xmlhttp.responseText); }
Hello (only available on server)
alert
console.log
alert("Hello");
console.log("Hello");
Hello in window
Hello in console
Array
length
var a = new Array("A", "B", "C", "D");
var a = ["A", "B", "C", "D"];  // another expression
console.log(a.length);
console.log(a[0]);
console.log(a[a.length - 1]);
4
A
D
async
Promise
await
async function f()
{ var p = new Promise((resolve, reject) => { setTimeout(() => resolve("Hello"), 3000); });
  var s = await p;
  console.log(s); }
f();
Hello (shown in 3 seconds)
call
apply
function f() { console.log("Hello"); }
f.call();
f.apply();
Hello
Hello
charAt
charCodeAt
fromCharCode
var s = "Hello";
console.log(s.charAt(4));
console.log(s.charCodeAt(4));
console.log(String.fromCharCode(111));
o
111
o
childNodes
nodeName
firstChild
lastChild
<div id="x"><h1>1</h1><h2>2</h2><h3>3</h3></div>

var c = document.getElementById("x").childNodes;
for (var i = 0; i < c.length; i++)
  console.log(c[i].nodeName);
var e = document.getElementById("x");
console.log(e.firstChild.nodeName);
console.log(e.lastChild.nodeName);
H1
H2
H3
H1
H3
class
class cuboid { constructor(length, width, height, volume)
{ this.length = length;
  this.width = width;
  this.height = height;
  this.volume = this.length * this.width * this.height; } }
var c = new cuboid(5, 4, 3);
console.log(c.volume);
60
comment
// comment

/*
comment1
comment2
comment3
*/
 
confirm
prompt
null
var c = confirm("YES or NO?");
if (c == true)
  console.log("YES")
else
  console.log("NO");
var p = prompt("YES or NO?", "YES");
if (p == "" || p == null)
  console.log("NULL")
else
  console.log(p);
e.g. YES and YES
constructor
var a = new Array("A", "B", "C", "D");
if (a.constructor == Array)
  console.log("Array");
Array
Date
var d = new Date();
console.log(d.getFullYear() + "-" + d.getMonth() + "-" + d.getDay());
2019-11-25
debugger
console.log("A");
debugger;
console.log("B");
A if F12 is pressed
document.addEventListener
document.removeEventListener
function f() { console.log("mouse moved");
               document.removeEventListener("mousemove", f); }
document.addEventListener("mousemove", f);
mouse moved
document.cookie
toUTCString
var d = new Date();
d.setTime(d.getTime() + 90 * 24 * 60 * 60 * 1000); // expire in 90 days
document.cookie = "username=John Doe; expires=" + d.toUTCString() + "; path=/";
console.log(document.cookie);
username=John Doe (only available on server)
toUTCString = Wed, 29 Nov 2023 13:27:45 GMT
document.createElement
document.getElementById
appendChild
<div id="x">0</div>

var i, e;
for (i = 1; i <= 5; i++)
{ e = document.createElement("div");
  document.getElementById("x").appendChild(e);
  e.id = i;
  document.getElementById(i).innerHTML = i; }
0
1
2
3
4
5
document.onkeydown
event.key
event.keyCode
document.onkeydown = function(event)
{ var s = event.key;
  console.log(s);
  var i = event.keyCode;
  console.log(i); }
Enter
13
document.querySelector
document.querySelectorAll
<p class="x">1</p>
<p class="x">2</p>
<p class="x">3</p>

document.querySelector(".x").innerHTML = "ONE";
var p = document.querySelectorAll(".x");
p[0].innerHTML = "one";
p[1].innerHTML = "two";
p[2].innerHTML = "three";
one (1 -> ONE -> one)
two
three
document.write
document.writeln
H<script>document.write("ell");</script>o
H<script>document.writeln("ell");</script>o
Hello
Hell o
escape
unescape
encodeURI
decodeURI
encodeURIComponent
decodeURIComponent
console.log(escape("你好"));
console.log(unescape("%u4F60%u597D"));
console.log(encodeURI("你好"));
console.log(decodeURI("%E4%BD%A0%E5%A5%BD"));
console.log(encodeURIComponent("google.com/search?q=北京"));
console.log(decodeURIComponent("google.com%2Fsearch%3Fq%3D%E5%8C%97%E4%BA%AC"));
%u4F60%u597D
你好
%E4%BD%A0%E5%A5%BD
你好
google.com%2Fsearch%3Fq%3D%E5%8C%97%E4%BA%AC
google.com/search?q=北京
eval
eval("console.log('" + "Hello" + "')");
Hello
event.clientX
event.clientY
<body onclick="console.log(event.clientX + ', ' + event.clientY)"></body>
e.g. 302, 286
export
import
[module.js]
export function Hello() { console.log("Hello"); }

[index.html]
<script type="module">
import {Hello} from "./module.js";
Hello();
</script>
Hello (only available on server)
for
continue
var i;
for (i = 1; i <= 3; i++)
{ if (i == 2)
    continue;
  console.log(i); }
1
3
for/in
var i, a = new Array("A", "B", "C", "D");
for (i in a)
  console.log(a[i]);
A
B
C
D
forEach
var a = new Array("A", "B", "C", "D");
a.forEach(f);
function f(i) { console.log(i); }
A
B
C
D
function
return
function f(i, j)
{ return i + j; }
var k = f(2, 3);
console.log(k);
var f = (i, j) => i + j; // another expression
var k = f(2, 3);
console.log(k);
5
5
getSelection
<textarea onselect="alert(window.getSelection())">Hello</textarea>
<textarea onselect="alert(document.getSelection())">Hello</textarea>
ll if "ll" is selected
history
<button onclick="history.back()">back</button>
<button onclick="history.forward()">forward</button>
back
forward
if/else
var i = 3;
if (i == 1)
  console.log("one")
else if (i == 2)
  console.log("two")
else if (i == 3)
  console.log("three")
else
  console.log("greater than three");
three
if/else
var i = 3;
if (i == 1)
  console.log("one")
else if (i == 2)
  console.log("two")
else if (i == 3)
  console.log("three")
else
  console.log("greater than three");
three
includes
var a = new Array("A", "B", "C", "D");
console.log(a.includes("C"));
true
indexOf
lastIndexOf
search
var s = "Hello", i, j, k;
i = s.indexOf("l");
j = s.lastIndexOf("l");
k = s.search(/l/i);
console.log(i);
console.log(j);
console.log(k);
2
3
2
Infinity
var i = 1 / 0;
console.log(i);
Infinity
isNaN
console.log(isNaN(5));
console.log(isNaN("Hello"));
false
true
join
split
var a = new Array("A", "B", "C", "D"), s, b;
s = a.join(" ");
console.log(s);
b = s.split(" ");
console.log(b);
A B C D
['A', 'B', 'C', 'D']
jQuery
<script src="jquery-3.6.1.slim.min.js"></script>

<script>
$(document).ready(function()
{ $("button#x").click(function()
  { console.log("Hello"); }); });
</script>

<button id="x">Hello</button>
Hello
JSON
var cuboid = { length: 5,
               width: 4,
               height: 3 }, s, o;
s = JSON.stringify(cuboid);
console.log(s);
o = JSON.parse(s);
console.log(o);
{"length":5,"width":4,"height":3}
{length:5, width:4, height:3}
localeCompare
var s1 = "abc", s2 = "xyz";
console.log(s1.localeCompare(s2));
var s1 = "xyz", s2 = "abc";
console.log(s1.localeCompare(s2));
-1 (s1 comes before s2)
1 (s1 comes after s2)
localStorage
sessionStorage
var f;
localStorage.setItem("pi", 3.14);
f = localStorage.getItem("pi");
console.log(f);
sessionStorage.setItem("pi", 3.14);
f = sessionStorage.getItem("pi");
console.log(f);
3.14
3.14
location.href
window.open
location.href = "https://www.google.com";
window.open("https://www.google.com", "", "width=300, height=300");
visit google in current window
visit google in new window
location.reload
<button onclick="location.reload()">Reload</button>
reload
Map
const m = new Map();
m.set("a", 1);
m.set("b", 2);
m.set("c", 3);
console.log(m.get("b"));
2
Math
console.log(Math.min(1, 5));
console.log(Math.max(1, 5));
console.log(Math.round(4.6));
console.log(Math.floor(4.6));
console.log(Math.ceil(4.6));
console.log(Math.random());
1
5
5
4
5
0.8361748718178987
navigator.clipboard
then
navigator.clipboard.writeText("Hello").then(function w() { console.log("Hello"); });
navigator.clipboard.readText().then(function r(text) { console.log(text); });
Hello
Hello
navigator.geolocation
if (navigator.geolocation)
  navigator.geolocation.getCurrentPosition(f);
function f(position)
{ console.log(position.coords.latitude);
  console.log(position.coords.longitude); }
38.855868
115.384835
navigator.onLine
if (navigator.onLine)
  console.log("online")
else
  console.log("offline");
online
navigator.userAgent
var s = navigator.userAgent;
console.log(s);
var a = s.match(/Chrome\/\d+/);
if (a != null)
  console.log(a[0].replace(/\//, " v"));
... Chrome/103.0.5060.114 ...
Chrome v103
Number
String
typeof
var i, s;
i = Number("3");
s = String(3);
console.log(typeof i);
console.log(typeof s);
number
string
object
var cuboid = { length: 5,
               width: 4,
               height: 3,
               volume: function() { return this.length * this.width * this.height; } }
console.log(cuboid.length);
console.log(cuboid.volume());
5
60
outerHTML
innerHTML
<div id="x">Hello</div>

console.log(document.getElementById("x").outerHTML);
console.log(document.getElementById("x").innerHTML);
<div id="x">Hello</div>
Hello
parseInt
parseFloat
console.log(parseInt("3.99$"));
console.log(parseInt("$3.99"));
console.log(parseFloat("3.99$"));
console.log(parseFloat("$3.99"));
3
NaN
3.99
NaN
prototype
String.prototype.trim = function()
{ return this.replace(/(^\s*)|(\s*$)/g, ""); }
var s = "   Hello   ";
s = s.trim();
console.log("|" + s + "|");
|Hello|
push
pop
var a = new Array("A", "B", "C");
a.push("D");
console.log(a);
var b = new Array("A", "B", "C", "D");
b.pop();
console.log(b);
['A', 'B', 'C', 'D']
['A', 'B', 'C']
RegExp
test
exec
match
var re = new RegExp("^[A-z]+$");
// another expression: var re = /^[A-z]+$/;
console.log(re.test("Hello"));
console.log(re.test("Hell8"));
console.log(re.exec("Hello"));
console.log(re.exec("Hell8"));
console.log("Hello".match(re));
console.log("Hell8".match(re));
true
false
['Hello' ...]
null
['Hello' ...]
null
replace
replaceAll
var s = "Hekko";
console.log(s.replace("k", "l"));
console.log(s.replaceAll("k", "l"));
Helko
Hello
screen.width
screen.height
screen.availWidth
screen.availHeight
console.log(screen.width);
console.log(screen.height);
console.log(screen.availWidth);
console.log(screen.availHeight);
1366
768
1366
728
script
[include.js]
console.log("Hello");

[index.html]
<script src="include.js"></script>
Hello
Set
var s = new Set();
s.add("h");
s.add("e");
s.add("l"); // valid adding
s.add("l"); // invalid adding
s.add("o");
console.log(s);
console.log(s.has("o"));
console.log(s.has("x"));
Set (4) {'h', 'e', 'l', 'o'}
true
false
setAttribute
getAttribute
removeAttribute
<button id="x">Hello</button>

var e, t;
e = document.getElementById("x");
e.setAttribute("disabled", "true");
console.log(e.getAttribute("disabled"));
t = setTimeout("e.removeAttribute('disabled')", 5000);
true
setInterval
clearInterval
var i = setInterval("console.log('Hello')", 10000);

<button onclick="clearInterval(i)">stop</button>
display "Hello" every 10 seconds until press "stop"
setTimeout
clearTimeout
var t = setTimeout("console.log('Hello')", 10000);

<button onclick="clearTimeout(t)">stop</button>
display "Hello" in 10 seconds if don't press "stop"
shift
unshift
var a = new Array("A", "B", "C", "D");
a.shift();
console.log(a);
var b = new Array("B", "C", "D");
b.unshift("A");
console.log(b);
['B', 'C', 'D']
['A', 'B', 'C', 'D']
sort
reverse
var a = new Array("D", "C", "B", "A"), b;
b = a.sort();
console.log(b);
b.reverse();
console.log(b);
['A', 'B', 'C', 'D']
['D', 'C', 'B', 'A']
splice
var a = new Array("A", "B", "D"); // insert
a.splice(2, 0, "C");
console.log(a);

var a = new Array("A", "B", "X", "C", "D"); // delete
a.splice(2, 1);
console.log(a);

var a = new Array("A", "B", "X", "D"); // replace
a.splice(2, 1, "C");
console.log(a);
['A', 'B', 'C', 'D']
['A', 'B', 'C', 'D']
['A', 'B', 'C', 'D']
0 & 1 = deletion count
startsWith
endsWith
var s = "Hello";
console.log(s.startsWith("H"));
console.log(s.endsWith("o"));
true
true
substr
substring
slice
var s = "Hello", i, j;
i = s.indexOf("e");
j = s.indexOf("o");
console.log(s.substr(i, 4));
console.log(s.substring(i, j));
console.log(s.slice(i, j));
ello
ell
ell
switch
break
var i = 3;
switch (i)
{ case 1: console.log("one");
          break;
  case 2: console.log("two");
          break;
  case 3: console.log("three");
          break;
  default: console.log("greater than three"); }
three
this
<button onclick="this.style.display='none'">disappear</button>
disappear
throw
var i = 4;
try
{ if (i > 3)
    throw "greater than three"; }
catch(error)
{ console.log(error); }
finally
{ i = 3; }
greater than three
toFixed
toPrecision
var i = 9.6573;
console.log(i.toFixed(2));
console.log(i.toPrecision(3));
9.66
9.66
toLowerCase
toUpperCase
var s1 = "HELLO";
console.log(s1.toLowerCase());
var s2 = "hello";
console.log(s2.toUpperCase());
hello
HELLO
toString
var i = 123;
console.log(i.toString(2));
console.log(i.toString(8));
console.log(i.toString(10));
console.log(i.toString(16));
1111011
173
123
7b
trim
trimStart
trimEnd
var s = "   Hello   ";
console.log("|" + s.trim() + "|");
console.log("|" + s.trimStart() + "|");
console.log("|" + s.trimEnd() + "|");
|Hello|
|Hello   |
|   Hello|
try
catch
finally
try
{ display("Hello"); }
catch(error)
{ console.log(error.message); }
finally
{ console.log("Hello"); }
display is not defined
Hello
undefined
var i;
if (i === undefined)
  console.log("i is undefined");
i is undefined
use strict
"use strict";
pi = 3.14;
pi is not defined
var
let
const
var i = 3; // global
console.log(i);
{ let i = 5; // local
  console.log(i); }
console.log(i);
const pi = 3.14;
console.log(pi);
3
5
3
3.14
void
<a href="javascript:void(0)">do nothing</a>
do nothing
WebSocket
var ws = new WebSocket("https://echo.websocket.org");
ws.onopen = function(event) { ws.send("Hello"); };
ws.onmessage = function(event) { console.log(event.data);
                                 ws.close(); };
Hello (sent message)
Request served by 1781505b56ee58 (received message)
while
do/while
var i = 1, j = 1;
while (i <= 3)
{ console.log(i);
  i++; }
do
{ console.log(j);
  j++; }
while (j <= 3);
1
2
3
1
2
3
with
with (Math)
{ console.log(floor(4.6));
  console.log(ceil(4.6)); }
4
5