The Basics

JavaScript is an interpreted language running in all major browsers and servers through Node.js. JavaScript was created in 1995 by Brendan Eich, with the first version produced in ten days to accommodate a release of Netscape Navigator 2.0. Brendan initially aimed to bring the scheme language to the browser but was tasked by his overlords with creating a language resembling Java’s syntax.

Using JavaScript, you can build sophisticated single-page web applications with frameworks like React.js and Angular. It also creates APIs that run on a server.

Primary Use Cases

  • Building web and mobile applications
  • Creating backend APIs, including REST and GraphQL, among others
  • Creating games

Less Suitable Use Cases

  • Data science, use Python instead
  • Multithreading, JavaScript doesn’t have this feature

Node Package Manager

Most JavaScript developers use the Node Package Manager ( NPM ) to start a new project. Once NPM is installed, you can easily manage dependencies and create self-contained modules.

To get started with NPM, a node version manager like nvm is recommended. Once nvm is installed, you can start using the latest stable version of nodejs.

# Run these commands to create a new project
mkdir myproject
cd ./myproject
npm init # Follow the prompts; using defaults is fine the package.json file can be edited later.

By now, you should have a new project you can use to begin learning.

Fundamentals

Learning the fundamentals of any language is a path to success.

Variables

I’m not pointing; you’re pointing!

const color = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

console.log(
  `${color.BOLD_UNDERLINE}Assign a string value to a variable${color.END}`,
);
console.log();
const office_name1 = "Office A";
console.log(office_name1);
console.log();
console.log("----------------------------------------------");
console.log();

console.log(
  `${color.BOLD_UNDERLINE}Assign a multiple line string value to a variable${color.END}`,
);
console.log();
const office_name2 = `Office A\n
Office B
`;
console.log(office_name2);
console.log("----------------------------------------------");
console.log();

console.log(
  `${color.BOLD_UNDERLINE}Assign an integer value to a variable${color.END}`,
);
console.log();
const office_sales = 7;
const office_sales_type = typeof office_sales;
console.log(`office_sales is a lucky ${office_sales_type} ${office_sales}`);
console.log();
console.log("----------------------------------------------");
console.log();

console.log(
  `${color.BOLD_UNDERLINE}Assign an boolean value to a variable${color.END}`,
);
console.log();
office_is_active = true;
office_is_active_type = typeof office_is_active;
console.log(`office_score is a ${office_is_active_type} ${office_is_active}`);
console.log();
console.log("----------------------------------------------");
console.log();

Comments

I like purposeful comments.

// A simple single-line comment
console.log("There's a comment before this line, trust me.");
/*
A
Comment
on multiple lines
*/
console.log();
console.log("A few comments just happened, honest!");
console.log();

/**
 * Represents a book.
 * @constructor
 */
function Book(title, author) {}
console.log("Look at the code to see what a JSDoc comment looks like.");
console.log("What is JSDoc? https://jsdoc.app/about-getting-started.html");

Control Structures

Oh, mighty ECMAScript, many thanks for your ample bounty of flow.

const colors = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

/*
The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.
*/
console.log(`${colors.BOLD_UNDERLINE}An if statement.${colors.END}`);
console.log();
if (true) {
  console.log("Since true is true this line prints.");
}
console.log();
console.log("-----------------------");
console.log(`${colors.BOLD_UNDERLINE}An if else statement.${colors.END}`);
console.log();
if (false) {
  // I won't do anything, I refuse!
} else {
  console.log("Since false is false this line prints.");
}
console.log();
console.log("-----------------------");

/*
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
*/
console.log(`${colors.BOLD_UNDERLINE}A standard for loop.${colors.END}`);
console.log();

offices = ["Office A", "Office B", "Office C"];

for (var i = 0; i < offices.length; i++) {
  console.log(`${offices[i]}\n`);
}
console.log();
console.log("-----------------------");
/*

The purpose of the for-in statement is to enumerate over object properties. The for in statement reads up the prototype chain and enumerates over inherited properties.

*/
console.log(
  `${colors.BOLD_UNDERLINE}Use for in to loop over the properties of the color object.${colors.END}`,
);
console.log();
console.log();
for (color in colors) {
  console.log(`${color}\n`);
}
console.log();
/*
The purpose of the forEach function is to
enumerate the elements of an array. Using a forEach
function prevents out of bounds errors that can occur when using a for loop with an index. If you need to break from your loop avoid the use of forEach.
*/
console.log("-----------------------");
console.log(
  `${colors.BOLD_UNDERLINE}Create an orderly bounded and scoped loop with the .forEach function.${colors.END}`,
);
console.log();
console.log();
const numbers1 = [1, 2, 3, 4, 5];

