function sayHello(name) {
document.writeln("Hello, " + name);
}
function max(x, y) {
if (x < y)
return y;
else
return x;
}
let x = 3;
function test() {
// y is local
let y = 10;
document.writeln("y is " + y);
// x is global
document.writeln("x is " + x);
}
// z is 0 if not supplied
function sum(x, y, z = 0) {
return x + y + z;
}
total = sum(1, 2); // 3
total = sum(1, 2, 4); // 7
parseFloat("s")
- Converts the beginning of a string to a
floating-point value; returns NaN
if unsuccessful
let x = parseFloat("1.23"); // 1.23
parseInt("s")
- Converts the beginning of a string to an
integer value; returns NaN
if unsuccessful
let x = parseInt("66"); // 66
isNaN("s")
- Returns true
if the argument is not a number,
false
otherwise
if (isNaN("dog")) {
console.log("'dog' is not a number.");
}
// Careful... empty string or string with all spaces is NOT NaN!
if (!isNaN("")) {
console.log("Empty string is a number!");
}
isFinite(value)
- Returns true
if the argument is a number in the
range that JavaScript supports, false
otherwise
isFinite(123) // true
isFinite(6.5) // true
isFinite(false) // true (because false = 0)
isFinite("dog") // false
alert(s)
-
Alert dialog box with OK button
alert("This is an alert.");
prompt(s)
- Dialog box that
prompts the user
for a single line of text; returns the text or null
if Cancel is pressed
let firstName = prompt("Enter your name:");
confirm(s)
- Dialog box that
asks a question;
returns true
if OK is pressed, false
otherwise
let answer = confirm("Are you sure?");
// Assign an anonymous function to a variable
let hello = function() { alert('Hello'); }
// Variable acts like a function
hello();
let nums = [8, 2, -1, 5];
// Sort in descending order
nums.sort(function(a, b) {
return b - a;
});
// Display the even numbers in the array
nums.forEach(function(n) {
if (n % 2 == 0)
console.log(n);
});
(param1, param2, …, paramN) => { statements } // No return value
(param1, param2, …, paramN) => expression // same as: => { return exp; }
// Parentheses are optional when there's only one parameter:
(singleParam) => { statements }
singleParam => { statements }
let hello = name => console.log("Hello, " + name);
hello("Bob");
// Same as
let hello = function(name) {
console.log("Hello, " + name);
};
let add = () => 1 + 2;
let num = add(); // 3
// Same as
let add = function() {
return 1 + 2;
};
let subtract = (x, y) => x - y;
let num = subtract(4, 3); // 1
// Same as
let subtract = function(x, y) {
return x - y;
};
let nums = [8, 2, -1, 5];
// Sort in descending order
nums.sort((a, b) => b - a);
// Display the even numbers in the array
nums.forEach(n => {
if (n % 2 == 0)
console.log(n);
});