<!DOCTYPE html>
at the beginning of each HTML file<link>
tags inside <head>
<head>
<link rel="stylesheet" href="./styles/app.css" />
</head>
<script>
tags right before the </body>
tag
<script src="./scripts/app.min.js"></script>
</body>
<meta>
tags (e.g.: for responsive layout, for character encoding, for Internet Explorer rendering engine usage):
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link>
tag and don't forget to add the <title>
inside <head>
:
<link rel="icon" href="favicon.ico">
<div>
s everywhere (try to use HTML5 elements and attributes where possible)
https://www.w3schools.com/html/html5_semantic_elements.asp
<div>, <p>, <h1>, <ul>, <section>
etc.) and inline elements <span>, <a>
etc.)class
attributes to elements, in order to use them in CSSid
s where needed for binding handlers to elements in JS and make sure the id
s are unique per pagedata-
attributes for storing relevant data on HTML elements</div>, </script>
) and which tags don't need to be closed (e.g.: <input>
).container
) wherever possible and avoid using IDs (e.g.: #myButton
) for stylinghttps://necolas.github.io/normalize.css/
) or 'reset.css' https://meyerweb.com/eric/tools/css/reset/
) as the first CSS in your project, in order to remove/adjust default browser styling that may affect the look and feel#submitButton
) and dashed-notation for classes (e.g.: .layer-wrapper
)
[100].wrapper .container button {
[101] background-color: #f00;
[102]}
..................................
[255].wrapper .container button {
[256] text-transform: uppercase;
[257]}
.container {
background-color: transparent;
background-image: url('../../images/pattern.png');
background-repeat: no-repeat;
background-position: 0 0;
background-size: 100% 100%;
}
use this:
.container {
background: url('../../images/pattern.png') no-repeat 0 0 / 100% 100% transparent;
}
body,
html {
width: 100%;
height: 100%;
overflow: hidden;
}
instead of:
body, html {
width: 100%;
height: 100%;
overflow: hidden;
}
z-index
assign it the smallest value that suits your needs: position: absolute;
position: relative;
position: fixed;
http://fontawesome.io/
, http://glyphicons.com/
):
.icon,
.icon.facebook {
width: 54px;
height: 54px;
background: url('social-icons.jpg') no-repeat 0 0 transparent;
}
.icon.twitter {
background-position: -80px 0;
}
(function(){
/*** Your code here...***/
})();//<- This paranthesis shows that the anonymous function is invoked right after it is read by the interpreter
===
/ !==
instead of simple equality / inequality ==
/ !=
:
var a = 1,
b = '1';
if(a == b) { //<- true
//do something
}
if(a === b) { //<- false
//do something else
}
/**
* Adds 2 numbers
* @param param1 Number
* @param param2 Number
* @returns Number
*/
function sum(param1, param2) {
if(typeof param1 !== 'number' && param2 !== 'number') {
throw new Error('Invalid parameters!');
}
return param1 + param2;
}
(function(){
'use strict';
a = 1;
})();//Throws a reference error: 'a is not defined!'
(function(){
a = 1;
})();//Adds 'a' to the Global namespace => window.a = 1;
//utils.js
function MathUtils () {
var add = function(param1, param2) {
if (typeof param1 !== 'number' && typeof param2 !== 'number') {
throw new Error('Cannot perform operation, invalid parameters!');
}
return param1 + param2;
},
power = function(base, exponent) {
if (typeof base !== 'number' && typeof exponent !== 'number') {
throw new Error('Cannot perform operation, invalid parameters!');
}
return Math.pow(base, exponent);
};
return {
add: add,
pow: power
};
}
//app.js
(function(){
'use strict';
console.log(new MathUtils().pow(2, 3)); //logs 8
})();
document.getElementById("submitButton").style.color = "red";
var foo = 1;
(function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
})();
var
s and function
names, and use verbs as function names (e.g. readFromInput()
)
$('section').on('click', function(e){
alert('Clicked on section!');
}
$('section').on('mouseover', function(e) {
alert('Mouse over section!');
}
you can do:
var section = $('section');
section.on('click', function(e){
alert('Clicked on section!');
}
section.on('mouseover', function(e) {
alert('Mouse over section!');
}
try{...}catch(){...}
, typeof
, check object instances using instanceof
etc.)let
and const
var link = function (height, color, url) {
var height = height || 50
var color = color || 'red'
var url = url || 'http://example.com'
...
}
Default Parameters (ES6):
var link = function(height = 50, color = 'red', url = 'http://example.com') {
...
}
var name = 'Your name is ' + first + ' ' + last + '.'
var url = 'http://localhost:3000/api/messages/' + id
Template Literals (ES6):
var name = `Your name is ${first} ${last}.`
var url = `http://localhost:3000/api/messages/${id}`
var roadPoem = 'Then took the other, as just as fair,\n\t'
+ 'And having perhaps the better claim\n\t'
+ 'Because it was grassy and wanted wear,\n\t'
+ 'Though as for that the passing there\n\t'
+ 'Had worn them really about the same,\n\t'
var fourAgreements = 'You have the right to be you.\n\
You can only be you when you do your best.'
var roadPoem = `Then took the other, as just as fair,
And having perhaps the better claim
Because it was grassy and wanted wear,
Though as for that the passing there
Had worn them really about the same,`
var fourAgreements = `You have the right to be you.
You can only be you when you do your best.`
var data = $('body').data(), // data has properties house and mouse
house = data.house,
mouse = data.mouse
var jsonMiddleware = require('body-parser').json
var body = req.body, // body has username and password
username = body.username,
password = body.password
var {house, mouse} = $('body').data() // we'll get house and mouse variables
var {json: jsonMiddleware} = require('body-parser')
var {username, password} = req.body
var [col1, col2] = $('.column'),
[line1, line2, line3, , line5] = file.split('\n')
var serviceBase = {port: 3000, url: 'example.com'},
getAccounts = function(){return [1,2,3]}
var accountServiceES5 = {
port: serviceBase.port,
url: serviceBase.url,
getAccounts: getAccounts,
toString: function() {
return JSON.stringify(this.valueOf())
},
getUrl: function() {return "http://" + this.url + ':' + this.port},
valueOf_1_2_3: getAccounts()
}
var getAccounts = function(){return [1,2,3]}
var accountService = {
getAccounts,
toString() {return JSON.stringify((super.valueOf()))},
getUrl() {return "http://" + this.url + ':' + this.port},
[ 'valueOf_' + getAccounts().join('_') ]: getAccounts()
}
this
:
ES5 handling of this
:
var self = this
$('.btn').click(function(event){
self.sendData()
})
With Arrow Functions:
$('.btn').click((event) =>{
this.sendData()
})
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map(function (value) {
return "ID is " + value // explicit return
})
With Arrow Functions and Template Literals:
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map(value => `ID is ${value}`) // implicit return
ES6 introduces a standard Promise implementation
Example of ES5 delayed executions withsetTimeout()
:
setTimeout(function(){
console.log('After 1 sec!');
setTimeout(function(){
console.log('After 2 sec!')
}, 1000)
}, 1000)
var wait1000 = ()=> new Promise((resolve, reject)=> {setTimeout(resolve, 1000)})
wait1000()
.then(function() {
console.log('Yay!')
return wait1000()
})
.then(function() {
console.log('Wheeyee!')
})
let
and const
Example of variable scoping using var
:
function calculateTotalAmount (vip) {
var amount = 0
if (vip) {
var amount = 1
}
{ // more blocks!
var amount = 100
{
var amount = 1000
}
}
return amount
}
console.log(calculateTotalAmount(true))
let
:
function calculateTotalAmount (vip) {
var amount = 0 // probably should also be let, but you can mix var and let
if (vip) {
let amount = 1 // first amount is still 0
}
{ // more blocks!
let amount = 100 // first amount is still 0
{
let amount = 1000 // first amount is still 0
}
}
return amount
}
console.log(calculateTotalAmount(true))
const
:
function calculateTotalAmount (vip) {
const amount = 0
if (vip) {
const amount = 1
}
{ // more blocks!
const amount = 100
{
const amount = 1000
}
}
return amount
}
console.log(calculateTotalAmount(true))
class BaseModel {
constructor(options = {}, data = []) { // class constructor
this.name = 'Base'
this.url = 'http://example.com/api'
this.data = data
this.options = options
}
getName() { // class method
console.log(`Class name: ${this.name}`)
}
}
class AccountModel extends BaseModel {
constructor(options, data) {
super({private: true}, ['32113123123', '524214691']) //call the parent method with super
this.name = 'Account Model'
this.url +='/accounts/'
}
get accountsData() { //calculated attribute getter
// ... make XHR
return this.data
}
}
let accounts = new AccountModel(5);
accounts.getName();
console.log('Data is: ', accounts.accountsData);
//module.js
module.exports = {
port: 3000,
getAccounts: function() {
...
}
}
//main.js
var service = require('module.js')
console.log(service.port) // 3000
//module.js
export var port = 3000
export function getAccounts(url) {
...
}
//main.js
import {port, getAccounts} from 'module'
console.log(port) // 3000
//or
import * as service from 'module'
console.log(service.port) // 3000
https://babeljs.io/