Published
Edited
Jan 21, 2020
Insert cell
Insert cell
{
// Semicolons are optional
return 21 * 2
}
Insert cell
{
// The const keyword
const foo = 42
foo = 0
}
Insert cell
{
// Arrow functions
// If you're immediately returning a value, no curly braces are needed:
const add = (a, b) => a + b
// If there's only one argument, parentheses aren't needed, either:
const square = n => n**2
return [ add(10, 32), square(4) ]
}
Insert cell
{
// More examples of arrow functions
// If there is a function body, curly braces are needed:
const fibonacci = n => {
if (n < 2) {
return 1
}
else {
return fibonacci(n - 1) + fibonacci(n - 2)
}
}
/* A shorter fibonacci function that uses the ternary operator:
<condition> ? <value_if_true> : <value_if_false>
*/
const fib = n =>
n < 2 ? 1
: fib(n - 1) + fib(n - 2)
return [ fibonacci(7), fib(7) ]
}
Insert cell
{
// The "spread" operator, ...
// The spread operator makes working with arrays more natural.
const left = [1, 2, 3]
const right = [4, 5, 6]
const foo = [...left, ...right] // "the stuff from left, then the stuff from right"
// Note foo is a *new* array.
return foo
}
Insert cell
{
// The spread operator also applies to objects.
const thing_1 = {key1: 'value1', key2: 'value2'}
const thing_2 = {key3: 'value3', key2: 'value4'}
const bar = {...thing_1, ...thing_2} // make a new object with the stuff from thing_1 and (then) thing_2
// Note that key2 gets "overwritten"--the last key-value pair wins.
return bar
}
Insert cell
{
// Object "destructuring"
const foo = {a: 1, b: 2, c: 3}
const {a, b, c} = foo // foo gets "destructured"
return c // now we can access foo's keys as variables
}
Insert cell
{
// You can also destructure the arguments to functions.
const object_adder = ({a, b}) => a + b
const baz = {a: 3, b: 9}
return object_adder(baz)
}
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