return
statement returns undefined
function sayHello(name) {
console.log("Hello, " + name);
}
function max(x, y) {
if (x < y) {
return y;
}
else {
return 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
// x is global
let x = 3;
function test() {
// y is local
let y = 10;
console.log("y is " + y);
// x is global
console.log("x is " + x);
}
let
has block scope, but variable declared with var
does not
function test(num) {
if (num > 0) {
let x = 2;
console.log("x is " + x);
}
// Exception thrown because x is scoped to the if statement
console.log("x is " + x);
}
var
does not have block scope
function test(num) {
if (num > 0) {
var x = 2;
console.log("x is " + x);
}
// No exception thrown because x is scoped to the function
console.log("x is " + x);
}
let
or var
) have global scope!
function test(num) {
if (num > 0) {
// Implicitly declared
x = 2;
console.log("x is " + x);
}
}
test(2);
// No exception thrown because x is global
console.log("x is " + x);
var
or implicitly
declared become properties of the global object
// Adds x as a property to window
var x = 5;
// Adds y as a property to window
y = 10;
// Does NOT add a property to window
let z = 20;
console.log(window.x); // 5
console.log(window.y); // 10
console.log(window.z); // undefined
function outerFunc() {
let value = "Test";
function innerFunc() {
console.log(value);
}
innerFunc();
}
outerFunc(); // Outputs "Test"
function getEventNums(nums) {
function isEven(num) {
return num % 2 === 0;
}
return nums.filter(isEven);
}
let nums = [8, 3, 2, 5];
let evens = getEventNums(nums); // returns [8, 2]
// 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);
}
});