// If you're immediately returning a value, no curly braces are needed:
constadd=(a,b)=>a+b
// If there's only one argument, parentheses aren't needed, either:
constsquare=n=>n**2
return[add(10,32),square(4)]
}
{
// More examples of arrow functions
// If there is a function body, curly braces are needed:
constfibonacci=n=>{
if(n<2){
return1
}
else{
returnfibonacci(n-1)+fibonacci(n-2)
}
}
/* A shorter fibonacci function that uses the ternary operator:
<condition> ? <value_if_true> : <value_if_false>
*/
constfib=n=>
n<2?1
:fib(n-1)+fib(n-2)
return[fibonacci(7),fib(7)]
}
{
// The "spread" operator, ...
// The spread operator makes working with arrays more natural.
constleft=[1,2,3]
constright=[4,5,6]
constfoo=[...left,...right]// "the stuff from left, then the stuff from right"
// Note foo is a *new* array.
returnfoo
}
{
// The spread operator also applies to objects.
constthing_1={key1:'value1',key2:'value2'}
constthing_2={key3:'value3',key2:'value4'}
constbar={...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.
returnbar
}
{
// Object "destructuring"
constfoo={a:1,b:2,c:3}
const{a,b,c}=foo// foo gets "destructured"
returnc// now we can access foo's keys as variables
}
{
// You can also destructure the arguments to functions.
constobject_adder=({a,b})=>a+b
constbaz={a:3,b:9}
returnobject_adder(baz)
}
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.