View on GitHub

JS-Cheatsheet

JavaScript Cheatsheet for Modern JS, ES6 and useful Resources

JS Cheat Sheet

Summary of code snippets arround modern JS, ES6, etc., as well as a couple of interesting resource links.

Overview

Misc

JavaScript Versions

Resources

References, useful and interesting links.

Resources

Interesting Links

ES6 Basics

Introduction

To make sure your audience can use the code you still might want to use Babel to transpile your modern JS. Make sure to check your sites features with Can I use and the ES6 Compat Table

Use Strict

Was actually part of ES5, to tell the browser to run in strict mode. It is always block scoped, declared of the beginning of a file it has a global scope. But it always needs to be declared at the beginning of a block / function / file.

'use strict';
...

Let vs. Var vs. Const

var x; // Good old vars
const x; // Can not be changed
let x; // Block scoped, not accessible before assigning, can't get redeclared in scope

Arrow Functions

// ES6
var eq = (para, parb) => para == parb;

// Old Vanilla JS
var eq = function(para, parb){
	return para == parb;
}

Immediatly Invoked Arrow Function need to be put in brackets

(() => {
  console.log('Do it now!');
})()

Blocks

To replace immediatly invoked functions. See also immediatly invoked arrow functions.

{
	let internal = "";
};
console.log(internal); // Will crash

Default Parameter

function f (x, y = 7, z = 42) {
    return x + y + z
}

String Interpolation

ES6 String Interpolation / Template Literals Browser Support

const name = "Peter";
var helloMessage = `Hello ${name},
I hope you are doing good?
Warm Regards`;

Shorthand Properties

Set an object without having to define property names

var a = 'Hello';
var b = 'World';
// ES6 can do
var c = {a,b};
// which gets the same result as
var c = {a: a, b: b};

So we can also…

let f = () => {
  var a = 1;
  var b = 2;
  return {a, b};
};

var {a,b} = f();

Another sample of function in an object

var funcinator = {
	stateOfTheArt(instead, of){

	},
	theOldWay: function(you, know){

	}
};

Dynamic Generated Property Names

var propertyNameSuffix = "test";
var dynProp = {
		["my-new" + propertyNameSuffix](){
	}
};

Maps

Usage of a JS Hashmap

let m = new Map();
m.set("Hell", "World");
console.log(m.get("Hell"));

Classes

ES6 Classes Browser Support Currently it is not possible to have private variables in a class.

Sample

class CheatSheet{
	constructor(lang, text){
		this.lang = lang; // Declare Public Variable
		this.text = text;
	}
	print(){
		console.log(`# ${this.lang}
			${this.text}`);
	}
	changeLanguage(l){
		this.lang = l;
	}
}

class PetersCheatSheet extends CheatSheet{

}
var myCS = new PetersCheatSheet("JavaScript", "Here will be some text for JS");
myCS.print();

Modules

CommonJS Modules

CommonJS Modules are supported in Node.JS by default, but can also be used by using RequireJS, Browserify or other Tools

// foobar.js
function foobar(){
        this.bar = function(){
                console.log('Hello bar');
        }
}
// Expose variables / public variables
exports.foobar = foobar;
//main.js
var foobar = require('./foobar').foobar,
    myfoobar   = new foobar();
 
myfoobar.bar(); // 'Hello bar'

ES6 Modules

Was designed with influence of CommonJS and AMD modules.
Check out the full working sample

// Lib.js
class Lib {
	increase(n) {
		console.log(n);
        return ++n;
    }
}
export default Lib;
// main.js
import Lib from './Lib.js';
var lib = new Lib();
lib.increase(99);

Or as an alternative you could also

// foobar.js
export bar = function(){
	console.log('Hello bar');
}
// main.js
import * as foobar from 'foobar';
foobar.bar();

To Include a ES6 Module in your HTML-File use

<script src="index.js" type="module"></script>

Promises

ES6 Promise pattern, so there is no need anymore to use q, but be aware of no IE11 support To have browser support for IE11 and older browsers make sure to polyfill Promises

function logAsync(text) {
    return new Promise(
        function (resolve, reject) {

            setTimeout(function(){
              console.log(text)
              resolve();              
            }, 100);
            //reject("error");
        });
}

logAsync("Log me async")
.then(result => { console.log("Here we go")})
.catch(error => { console.log("Something didn't work") });

Analytics