Math.max(a, b)
- Returns the larger of the two values
let x = Math.max(4, Math.PI); // 4
Math.pow(a, b)
- Returns a
to the power of b
let x = Math.pow(2, 3); // 8
Math.sqrt(n)
- Returns the square root of n
let x = Math.sqrt(25); // 5
Math.random()
- Returns a pseudorandom number between 0.0 and 1.0
// Get a random number between 1 and 10 (inclusive)
let x = Math.floor(1 + Math.random() * 10);
charAt(i)
- Returns the character at index i
or an
empty string if no character is present at that index
let s = "Hello there!";
let t = s.charAt(0); // "H"
t = s[1]; // [] works the same, returns "e"
indexOf(s, [i])
- Returns the first occurence of the substring s
starting at the position i
, -1 if the substring is not found
let s = "Hello there!";
let t = s.indexOf("the"); // 6
replace(search, replace)
- Replaces the first search
string
with the replace
string and returns the modified string
let s = "Hello there!";
s = s.replace("there", "man"); // "Hello man!"
substr(start, length)
- Returns a substring with length length
(optional) that begins at index start
let s = "Hello there!";
s = s.substr(6, 5); // "there"
trim()
- Returns a string with all white space at beginning and end removed
let s = " Hello there! ";
s = s.trim(); // "Hello there!"
split(delimiter)
- Returns a an
array that splits the string with the given delimiter
let s = "This is a test";
let words = s.split(" "); // ["This", "is", "a", "test"]
x = 4;
y = 3;
s = `${x} - ${y} = ${x - y}`; // "4 - 3 = 1"
let now = new Date();
s = now.toString(); // Tue Aug 21 2012 16:17:26 GMT-0500 (Central Daylight Time)
s = now.getDate(); // 21
s = now.getDay(); // 2 (0-6 for Sun-Sat)
s = now.getMonth(); // 7 (0-11 for Jan-Dec)
s = now.getFullYear(); // 2012
s = now.getTime(); // 1345584701802 (milliseconds since midnight Jan 1, 1970)
s = now.getHours(); // 16
s = now.getMinutes(); // 17
s = now.getSeconds(); // 26
let billGates = new Date(1955, 9, 28); // Oct 28, 1955
let steveJobs = new Date(1955, 1, 24); // Feb 24, 1955
let oneDay = 1000 * 60 * 60 * 24; // Milliseconds in a day
// "Steve is older by 246 days."
if (billGates < steveJobs) {
let diff = Math.ceil((steveJobs.getTime() - billGates.getTime()) / oneDay);
document.writeln("Bill is older by " + diff + " days.");
}
else {
let diff = Math.ceil((billGates.getTime() - steveJobs.getTime()) / oneDay);
document.writeln("Steve is older by " + diff + " days.");
}