function sayHello(name) {
document.writeln("Hello, " + name);
}
function max(x, y) {
if (x < y)
return y;
else
return x;
}
var x = 3;
function test() {
// y is local
var 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
var x = parseFloat("1.23"); // 1.23
parseInt("s")
- Converts the beginning of a string to an
integer value; returns NaN
if unsuccessful
var x = parseInt("66"); // 66
isNaN("s")
- Returns true
if the argument is not a number,
false
otherwise
if (isNaN("dog"))
alert("This is not 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
firstName = prompt('Enter your name:');
confirm(s)
- Dialog box that
asks a question;
returns true
if OK is pressed, false
otherwise
answer = confirm('Are you sure?');
// Assign an anonymous function to a variable
var hello = function() { alert('Hello'); }
// Variable acts like a function
hello();
var 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 }
var hello = name => console.log("Hello, " + name);
hello("Bob");
// Same as
var hello = function(name) {
console.log("Hello, " + name);
};
var add = () => 1 + 2;
var num = add(); // 3
// Same as
var add = function() {
return 1 + 2;
};
var subtract = (x, y) => x - y;
var num = subtract(4, 3); // 1
// Same as
var subtract = function(x, y) {
return x - y;
};
var 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);
});