JavaScript: reference

The language of the browser: functions, arrays, the DOM and server requests.

Basics

Output and comments

console.log prints a value to the browser console (F12).

console.log("Hello, world!");   // comment
console.log(2 + 3, "text", true);
/* multi-line
   comment */

Adding it to the page

A script with defer runs after the page has been parsed.

<script src="app.js" defer></script>

Variables and types

let, const

Use const by default and let only when the value changes. Better not to use the old var.

let count = 1;        // can be changed
const PI = 3.14;      // cannot be changed
count += 1;
console.log(typeof count, typeof "a", typeof true);

Value types

All numbers in JavaScript have the type number. An undefined variable has the value undefined.

let n = 42;          // number
let s = "text";     // string
let ok = true;       // boolean
let nothing = null;  // intentionally empty
let u;               // undefined
console.log(Number("12"), String(5), Boolean(0));

Operators

Comparison

Compare with === and !==: they do not convert types.

console.log(5 === 5, 5 === "5", 5 == "5");   // true false true
console.log(5 !== 6, 3 < 4, "a" < "b");
console.log(true && false, true || false, !true);

?? and ?.

?. safely reads nested fields, ?? substitutes a fallback value for null and undefined.

const city = user?.address?.city ?? "Unknown";

Strings

Methods and templates

Template strings in backticks insert values through ${...}.

const s = "JavaScript";
console.log(s.length, s[0], s.slice(0, 4), s.toUpperCase());
console.log(s.includes("Script"), s.split("a"));
const name = "Alex";
console.log(`Hello, ${name}! ${2 + 3}`);

Conditions

if, switch, ternary

Falsy values are false, 0, "", null, undefined and NaN; everything else is truthy.

if (age < 12) {
  console.log("child");
} else if (age < 18) {
  console.log("teenager");
} else {
  console.log("adult");
}
const kind = age >= 18 ? "adult" : "minor";

Loops

for, while, for...of

for...of goes through the values of an array, for...in goes through the keys of an object.

for (let i = 0; i < 3; i++) {
  console.log(i);
}
let n = 0;
while (n < 3) n++;
for (const x of [10, 20, 30]) {
  console.log(x);
}

Arrays

Main methods

The push and pop methods change the array, while slice returns a copy of a part.

const a = [3, 1, 2];
a.push(5);
console.log(a.length, a[0], a.includes(2));
console.log(a.slice(1, 3), a.indexOf(2));
a.sort((x, y) => x - y);

map, filter, reduce

These methods do not change the original array but return a new result.

const nums = [1, 2, 3, 4];
const doubled = nums.map((x) => x * 2);
const even = nums.filter((x) => x % 2 === 0);
const sum = nums.reduce((acc, x) => acc + x, 0);
const first = nums.find((x) => x > 2);

Objects

Creating and accessing

The ... operator spreads an array or an object, handy for copying.

const user = { name: "Alex", age: 16 };
user.city = "Dnipro";
console.log(user.name, user["age"]);
console.log(Object.keys(user), Object.entries(user));
const { name, age } = user;          // destructuring
const copy = { ...user, age: 17 };   // a copy with changes

Functions

Three ways to write it

Arrow functions are handy for short callbacks.

function add(a, b = 0) {
  return a + b;
}
const mul = function (a, b) { return a * b; };
const sq = (x) => x * x;
console.log(add(2, 3), mul(2, 3), sq(4));

Closures

An inner function remembers the variables that were around when it was created.

function counter() {
  let n = 0;
  return () => ++n;
}
const next = counter();
console.log(next(), next());   // 1 2

DOM

Finding and changing elements

textContent is safer than innerHTML when the text contains data from the user.

const title = document.querySelector("h1");
title.textContent = "New heading";
title.classList.add("active");
const items = document.querySelectorAll(".item");
items.forEach((el) => el.setAttribute("hidden", ""));

Events

addEventListener subscribes a function to an event. Typical events: click, input, submit, keydown.

const btn = document.querySelector("#btn");
btn.addEventListener("click", (e) => {
  console.log("Click!", e.target);
});
form.addEventListener("submit", (e) => e.preventDefault());

Asynchronous code

Promise and async/await

await waits for the result without blocking the page. Errors are caught with try/catch.

async function load() {
  try {
    const res = await fetch("/api/items");
    if (!res.ok) throw new Error("Error " + res.status);
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err.message);
  }
}
setTimeout(() => console.log("after a second"), 1000);

Modules and JSON

import / export

Scripts with import are included through <script type="module">.

// math.js
export const add = (a, b) => a + b;
export default function hello() {}

// app.js
import hello, { add } from "./math.js";

JSON and storage

localStorage stores only strings, so objects are converted through JSON.

const text = JSON.stringify({ a: 1 });
const obj = JSON.parse(text);
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));

Learn JavaScript with practice

Want to learn step by step? Your account has 110 lessons organised by chapter (80 core and 30 advanced, you can switch the level at any time) and tasks with code checking.