13 Noteworthy Points from Google’s JavaScript Style Guide

For anyone who isn’t already familiar with it, Google puts out a style guide for writing JavaScript that lays out (what Google believes to be) the best stylistic practices for writing clean, understandable code.

Google’s JavaScript Style Guide
Google’s JavaScript Style Guide

These are not hard and fast rules for writing valid JavaScript, only proscriptions for maintaining consistent and appealing style choices throughout your source files. This is particularly interesting for JavaScript, which is a flexible and forgiving language that allows for a wide variety of stylistic choices.

Google and Airbnb have two of the most popular style guides out there. I’d definitely recommend you check out both of them if you spend much time writing JS.

The following are thirteen of what I think are the most interesting and relevant rules from Google’s JS Style Guide.

They deal with everything from hotly contested issues (tabs versus spaces, and the controversial issue of how semicolons should be used), to a few more obscure specifications which surprised me. They will definitely change the way I write my JS going forward.

For each rule, I’ll give a summary of the specification, followed by a supporting quote from the style guide that describes the rule in detail. Where applicable, I’ll also provide an example of the style in practice, and contrast it with code that does not follow the rule.

Use spaces, not tabs
Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that… Tab characters are not used for indentation.
The guide later specifies you should use two spaces (not four) for indentation.

// bad
function foo() {
∙∙∙∙let name;
}

// bad
function bar() {
∙let name;
}

// good
function baz() {
∙∙let name;
}
Semicolons ARE required
Every statement must be terminated with a semicolon. Relying on automatic semicolon insertion is forbidden.
Although I can’t imagine why anyone is opposed to this idea, the consistent use of semicolons in JS is becoming the new ‘spaces versus tabs’ debate. Google’s coming out firmly here in the defence of the semicolon.

// bad
let luke = {}
let leia = {}
[luke, leia].forEach(jedi => jedi.father = ‘vader’)
// good
let luke = {};
let leia = {};
[luke, leia].forEach((jedi) => {
jedi.father = ‘vader’;
});
Don’t use ES6 modules (yet)
Do not use ES6 modules yet (i.e. the export and import keywords), as their semantics are not yet finalized. Note that this policy will be revisited once the semantics are fully-standard.
// Don’t do this kind of thing yet:
//—— lib.js ——
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}

//—— main.js ——
import { square, diag } from ‘lib’;
Horizontal alignment is discouraged (but not forbidden)
This practice is permitted, but it is generally discouraged by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.
Horizontal alignment is the practice of adding a variable number of additional spaces in your code, to make certain tokens appear directly below certain other tokens on previous lines.

// bad
{
tiny: 42,
longer: 435,
};
// good
{
tiny: 42,
longer: 435,
};
Don’t use var anymore
Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used.
I still see people using var in code samples on StackOverflow and elsewhere. I can’t tell if there are people out there who will make a case for it, or if it’s just a case of old habits dying hard.

// bad
var example = 42;
// good
let example = 42;
Arrow functions are preferred
Arrow functions provide a concise syntax and fix a number of difficulties with this. Prefer arrow functions over the function keyword, particularly for nested functions
I’ll be honest, I just thought that arrow functions were great because they were more concise and nicer to look at. Turns out they also serve a pretty important purpose.

// bad
[1, 2, 3].map(function (x) {
const y = x + 1;
return x * y;
});

// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
Use template strings instead of concatenation
Use template strings (delimited with `) over complex string concatenation, particularly if multiple string literals are involved. Template strings may span multiple lines.
// bad
function sayHi(name) {
return ‘How are you, ‘ + name + ‘?’;
}

// bad
function sayHi(name) {
return [‘How are you, ‘, name, ‘?’].join();
}

// bad
function sayHi(name) {
return `How are you, ${ name }?`;
}

// good
function sayHi(name) {
return `How are you, ${name}?`;
}
Don’t use line continuations for long strings
Do not use line continuations (that is, ending a line inside a string literal with a backslash) in either ordinary or template string literals. Even though ES5 allows this, it can lead to tricky errors if any trailing whitespace comes after the slash, and is less obvious to readers.
Interestingly enough, this is a rule that Google and Airbnb disagree on (here’s Airbnb’s spec).

While Google recommends concatenating longer strings (as shown below) Airbnb’s style guide recommends essentially doing nothing, and allowing long strings to go on as long as they need to.

// bad (sorry, this doesn’t show up well on mobile)
const longString = ‘This is a very long string that \
far exceeds the 80 column limit. It unfortunately \
contains long stretches of spaces due to how the \
continued lines are indented.’;
// good
const longString = ‘This is a very long string that ‘ +
‘far exceeds the 80 column limit. It does not contain ‘ +
‘long stretches of spaces since the concatenated ‘ +
‘strings are cleaner.’;
“for… of” is the preferred type of ‘for loop’
With ES6, the language now has three different kinds of for loops. All may be used, though for-of loops should be preferred when possible.
This is a strange one if you ask me, but I thought I’d include it because it is pretty interesting that Google declares a preferred type of for loop.

I was always under the impression that for… in loops were better for objects, while for… of were better suited to arrays. A ‘right tool for the right job’ type situation.

While Google’s specification here doesn’t necessarily contradict that idea, it is still interesting to know they have a preference for this loop in particular.

Don’t use eval()
Do not use eval or the Function(…string) constructor (except for code loaders). These features are potentially dangerous and simply do not work in CSP environments.
The MDN page for eval() even has a section called “Don’t use eval!”

// bad
let obj = { a: 20, b: 30 };
let propName = getPropName(); // returns “a” or “b”
eval( ‘var result = obj.’ + propName );
// good
let obj = { a: 20, b: 30 };
let propName = getPropName(); // returns “a” or “b”
let result = obj[ propName ]; // obj[ “a” ] is the same as obj.a
Constants should be named in ALL_UPPERCASE separated by underscores
Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores.
If you’re absolutely sure that a variable shouldn’t change, you can indicate this by capitalizing the name of the constant. This makes the constant’s immutability obvious as it gets used throughout your code.

A notable exception to this rule is if the constant is function-scoped. In this case it should be written in camelCase.

// bad
const number = 5;
// good
const NUMBER = 5;
One variable per declaration
Every local variable declaration declares only one variable: declarations such as let a = 1, b = 2; are not used.
// bad
let a = 1, b = 2, c = 3;
// good
let a = 1;
let b = 2;
let c = 3;
Use single quotes, not double quotes
Ordinary string literals are delimited with single quotes (‘), rather than double quotes (“).
Tip: if a string contains a single quote character, consider using a template string to avoid having to escape the quote.
// bad
let directive = “No identification of self or mission.”
// bad
let saying = ‘Say it ain\u0027t so.’;
// good
let directive = ‘No identification of self or mission.’;
// good
let saying = `Say it ain’t so`;
A final note
As I said in the beginning, these are not mandates. Google is just one of many tech giants, and these are just recommendations.

That said, it is interesting to look at the style recommendations that are put out by a company like Google, which employs a lot of brilliant people who spend a lot of time writing excellent code.

You can follow these rules if you want to follow the guidelines for ‘Google compliant source code’ — but, of course, plenty of people disagree, and you’re free to brush any or all of this off.

I personally think there are plenty of cases where Airbnb’s spec is more appealing than Google’s. No matter the stance you take on these particular rules, it is still important to keep stylistic consistency in mind when write any sort of code.

Advertisements

Brilliant User Interface Animations

Animated interface elements reveal the process and functionality of a UI much better than static text. They enhance user experience and help guide user flow. Like any other element of good design, UI animations should have a purpose. They should be functional without being overly flashy.

 Note  If you’re on a slow connection, give a few seconds for the GIFs to load.

1. Menu open / tick / close

Menu open / tick / close
By Kreativa Studio

2. Download / save

Download / save
By Warren Lebovics

3. Play / pause

Play / pause
By Kreativa Studio

4. Search bar

Search bar
By Sandeep Virk

5. Menu open / close

Menu open / close
By Thanks But No Thanks

6. Responsive icons

Responsive icons
By Joe Harrison

7. Sound on / off

Sound on / off
By Kreativa Studio

8. Sending mail

Sending mail
By Tamas Kojo

9. Menu open / close

Menu open / close
By Creativedash

10. Favourite

Favourite
By Brian Waddington

11. Recording Audio

Recording Audio
By Ryan McLaughlin

12. Cloud download / done

Cloud download / done
By Brandon Termini

13. Menu open / close

Menu open / close
By Tamas Kojo

14. Responsive design

Responsive design
By Karol Podleśny

15. New Message

New Message
By Davor Moucka

16. Pull down / refresh

Pull down / refresh
By Hoang Nguyen

17. Menu open / close

Menu open / close
By Kenny Sing

18. Refresh

Refresh
By Sandeep Virk

19. Save

Save
By Justin Nurse

20. Search / back

Search / back
By Rahul Bhosale

21. Menu / more / close / back

Menu / more / close / back
By Alex Kirhenstein | Draward

22. Back / close

Back / close
By Sandeep Virk

23. Upload / complete

Upload / complete
By Colin Garven

24. Attaching file

Attaching file
By Roman Bulah

25. Dotted menu open / close

Dotted menu open / close
By Warren Lebovics

26. Message sent

Message sent
By Mike DiLuigi

27. New mail

New mail
By Dominik Levitsky

28. Shortlist

Shortlist
By Rahul Bhosale

29. Menu open / close

Menu open / close
By Homeliuwei

30. Music app intro animations

Music app intro animations
By Sergey Valiukh

31. Search / loading

Search / loading
By Sandeep Virk

32. Radial menu

Radial menu
By Howard Moen

33. EatStreet loading animation

EatStreet loading animation
By Jeremy Martinez

34. Firefox logo

Firefox logo
By Latham Arnott

35. In-app animations

In-app animations
By Sergey Valiukh

36. Weather icons

Weather icons
By Mark Geyer

SEE MORE …

Our favourites: no. 7, 18 and 32. What about you? Share this post with a fellow designer and voice your views in the comments below.

REM Calculator!

/*global jQuery */
(function( $ ) {
var result = $(‘#result’);
var base = $(‘#base’);
var list = $(‘#list’);
$(‘#calc’).click(function() {
var baseVal = base.val();
var px = list.val().split(‘,’);
var html = [];
$.each(px, function(i, v) {
var px = parseInt(v);
var rem = parseFloat((px / parseInt(baseVal, 10)).toPrecision(4));
var isBase = (rem === 1) ? ‘ <i>(base)</i>’ : ”;
html.push(‘<li>’ + v + ‘px = ‘ + rem + ‘rem’ + isBase + ‘</li>’);
});
result.html(html.join(”));
}).click();
}(jQuery));

 

REM Calculator!

What’s the difference between UX and UI design?

Let’s start!

First off, let’s answer the question: What exactly are UI design and UX design, and what is the difference between the two?

UXUI

Simply put, UI is how things look, UX is how things work. UX is a process, while UI is a deliverable. Let’s elaborate further…

User Interface Design

UI is a combination of content (documents, texts, images, videos, etc), form (buttons, labels, text fields, check boxes, drop-down lists, graphic design, etc), and behavior (what happens if I click/drag/type).

It takes a good eye, a lot of practice, and a lot of trial and error to get better at it. As a UI designer, your goal is to create a user interface that is engaging, beautiful, and also creates an emotional response from the user to make your products more lovable and beautiful.

 

User Experience Design

User Experience (UX) design is about creating pain-free and enjoyable experiences.

Here are 7 questions to ask yourself to know if the UX of your product is good:

  • Usability
  • User Profiling
  • Asking for permissions
  • Form vs Function
  • Consistency
  • Simplicity
  • Don’t make me think

“Design is not just what it looks like and feels like. Design is how it works”
-Steve Jobs

Good to great UI animation tips

Let’s see some examples of UI animations going from good to great. With a little bit of tweaking here and there, you can elevate your UI patterns with animation.uianimation

The interactions listed show continuity between states, denote a relationship between shared elements, and call the user’s attention to something they should notice and act upon.

 

UI animation tips

Brilliant Slider Animations For UI Inspiration

Sliders are the most commonly-used UI element, after buttons. From lock screens and image galleries to volume controls and app selections, we use sliders to navigate our way through different interfaces everyday. An effectively implemented slider enhances the user experience and makes the interface more engaging, dynamic, and memorable.

 Note  If you’re on a slow connection, give a few seconds for the GIFs to load.

1.

Slider Animation Inspiration - 1
By Gal Shir

 

2.

Slider Animation Inspiration - 2
By Matthew Kissick

 

3.

Slider Animation Inspiration - 3
By Saptarshi Prakash

 

4.

Slider Animation Inspiration - 4
By Saptarshi Prakash

 

5.

Slider Animation Inspiration - 5
By KREATIVA Studio

 

6.

Slider Animation Inspiration - 6
By Tylko

 

7.

Slider Animation Inspiration - 7
By Nick Buturishvili

 

8.

Slider Animation Inspiration - 8
By Alex Pronsky

 

9.

Slider Animation Inspiration - 9
By UI8

 

10.

Slider Animation Inspiration - 10
By Karol Ortyl

 

11.

Slider Animation Inspiration - 11
By KREATIVA Studio

 

12.

Slider Animation Inspiration - 12
By KREATIVA Studio

 

13.

Slider Animation Inspiration - 13
By Yury Smirnov

 

14.

Slider Animation Inspiration - 14
By Benjamin den Boer

 

15.

Slider Animation Inspiration - 15
By Johny vino™

 

16.

Slider Animation Inspiration - 16
By Budi Tanrim

 

17.

Slider Animation Inspiration - 17
By Logan Cee

 

18.

Slider Animation Inspiration - 18
By Stan Yakusevich

 

19.

Slider Animation Inspiration - 19
By Yaroslav Zubko

 

20.

Slider Animation Inspiration - 20
By Floris van der Harst

 

21.

Slider Animation Inspiration - 21
By Nikonov Dmitry

 

22.

Slider Animation Inspiration - 22
By Jurre Houtkamp

 

23.

Slider Animation Inspiration - 23
By Divan Raj

 

24.

Slider Animation Inspiration - 24
By Aurélien Salomon

 

25.

Slider Animation Inspiration - 25
By Andrew J Lee

 

26.

Slider Animation Inspiration - 26
By Olga Mikhailenko

 

27.

Slider Animation Inspiration - 27
By Cynthia_yue

 

28.

Slider Animation Inspiration - 28
By pixbugius

 

29.

Slider Animation Inspiration - 29
By k3nnyart

 

Why Google’s “Smart Reply” Is So Annoying

smartgoogle

 

I opened my Gmail account this morning and my emails started writing themselves. As I typed just a few words the next words appeared before I even thought of them. The screen told me I could hit tab and there they would be, like graven type, ready to send. That they weren’t the right words at all didn’t seem to matter — it was mind-reading magic! Shitty, annoying magic. I turned off Google’s auto-suggestions as soon as I could. (Apparently some people have had this feature for a while, but the plague just hit my inbox.)

“Smart Reply”

Blog at WordPress.com.

Up ↑