Skip to content

Instantly share code, notes, and snippets.

function myFunction() {
const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
// (accumulator, currentValue) => accumulator.concat(currentValue)
function(accumulator, currentValue) {return accumulator.concat(currentValue);}
);
console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]
}
function myFunction() {
const array1 = [1, 2, 3, 4];
// const reducer = (accumulator, currentValue) => accumulator + currentValue;
const reducer = function(accumulator, currentValue) { return accumulator + currentValue;};
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
function myFunction() {
// var power = function(x) { return x * x;}; // JavaScript 1.7 and older
var power = function(x) x * x; // error
var result = power(10);
console.log(result);
}
function destructuringAssignment() {
var a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
function constFunction() {
const number = 42;
try {
number = 99;
} catch(err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
function letFunction() {
let x = 1; // error
if (x === 1) {
let x = 2; // error
console.log(x);
// expected output: 2
}
function mapFunction() {
var numbers = [1, 2, 3, 4];
// var doubled = numbers.map(i => i * 2);
var doubled = numbers.map(function(i) {return i * 2;});
console.log(doubled); // logs 2,4,6,8
}
function filterFunction() {
function myFunction() {
[for (i of [1, 2, 3]) i * i ]; // error
// [1, 4, 9]
var abc = ['A', 'B', 'C'];
[for (letters of abc) letters.toLowerCase()]; // error
// ["a", "b", "c"]
}
function* makeRangeIterator(start, end, step) { // error
var iterationCount = 0;
for (var i = start; i < end; i += step) {
iterationCount++;
yield i; // error
}
return iterationCount;
}
function useMakeRangeIterator() {
function makeRangeIterator(start, end, step) {
var nextIndex = start;
var iterationCount = 0;
var rangeIterator = {
next: function() {
var result;
if (nextIndex < end) {
result = { value: nextIndex, done: false }