JavaScript basics for React

JavaScript basics for React

  • "bare" / "blank" return statements (MDN docs)
  • destructuring assignment (MDN docs)
  • imports and exports
  • arrow functions
  • template strings

"Bare" / "blank" return statements

this will not work as intended in JavaScript:

return
  <div>foo</div>;

it would be interpreted as:

return;
<div>foo</div>;

(automatic semicolon insertion)

"Bare" / "blank" return statements

versions that work:

return <div>foo</div>;
return (
  <div>foo</div>
);

Destructuring assignment

assigning the contents of an object or array to multiple variables simultaneously

Destructuring assignment with objects

long version (without destructuring):

const protocol = window.location.protocol;
const host = window.location.host;
const pathname = window.location.pathname;

version with destructuring assignment:

const { protocol, host, pathname } = window.location;

Destructuring assignment with arrays

const [a, b, c] = [1, 2, 3];
const [result, logs] = someLongComputation();
// swapping values of a and b
[a, b] = [b, a];

Imports and exports

named exports:

const foo = 1;
function bar() {
  return 2;
}

export { foo, bar };

or

export const foo = 1;
export function bar() {
  return 2;
}

Imports and exports

named imports in another file:

import { foo, bar } from './mymodule.js';

when using a bundler like webpack:

import { foo, bar } from './mymodule';

Imports and exports

there may be one default export per module:

export default function Main() {
  return <div>Main</div>;
}

or

function Main() {
  return <div>Main</div>;
}

export default Main;

Imports and exports

imports (default and named):

import Main, { foo, bar } from 'mymodule.js';

the default can be imported under any name

Arrow functions

notation for anonymous functions:

const multiply = (a, b) => {
  return a * b;
};

short notation if the function only returns a single expression:

const multiply = (a, b) => a * b;

Template strings

template strings allow for interpolation (via ${})

are delimited by backticks (`)

const message = `Hello, ${name}!`;