let txt = "";
numbers1.forEach(myFunction);

function myFunction(value, index, array) {
  console.log((txt += value));
}

console.log();
/*
The for of statement is used for looping over
iterable objects like arrays, maps, sets, Etc.
*/
console.log("-----------------------");
console.log(
  `${colors.BOLD_UNDERLINE}Create an orderly loop with the for of statement.${colors.END}`,
);

const numbers2 = [1, 2, 3, 4, 5];
console.log();

for (let value of numbers2) {
  console.log(value);
}

/*
A while statement executes its statements as long as a specified condition evaluates to true.
*/
console.log("-----------------------");
console.log(
  `${colors.BOLD_UNDERLINE}Create a while loop that loops until a condition if met.${colors.END}`,
);
console.log();
i = 0;
while (i < 5) {
  i++;
  console.log(i);
}
console.log("-----------------------");

/*
The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false.

The only difference between do while and a while loop is that at least one execution will occur since the evaluation executes after enclosed statement(s).
*/
console.log("-----------------------");
console.log(
  `${colors.BOLD_UNDERLINE}Create a do while loop that loops until a condition is met.${colors.END}`,
);
console.log();
i = 0;
do {
  i++;
  console.log(i);
} while (i < 5);

Functions

If you don’t love functions, you won’t love JavaScript.

const color = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

console.log(
  `${color.BOLD_UNDERLINE}Create a function then execute it.${color.END}`,
);
console.log();
function myFunction() {
  console.log("Executed myFunction");
}
myFunction();

console.log("----------------------------------------------");
console.log();
console.log(
  `${color.BOLD_UNDERLINE}Create an arrow function then execute it.${color.END}`,
);
console.log();
myArrowFunction = () => {
  console.log("Executed myArrowFunction");
};
myArrowFunction();
console.log();
console.log("----------------------------------------------");
console.log();
console.log(
  `${color.BOLD_UNDERLINE}Create a function as an expression then execute it.${color.END}`,
);
console.log();
const myExpressionFunction = function () {
  console.log("Executed myExpressionFunction");
};
myExpressionFunction();
console.log();
console.log("----------------------------------------------");
console.log();
console.log(
  `${color.BOLD_UNDERLINE}Create a function with the Function constructor then execute it.${color.END}`,
);
console.log();
const myFunctionConstructorFunction = Function(
  'console.log("Executed myFunctionConstructorFunction")',
);
myFunctionConstructorFunction();
console.log();
console.log("----------------------------------------------");
console.log();

Prototypes and Objects

All the cool kidz think objects are satan spawn. I lean heavily towards pragmatism and use the right tool for the job.

Use at your own risk if you’re worried about being at the mercy of the cool kidz.

const color = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

/*

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics

An object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects.) Let's work through an example to understand what they look like.

*/
console.log(
  `${color.BOLD_UNDERLINE}Create a new JavaScript object.${color.END}`,
);
console.log();
const officeObject = {
  name: "officeObject",
};
console.log(officeObject);
console.log();
console.log(
  `${color.BOLD_UNDERLINE}Access the value of officeObject.name.${color.END}`,
);
console.log();
console.log(officeObject.name);
console.log("------------------------------");
console.log();
/*

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes

Prototypes enable object inheritance in JavaScript

JavaScript is often described as a prototype-based language — to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from.

*/
console.log(
  `${color.BOLD_UNDERLINE}Create constructor function, instantiate it, then call a method on it.${color.END}`,
);
console.log();
function OfficeConstructorFunction(name) {
  this.name = name;
}

OfficeConstructorFunction.prototype.open = function () {
  console.log(this.name + " has opened for business!");
};

const officeConstructorFunction = new OfficeConstructorFunction(
  "officeConstructorFunction",
);
console.log(officeConstructorFunction);
console.log(officeConstructorFunction.open());
console.log("------------------------------");
/*
ECMAScript 2015 Classes have simplified the
classic prototype syntax. Use this syntax to make your code easier to read.
*/
console.log(
  `${color.BOLD_UNDERLINE}Create a class, instantiate it, then call a method on it.${color.END}`,
);
console.log();
class OfficeECMA2015Class {
  constructor(name) {
    this.name = name;
  }

