This is an accelerated introduction to modern JavaScript.
- Read every snippet.
- Click the document linked in the snippet's header.
- Once you are familiar with the concept being demonstrated, move on to the next snippet.
JavaScript is the most popular programming language in the world. The language has some unusual design choices and pitfalls, many of which owe to the fact that it was originally designed in 10 days by one person and used by a very young, naïve Internet. It will be a lot easier to understand JavaScript if you have basic familiarity with C-like programming languages, id est C++, C#, or Java.
This training is purposefully dense. JS is a quirky language, and it is better to take the time to learn. JavaScript gets seriously easier to write and debug in modern versions. I cannot overstate how much better the language has gotten in the last five years.
Free free to look information up on DevDocs and MDN.
1 REPL
console.log(`hello world`);
a = 'a'
const b = 'b'
let c = 'c'
var a // just don't
3 Types
typeof true
typeof 3.14
typeof `wake me up`
typeof [] // less obvious
function doNothing1() {}
const doNothing2 = function () {}
const doNothing3 = () => {}
const dev = {name: 'alex'}
if (dev) `has non-zero value`
const text = dev.name ? `has name` : `missing name`
const dev = {name: 'alex'}
const name = dev && dev.name // null safety
const text = name || 'unnamed dev' // null coalescing
0 === `0`
0 == `0` // just don't
const dev = {name: 'alex'}
const text = `they are named ${dev.name}`
9 Promises
Promise.resolve(`hey`)
.then(msg => console.log(msg))
.catch(err => console.error(err))
10 Prototypes
function Foo() {}
const foo = new Foo()
foo instanceof Foo
const messageElement = document.getElementById('message')
messageElement.innerText = 'Hello world, from JS!'
// numbers.js
export const ONE = 1
export const TWO = 2
// index.js
import {ONE, TWO} from './number.js'
console.log(ONE + TWO)
// numbers.js
const Numbers = {ONE: 1, TWO: 2}
// index.js
console.log(Numbers.ONE + Numbers.TWO)
Press F12
.
// numbers.js
exports.ONE = 1
exports.TWO = 2
// index.js
const {ONE, TWO} = require('./number.js')
console.log(ONE + TWO)
$ npm i -D babel-cli
$ npm i -g typescript
$ npx babel src/example.js -o dist/example.js
$ npx tsc
Disclaimer: "how" to write JavaScript is always going to be an opinion, and I haven't been in the business very long. Take this advice with a grain of salt and skepticism.
- Write functional code
- Use arrow functions
- Write what you mean
- Don't type-check yourself
- Use tools to check types
If you need to work with old JS.