Public
Edited
Jan 16
1 fork
Insert cell
Insert cell
Insert cell
{
const sales = 13.45;
//const sales = 14.56;
return sales;
}
Insert cell
Insert cell
{
let color = "steelblue";
return color;
}
Insert cell
Insert cell
{
let arr = [];
for (let i = 0; i < 10; i++) {
arr = arr.concat(i);
}
return arr;
}
Insert cell
{
let values = [2, 3, 4];

let arr = [];
for (let num of values) arr = arr.concat(num ** 2);
return arr;
}
Insert cell
Insert cell
{
const ints = [-3, -2, -1, 0, 1, 2, 3];
const aFloat = 3.14;

return [
ints,
3 ** 2,
3 / 2,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
Number.NaN,
Number("1"),
parseInt("2 little pigs"),
parseInt(aFloat.toFixed(0))
];
}
Insert cell
Insert cell
{
const floats = [-3.3, -2.2, -1.1, 0.0, 1.1, 2.2, 3.3];

return [
floats,
Math.sqrt(9),
Math.pow(3, 2),
4 ** 2,
Math.round(0.6),
Math.ceil(0.6),
Math.floor(0.6),
Math.min(2, 4, 6),
Math.max(2, 4, 6),
Math.random()
];
}
Insert cell
Insert cell
{
const firstSession = new Date(2021, 0, 4), // 0-based months (0: January)
today = new Date(),
daysSince = (today - firstSession) / (1000 * 60 * 60 * 24);

const options = {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric'
};
const dateTimeFormat = new Intl.DateTimeFormat('en-US', options);

return [
`${daysSince.toFixed(1)} days since our first class.`,
Date.parse("2021-01-11"),
today.getFullYear(),
today.getMonth(), // 0-based months (0: January)
today.getDate(), // 1-based days
today.getDay(), // 0-based day of week (0: Sunday)
today.getHours(), // local time
today.getMinutes(),
today.toString(),
today.toLocaleTimeString(),
today.toUTCString(),
today.toLocaleDateString('en-US'),
today.toISOString(),
dateTimeFormat.format(today),
`MYSQL format: ${today
.toISOString()
.slice(0, 19)
.replace('T', ' ')}`
];
}
Insert cell
Insert cell
{
const name = "Clinton Brownley",
firstCharacter = name.charAt(0),
lastCharacter = name.charAt(name.length - 1),
firstName1 = name.substring(0, 7), // 1 position farther than the last character you want
firstName2 = name.slice(0, 7), // 1 position farther than the last character you want
nameArray = name.split(' '),
nameChange = name.replace('Clinton', 'John'),
nameYell = name.toUpperCase(),
newName = 'Aisha ' + 'Brownley',
joinedName = ['Amaya', 'Brownley'].join(' ');

return [
name,
firstCharacter,
name[0],
lastCharacter,
name[name.length - 1],
firstName1,
firstName2,
nameArray,
nameChange,
nameYell,
newName,
joinedName,
name.startsWith("C"),
name.endsWith("y"),
name.includes(" ")
];
}
Insert cell
Insert cell
{
const msg = `Multiline
string`;
return msg
}
Insert cell
{
const html = `
<div>
<h1>Title</h1>
</div>`.trim();
return html;
}
Insert cell
{
const count = 25,
price = 10.00,
msg = `${count} items cost $${(count * price).toFixed(2)}.`;
return msg;
}
Insert cell
Insert cell
{
const patternJS = /\bJAVASCRIPT\b/i; // Match "javascript" as a word, case-insensitive
const patternDigits = /\d+/g; // Match all instances of one or more digits

const text = 'Javascript, making the web dynamic is as easy as 1, 2, 3!';

return [
patternJS.test(text),
patternDigits.test(text),
text.search(patternJS), // position of first match
text.search(patternDigits), // position of first match
text.match(patternJS), // array of all matches
text.match(patternDigits), // array of all matches
text.replace(patternDigits, '$'), // changing each digit
text.replace(/1, 2, 3/, 'A, B, C'), // changing whole pattern '1, 2, 3'
text.split(/\bDynamic\b/i),
text.split(new RegExp('web dynamic'))
];
}
Insert cell
Insert cell
{
const values = [10, 20, 30, 40, 50]
return Math.max(...values)
}
Insert cell
{
const values = [-10, -20, -30, -40, -50]
return Math.max(...values, 0)
}
Insert cell
Insert cell
{
const sum = (num1, num2) => num1 + num2
return sum(3, 7)
}
Insert cell
{
const getName = () => "Clinton"
return getName()
}
Insert cell
{
const getObjId = id => ({ id: id, name: "Clinton" })
return getObjId("ABC")
}
Insert cell
{
const values = [50, 40, 30, 20, 10];

const valuesSorted = values.sort((a, b) => a - b);

return valuesSorted;
}
Insert cell
Insert cell
{
const addThreeDefaults = (first = 1, second = 2, third = 3) =>
first + second + third;

const calcTotalCost = (price = 10, taxRate = 0.15) => {
let taxes = price * taxRate;
return price + taxes;
};

return [addThreeDefaults(), calcTotalCost(20)];
}
Insert cell
Insert cell
{
const createPerson = (name, age) => ({
name,
age,
sayName() {
return `Hello ${this.name}`;
}
});

return createPerson("Clinton Brownley", 24).sayName();
}
Insert cell
Insert cell
{
const node = {
type: "person",
name: "Clinton"
}
const { type, name } = node
return [type, name]
}
Insert cell
{
const node = {
type: "person",
name: "Clinton"
}
const { type: localType, name: localName } = node
return [localType, localName]
}
Insert cell
Insert cell
{
const colors = [ "red", "green", "blue" ]
const [ firstColor, secondColor ] = colors
return [firstColor, secondColor]
}
Insert cell
{
const colors = [ "red", "green", "blue" ]
const [ , , thirdColor ] = colors
return [thirdColor]
}
Insert cell
{
const colors = [ "red", "green", "blue" ]
const [ firstColor, ...restColors ] = colors
return [firstColor, restColors.length, restColors[0], restColors[1] ]
}
Insert cell
{
const colors = [ "red", "green", "blue" ]
const [ ...clonedColors ] = colors
return clonedColors
}
Insert cell
Insert cell
{
let set = new Set();

set.add(5);
set.add(10);
set.add(15);
const setSizeBefore = set.size;

set.delete(15);
const setSizeAfter = set.size;

return [set, set.has(5), setSizeBefore, setSizeAfter];
}
Insert cell
{
const set = new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])
return set
}
Insert cell
{
const set = new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]),
arr = [...set]
return arr
}
Insert cell
{
const numbers = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
const eliminateDuplicates = (items) => [...new Set(items)]
return eliminateDuplicates(numbers)
}
Insert cell
{
const set = new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])
let output = []
set.forEach((value, key, ownerSet) => {
output = [...output, `${key}: ${value}`]
})
return output
}
Insert cell
Insert cell
{
let map = new Map();

map.set("name", "Clinton");
map.set("age", 25);
map.set("sport", "basketball");
const setSizeBefore = map.size;

map.delete("sport");
const setSizeAfter = map.size;

return [map, map.has("name"), map.get("age"), setSizeBefore, setSizeAfter];
}
Insert cell
{
let map = new Map([["name", "Clinton"], ["age", 25]]);

return map;
}
Insert cell
{
const map = new Map([["name", "Clinton"], ["age", 25]])
let output = []
map.forEach((value, key, ownerMap) => {
output = [...output, `${key}: ${value}`]
})
return output
}
Insert cell
Insert cell
Insert cell
{
const colors = ["red", "green", "blue"]
const zips = new Set([95014, 95014, 95014, 95014, 95070, 95025])
const data = new Map()
data.set("language", "javascript")
data.set("topic", "iterators")
let output = []
// array
for (let entry of colors.entries()) output = [...output, entry]
// set
for (let entry of zips.entries()) output = [...output, entry]
// map
for (let entry of data.entries()) output = [...output, entry]
return output
}
Insert cell
Insert cell
{
const colors = ["red", "green", "blue"]
const zips = new Set([95014, 95014, 95014, 95014, 95070, 95025])
const data = new Map()
data.set("language", "javascript")
data.set("topic", "iterators")
let output = []
// array
for (let value of colors.values()) output = [...output, value]
// set
for (let value of zips.values()) output = [...output, value]
// map
for (let value of data.values()) output = [...output, value]
return output
}
Insert cell
Insert cell
{
const colors = ["red", "green", "blue"];
const zips = new Set([95014, 95014, 95014, 95014, 95070, 95025]);
const data = new Map();

data.set("language", "javascript");
data.set("topic", "iterators");

let output = [];

// array
for (let key of colors.keys()) output = [...output, key];

// set
for (let key of zips.keys()) output = [...output, key];

// map
for (let key of data.keys()) output = [...output, key];

return output;
}
Insert cell
Insert cell
{
const colors = ["red", "green", "blue"];
const zips = new Set([95014, 95014, 95014, 95014, 95070, 95025]);
const data = new Map();

data.set("language", "javascript");
data.set("topic", "iterators");

let output = [];

// same as using colors.values()
for (let value of colors) output = [...output, value];

// same as using zips.values()
for (let value of zips) output = [...output, value];

// same as using data.entries()
for (let entry of data) output = [...output, entry];

return output;
}
Insert cell
Insert cell
{
let set = new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]),
array = [...set]
return array
}
Insert cell
{
let map = new Map([["name", "Clinton"], ["age", 25]]),
array = [...map]
return array
}
Insert cell
{
const smallNums = [1, 2, 3],
bigNums = [1001, 1002, 1003],
allNums = [100, ...smallNums, ...bigNums]
return allNums
}
Insert cell
Insert cell
Insert cell
{
const set = new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]),
map = new Map([["name", "Clinton"], ["age", 25]])
const arr1 = Array.from(set)
const arr2 = Array.from(map)
return [...arr1, ...arr2]
}
Insert cell
{
const set = new Set([2, 2, 3, 3, 4, 4, 5, 5, 6, 6])
const doubled = Array.from(set, (value) => value * 2)
return doubled
}
Insert cell
Insert cell
{
let person = { name: 'Clinton Brownley', age: 30 };

const changeAge1 = (person, age) => Object.assign({}, person, { age: age });

const changeAge2 = (person, age) => ({ ...person, age });

return [
person,
changeAge1(person, 25),
person,
changeAge2(person, 27),
person
];
}
Insert cell
{
let arrayOfPeople = [
{ name: 'Clinton Brownley', age: 30 },
{ name: 'Rachel Hiner', age: 25 },
{ name: 'Gloria Yu', age: 21 }
];

const addPerson = (person, array) => array.concat(person);

return [
arrayOfPeople,
addPerson({ name: 'Scott Porcello', age: 27 }, arrayOfPeople),
arrayOfPeople
];
}
Insert cell
{
const clinton = {
name: 'Clinton Brownley',
age: 30,
canRead: false,
canWrite: false
};

const getEducated = person => ({ ...person, canRead: true, canWrite: true });

return [clinton, getEducated(clinton), clinton];
}
Insert cell
Insert cell
{
const teams = ['FC Barcelona', 'Real Madrid', 'Manchester United'];

return [teams.filter(team => team[0] === 'R'), teams];
}
Insert cell
{
const teams = ['FC Barcelona', 'Real Madrid', 'Manchester United'];

const cutTeam = (cut, list) => list.filter(team => team !== cut);

return [cutTeam('Real Madrid', teams), teams];
}
Insert cell
Insert cell
{
const teams = ['FC Barcelona', 'Real Madrid', 'Manchester United'];

return [teams.map(team => `${team} Football Club`), teams];
}
Insert cell
{
const teams = ['FC Barcelona', 'Real Madrid', 'Manchester United'];

return teams.map(team => ({ name: team }));
}
Insert cell
{
const teams = [
{ name: 'FC Barcelona' },
{ name: 'Real Madrid' },
{ name: 'Manchester United' }
];

return [editTeamName('Real Madrid', 'Paris Saint-Germain', teams), teams];
}
Insert cell
Insert cell
{
const teams = {
'FC Barcelona': 5,
'Real Madrid': 6,
'Manchester United': 7
};

const teamsArray = Object.keys(teams).map(key => ({
name: key,
wins: teams[key]
}));

return [teamsArray, teams];
}
Insert cell
Insert cell
{
const numbers = [41, 35, 46, 75, 95, 83, 37, 10, 93];

const max = numbers.reduce((max, value) => (value > max ? value : max), 0);

return max;
}
Insert cell
{
const teams = [
{ name: 'FC Barcelona', wins: 5, cost: 110 },
{ name: 'Real Madrid', wins: 6, cost: 105 },
{ name: 'Manchester United', wins: 4, cost: 100 }
];

const hashTeams = teams.reduce((hash, { name, wins, cost }) => {
hash[name] = { wins, cost };
return hash;
}, {});

return hashTeams;
}
Insert cell
{
const colors = [
'red',
'red',
'red',
'green',
'green',
'blue',
'blue',
'blue'
];

const distinctColors = colors.reduce(
(distinct, color) =>
distinct.indexOf(color) !== -1 ? distinct : [...distinct, color],
[]
);

return distinctColors;
}
Insert cell
Insert cell
fakeMembers = getFakeMembers(50).then(
members => members,
err => new Error("cannot load members from randomuser.me")
)
Insert cell
Insert cell
Insert cell
d3 = require("d3@6")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more