JavaScript by Example

JavaScript (JS) is a programming language and core technology of the Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.

JavaScript by Example is a hands-on introduction to JavaScript. Check out the first example or browse the full list below.

Unless stated otherwise, examples here assume the latest major release of Javacript and may use new language features.

Hello World

In JavaScript, `console.log` can be used to print anything to the console in a browser, or a terminal when running in a server-side environment like Node JS.

console.log("Hello, world!");

Comments

In JavaScript, comments can span a single or multiple lines.

Use "//" to create a single-line comments and "/* ... */" to create a multi-line comment

// Single line comment

/*
    This comment
    is on
    multiple lines
*/

Variables

There are two ways to create variables in modern JavaScript.

`let` is creates a normal variable, one for which the value can change at any time.

`const` is used when creating a varaible for which the value will never change.

let foo = "foo";

const bar = "bar";

Data Types

JavaScript has eight data types:

String A text of characters enclosed in quotes.

Number A number representing a mathematical value.

Bigint A number representing a large integer.

Boolean A data type representing true or false.

Object A collection of key-value pairs of data.

Undefined A primitive variable with no assigned value.

Null A primitive value representing object absence.

Symbol A unique and primitive identifier.

// Strings
let color = "Yellow";

// Number
let length = 16;
let weight = 7.5;

// BigInt
let i = 1234567890123456789012345n;
let j = BigInt(1234567890123456789012345);

// Boolean
let t = true;
let f = false;

// Object
const person = { firstName:"John", lastName:"Doe" };

// Array object
const cars = ["Ford", "Toyota", "BMW"];

// Date object
const date = new Date("2022-03-25");

// Undefined
let x;

// Null
let x = null;

// Symbol
const x = Symbol();

If / Else

An if / else statement in JavaScript.

let name = "John";

if (name === "John") {
  console.log("The user's name is John!");
} else {
  console.log("The user's name is NOT John...");
}

Switch

A switch statement in JavaScript.

It is good practice to include a "default" case in ensure unexpected behavior is always handled.

let plan = "pro";

switch(plan) {
  case "plus":
    consol.log("Plus plan");
    break;
  case "pro":
    consol.log("Pro plan");
    break;
  case "team":
    consol.log("Team plan");
    break;
  default:
    consol.log("Free plan");
}

For Loops

A for loop statement in JavaScript.

for (let i = 0; i < 5; i++) {
  console.log("i: ", i);
}

Functions

A function in JavaScript.

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}

let value = toCelsius(77);

Operators

Arithmetic operators:

+ Addition

- Subtraction

* Multiplication

** Exponentiation

/ Division

% Modulus (division with remainder)

++ Increment

-- Decrement

console.log("Addition: ", 1 + 1);

console.log("Subtraction: ", 2 - 1);

console.log("Multiplication: ", 2 * 2);

console.log("Exponentiation: ", 2 ** 2);

console.log("Division: ", 4 / 2);

console.log("Modulus: ", 10 % 3);

console.log("Increment: ", 1++);

console.log("Decrement: ", 1--);

Numbers

JavaScript has only one type of number.

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

// A number with decimals
let x = 3.14;

// A number without decimals
let y = 3;

Dates & Time

Creating a new date object in JavaScript is done by creating a new instance of "Date".

Note that JavaScript counts months from 0 to 11 where January is 0 and December is 11.

All dates are stored as milliseconds since January 1st, 1970.

// year, month, day, hours, minutes, seconds, milliseconds
const date = new Date(2018, 11, 24, 10, 33, 30, 0);

Regular expressions

Regular expressions (commonly referrex to as RegEx) in JavaScript help performing a few action against strings.

RegEx are used for:

Searching text

Replacing text

Validating text

// Searching text
let text = "JavaScript by Example";
let n = text.search(/JavaScript/);

// Matching text
let text = "JavaScript by Example";
let result = text.replace(/JavaScript/i, "JS");

// Replacing text
let text = "JavaScript by Example";
let n = text.match(/JavaScript/);

Arrays

Arrays in JavaScript are special objects design for storing ordered data.

Elements: An array is a list of values, known as elements.

Ordered : Array elements are ordered based on their index.

Zero indexed: The first element is at index 0, the second at index 1, and so on.

Dynamic size: Arrays can grow or shrink as elements are added or removed.

Heterogeneous: Arrays can store elements of different data types (numbers, strings, objects and other arrays).

const cars = ["Ford", "Toyota", "BMW"];

Objects

Objects in JavaScript are mechanisms for storing data using key/value pairs.

const person = {
    firstName: "John",
    lastName: "Doe",
    age: "26",
};

Sets

A JavaScript Set is similar to an array, however the values must be unique.

// Correct
const letters = new Set(["a","b","c"]);

// Wrong
const letters = new Set(["a","b","b"]);

Classes

Classes are templates for JavaScript Objects.

class User {
  constructor(username, password, email) {
    this.username = username;
    this.password = email;
  }
}

const userOne = new User("johndoe123", "john@example.com", "password123");

Promises

Promises in JavaScript allow for asynchronous code to be executed and handled when the response is sent to the caller.

Additionally, promises allow for handling when an error is thrown within the promise, and when the promise has completed its execution.

myPromise.then(() => {
    console.log("Promise was successful");
}).catch(() => {
    console.log("Promise was unsuccessful");
}).finally(() => {
    console.log("Promise completed");
});

Async / Await

Async / await makes promises easier to write.

The "await" keyword acts as the "then" keyword as results in the result of promise being stored in the variable.

let value = await promise;

Error handling

Instead of needing to use the key words "then", "catch", and "finally", we now have a single key word "await" which we place in a try / catch block.

try {
    let value = await promise;
    console.log("value: ", value);
} catch (error) {
    console.log("error: ", error);
}