  open() {
    console.log(`${this.name} has opened for business!`);
  }
}

const officeECMA2015Class = new OfficeECMA2015Class("officeECMA2015Class");
console.log(officeECMA2015Class);
officeECMA2015Class.open();
console.log("------------------------------");

Exception Handling

I wonder if Brendan Eich took exception to Netscape’s scheme to make it look like Java. 💭

const fs = require("fs");

const color = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

console.log(
  `${color.BOLD_UNDERLINE}Try to read an existing file and finally make it!${color.END}`,
);

const read_file = (fileName) => {
  let fileContents;
  try {
    fileContents = fs.readFileSync(fileName, "utf8");
  } catch (err) {
    if (err.code === "ENOENT") {
      console.log(`Missing file: ${fileName}`);
    } else {
      throw err;
    }
  } finally {
    console.log();
    console.log("I finally made it!");
  }
  return fileContents;
};

console.log();
const fileContents = read_file("example.csv");
console.log();
console.log("fileContents:", fileContents);
console.log("-----------------------");
console.log();

console.log(
  `${color.BOLD_UNDERLINE}Read a non-existent file and catch the exception.${color.END}`,
);
console.log();

read_file("missing_file.csv");
console.log("-----------------------");

Arrays

I like Order it’s so much better than Chaos.

const color = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

console.log(`${color.BOLD_UNDERLINE}Create an office array.${color.END}`);
console.log();

const offices = ["Office A", "Office B", "Office C"];

console.log(`We have an office array: ${offices}`);
console.log();
console.log(`Accessing array item 0`);
office0 = offices;
console.log();
console.log(`Found ${office0}`);
console.log();

console.log("Update an array value");
console.log();
offices = "Office Z";
console.log(`Updated Office A to ${offices}`);
console.log();

console.log("Get the length of the array");
console.log();
offices_length = offices.length;
console.log(`${offices_length} offices exist in the array`);
console.log();

console.log("Loop a sorted array");
console.log();
for (office of offices.sort()) {
  console.log(office);
}
console.log();

console.log("Add an array element named Office Y");
offices.push("Office Y");
console.log(offices);
console.log();

console.log("Remove the first element of an array");
offices.splice(0, 1);
console.log(offices);
console.log();

Operators

I like to operate, not on a table. 🤡

const color = {
  END: "\033[0m",
  BOLD_UNDERLINE: "\033[1m\033[4m",
};

console.log(`${color.BOLD_UNDERLINE}Arithmetic Operators${color.END}`);
console.log();
const addition = 1 + 1;
console.log(`1 + 1 = ${addition}`);
console.log();

const subtraction = 2 - 1;
console.log(`2 - 1 = ${subtraction}`);
console.log();

const multiplication = 3 * 3;
console.log(`3 * 3 = ${multiplication}`);
console.log();

const exponentiation = 2 ** 3;
console.log(`2 ** 3 = ${exponentiation}`);
console.log();

const division = 10 / 5;
console.log(`10 / 5 = ${division}`);
console.log();

const modulus = 6 % 3;
console.log(`6 % 3 = ${modulus}`);
console.log();

let increment = 1;
increment++;
console.log(`1++ = ${increment}`);
console.log();

let decrement = 1;
decrement++;
console.log(`1++ = ${decrement}`);
console.log();

console.log(`${color.BOLD_UNDERLINE}Assignment Operators${color.END}`);
console.log();

let equals = 1;
console.log(`1 = ${equals}`);
console.log();

equals += 1;
console.log(`1 += ${equals}`);
console.log();

let minus_equals = 2;
minus_equals -= 1;
console.log(`2 -= ${minus_equals}`);
console.log();

let multiply_and = 5;
multiply_and *= 5;
console.log(`5 *= ${multiply_and}`);
console.log();

let divide_and = 5;
divide_and /= 5;
console.log(`5 /= ${divide_and}`);
console.log();

let modulus_and = 6;
modulus_and %= 3;
console.log(`6 %= ${modulus_and}`);
console.log();

exponent_and = 2;
exponent_and *= 3;
console.log(`2 *= ${exponent_and}`);
console.log();

exponent_assign = 2;
exponent_assign **= 3;
console.log(`2 **= ${exponent_assign}`);
console.log();

There are many other constructs to learn in JavaScript.

Learn JavaScript - Beyond the Basics


Other Learning