A Designer's Guide to JavaScript

You can learn the basics of JavaScript quickly. You don't need a engineering degree, or a front end bootcamp.

Learning the basics of JavaScript is enough to get started with modern frameworks like React.js. Once you know the basics, you can do some truly amazing things.

You can quickly spin up interactive prototypes.
You can use live data sets.
You can create web, mobile, and desktop apps.
You can define interfaces in high fidelity.
You can write scripts to automate daily tasks.
You can make plugins for design tools like Sketch and Figma.
You can build with modern frameworks like React.js.

You can't learn JavaScript in a day, but you can learn it quickly. The best way to learn is to build. This guide is meant to give you enough information to start building.

Editor

Before we write any code, it's a good idea to get comfortable with your text editor. I'd recommend using a text editor like VSCode, or Atom as you write JavaScript. They're both free and support lots of plugins to make things easier. You can also find lots of nice themes. Here's a theme for VSCode that I like.

Learning keyboard shortcuts, and customizing the look of your editor will make for a much more enjoyable coding experience.

Setup

JavaScript is a scripting language that for our intents and purposes, will be executed by the browser.

There are multiple ways to include javascript inside your webpage. The way we will use javascript will be by including <script> tags right before the closing </body> tag.

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    
    <script>
        // Javascript will go here
        console.log("Hello friend!")
    </script>
  </body>
</html>

We’ll put our javascript inside here, but we could also reference an external file. console.log() is a helpful tool for debugging. Here I'm writing "Hello Friend!" To the console. You an access the console in Chrome using the CMD+Option+J shortcut.

There are 5 core concepts in JavaScript that are important to understand.

1. Variables
2. Data Structures
3. Loops
4. Conditionals
5. Functions

Variables

Variables are containers that hold values. These values can take lots of different forms. If you wanted a variable to hold a number you could write it as var num = 20;. If I use console.log(num) it should show me the number twenty.

Variables can be referenced later. var double = num * 2; // 40

Variables can hold lots of different data types. I want to discuss a few different common ways to hold data. There are primitive data types like numbers, which we used earlier, There are strings, which are just a way to store text, and booleans which are values that are either true or false.

var days = 40; // Number
var label = "Hello"; // String
var hidden = true; // Boolean

Data Structures

In addition to primitive data types there are others that have more complex structures. Two of these important types are objects (sometimes called object literals) and arrays.

Objects can be defined using curly braces. var obj = {}

What goes inside the curly braces are a collection of key value pairs. The key goes first, followed by a colon, and then the value.

var obj = {
  key: value
}

Keys are labels that help you find the data you want to store. Keys in a single object must be unique. Values can be any data type. Numbers, strings, arrays, and even other objects. Here's an example Object with multiple key value pairs in action:

var profile = {
	name: 'Philip', 
	age: 25, 
	contact: {
		twitter: 'philipcdavis', 
		email: 'reactfordesigners@gmail.com'
	}
}

Name, age, contact, twitter, and email are all different keys in this object. The values are all different and many have different value types. Some are strings, some are numbers, and some are other objects.

This nested structure is common and you will see it a lot when working with data sets.

There are two ways to access a value inside an object. The first way is sometimes called dot notation: profile.name. The second way is by using brackets profile['name']. Bracket notion is useful when your key name is dynamic.

The other data type that’s important to know about is the Array. You define an array with square brackets.

var myArr = [];

You can store any type of data inside these arrays and they don't need to all be the same type (though they usually are). An example array might look like this:

var teams = ['lakers', 'nuggets', 'rockets'];

Instead of using keys, arrays use a built in index to keep track of location. The index of arrays starts at 0. If we wanted to access the second value of this array (nuggets) we could do so by typing teams[1];

If your data was as simple as this, using objects and arrays might seem unnecessary. They start to shine when you have data sets that are larger. To work with more data, we'll probably want to use a loop

Loops

Loops enable you to run a block of code multiple times. You can use a loop with objects and arrays to execute a block of code on each item in the structure.

To loop through each value in an array you can use a for loop that executes a block.

for (var i=0; i<teams.length; i++) {
    // Block to be executed
}

What goes into the parenthesis determines how many times the block of code is executed. The first value is a counter variable. i is often used to refer to the fact that it's used as the index value of the array. We will start the counter at 0.

The next value is called the conditional. Once the conditional is false, the loop will end. We can set the value to be i < teams.length. The .length is a helper value built into every array that will tell you how many items are in the array. Once the value of the counter is as great as the length of the array, we can stop looping. The last value i++ is what we want to happen after our loop runs. We want our counter to increase in value by one every time the loop runs.

If we log a string, you can see that it will print out 4 times. If we log the value i, you can see that it increments up. If you combine this incremented value i with our array, you can see how we can access each value in our array.

for (var i=0;i<teams.length;i++) { 
	console.log(teams[i])
};

There are other types of loops but they all are doing something pretty similar, running a block of code multiple times. That’s the essential work of a loop.

Conditionals

Next up on our list is conditionals. The most common type of conditional is the if/else statement.

if (conditional) {
	console.log('the conditional evaluated to true');
} else {
  console.log('the conditional evaluated to false');
}

If the conditional value in the parenthesis evaluates to true, the block inside the first set of curly brackets is run, otherwise the else block is run.

Let’s use it in combination with our loop to log only the first two items in our array. Because we don’t need the else here, we can remove it, and we’ll get the same result.

for (var i = 0; i<teams.length; i++) {
	if (i < 2) {
	  console.log(teams[i]);
	}
}

You’ll use these conditionals to to control what gets executed when.

Functions

Functions allow you to create reusable and modular code.

Another way to say it is that they are blocks of code than can be executed whenever they are needed.

Here's what one looks like

function add (a, b) {
	var total = a + b;
	return total;
} 

Here we have a simple function that takes two input values, adds them together, and then returns the total. We’ll use generic names for our input arguments. You can name these pretty much whatever you want, but they will be used within our block so if your function is complex, it’s good to have descriptive names. Because this is a pretty simple function we're using a and b.

What we've created is a function declaration. In order to execute, or invoke our function we can call add(2,50). console.log(add(2,50)) // 52

console.log is itself a function. Functions can be stored in variables, objects, arrays, or even passed into other functions.

One other important thing to note about functions is how they affect variables inside them. If you define a variable within a function, the variable cannot be used outside the function. That's because javascript has a function based scope.


Javascript is a really fun language to learn. If you feel comfortable with the material above you can do a lot! Most of JavaScript is just building on to these core concepts.

Modern JavaScript

In 2015 a set of new syntax and features were introduced that made writing JavaScript easier. Many of the following updates are meant to help you write code faster and cleaner. If you're using modern frameworks like React you'll often see them in examples.

Const / Let

This is just a new way to write variables.

const height = 30;
let height = 30;

const values cannot be reassigned after the initial assignment. This is usually the default way of creating variables.

let values can be reassigned but are scoped to conditionals, the same way all variables are scoped to functions. If you declare one inside an if/else statement it won't be available outside the statement.

Arrow Functions

This a shorthand for writing functions. Instead of writing:

const add = function(a,b){ return a + b }

You can use an arrow function which looks like this:

const add = (a,b) => a + b

If your function takes a single parameter you can omit the parenthesis.

const getStyle = a => a.style

Template Literals

Previously is you wanted dynamic strings, you would insert values using the following syntax.

const dynamicString = "Hello my name is" + firstName + ". Welcome!"

Using template literals, you can use the backtick for strings, and ${} to insert variables.

const dynamicString = `Hello my name is ${firstName}. Welcome!`

Imports and Exports

Instead of using large javascript files, you'll often want to break your code into smaller modules and export anything that other modules need to access.

// Colors.js
export const colors = {
	blue: "#EA3232",
	red: "#4062F3",
	yellow: "#FFAD05",
}

In a different file you can import these colors using the following syntax.

import {colors} from './Color'

You can also define default exports using the default keyword.

export default Button

This is useful when you are only exporting one function or variable from your file.

If you export using the default keyword you can import without using the curly braces.

import Button from './Button'

Many libraries will allow you to import a default value as well as other values. Here's an example from the styled-components library.

import styled, {keyframes, css} from 'styled-components'

Destructuring

The syntax for accessing values inside of arrays and objects also got a few upgrades. Previously if you wanted to use values in an array as variables it would look like this.

// Old method
const coordinates = [394.39827, 389.2834];
const x = coordinates[0];
const y = coordinates[1];

Destructing was added as a cleaner way to do this. Here's what it looks like for an array, which gets you the same two x and y variables.

// Destructuring
const coordinates = [394.39827, 389.2834];
const [x,y] = coordinates;

Objects work similar. You can use the same syntax with curly brackets instead of the square ones.

const user = {name:"Philip Davis", twitter: "@philipcdavis"}
const {name, twitter} = user;

Argument Defaults

Functions can now take argument defaults, which allow you to set values when arguments aren't passed in.

const welcome = (name, location="Not Set") => { ... };

Here I'm setting the default location set to "Not Set". These can be very useful for empty states.

const youGotThis = true;

JavaScript is an amazing language, and it can open up so many doors for designers. It's one of the reason I created React for Design. If you have questions about JavaScript, or just want some guidance as you get started please reach out.


A React Course for Designers

React is a powerful design tool. If you're interested in using React for design work I made a course for you.
React for Design