Node.js Introduction

Node.js is a JavaScript runtime built on Chrome's V8 engine, allowing us to run JavaScript outside of a browser. It is commonly used for building server-side apps, including Server API's, but also CLI's and desktop apps using the Electron framework.

REPL

REPL stands for Read-Eval-Print-Loop. It's an environment where we interactively can type JavaScript code and then see the immediate result. This is great for quickly testing code snippets in a terminal, instead of running it in an IDE.


Javascript Fundamentals

Variables and Data Types

JavaScript has three ways of declaring a variable:

const Used for values that won't be reassigned. let Used for values that will change. var Not used anymore, avoid using at all costs.

We usually want to use const when assigning a variable, but there are times where this would cause unwanted functionality, such as:

for(const i = 0; i < 5, i++){
  console.log(i) // will print 0 once
}

But on the other hand, it is a bad habit of 'just' using let for everything out of habit, when most variables never actually get reassigned.

Some examples of using let, instead of const:

 let status = 'active';
 status = 'done'
 let total = 0;
 total += price;

Data Types

  1. String - Text value
  2. Number - Numeric values
  3. Boolean - True or False
  4. Object - Collection of key: value pairs
  5. BigInt - Very large integers
  6. Symbol - Unique identifier
  7. Null - Absence of value
  8. Undefined - Variable declared but not assigned

Type Coercion

JavaScript will automatically convert types when needed:

 const year = 2020;
 const increment = 1;
 const result = year + increment;
 // result = 20251 (String concatenation)

To avoid unexpected behavior, explicitly convert types:

 const numberYear = Number(year);
 const newYear = numberYear + increment;
 // newYear = 2026 (Number addition)

Strict Equality

Use === instead of == by default, unless you have a reason to check for type coercion:

 '5' == 5 // True
 '5' === 5 // False

Strings and Numbers

There are 3 ways of defining string in javascript:

  • Double quotes
  • Single quotes
  • Backticks (Template literals)

You can use double quotes inside a string of single quotes and vice versa. We strive to only use single quotes, to adhere to a standard within JavaScript.

Backticks allow us to use multi-line strings and string interpolation, which means we can pass variables into the string for dynamic use. It does allow for custom tag functions as well, but that has not been covered in this elective.

const firstName = "Svend"
const lastName = 'Støvring Storgaard'

const fullName = `My first name is ${firstName}
and my last name is ${lastName}`

String Methods

Replace word:

const fact = 'You are learning javascript!';
const capitalizedFact =
    fact.replace('javascript', 'JavaScript');

Accessing String Characters:

const letters = 'abc';
console.log(letters.charAt(2)); // 'c'
console.log(letters[2]);        // 'c'

Working with Numbers

Converting Strings to Numbers

// parseFloat - converts to decimal number
const numberOne = '1.10';
const numberTwo = '2.30';
const total = parseFloat(numberOne) +
    parseFloat(numberTwo);
// 3.4

// Number - general conversion
const anotherNumber = Number('42'); // 42

toFixed()

Format decimal places:

const anotherNumberOne = '1.123849';
const anotherNumberTwo = '2.30';
const sum = Number(anotherNumberOne) +
    Number(anotherNumberTwo);
console.log(sum.toFixed(2)); // '3.42'

Calculating Averages

const one = 10;
const two = 45;
const three = 98;
const avg = (one + two + three) / 3;
console.log(avg);

Arrays and Objects

Arrays

An ordered collection of values, accessed by index.

Creating arrays:

const letters = ['a', 'b', 'c'];
const friends = [];

Accessing arrays:

console.log(letters[1]); // 'b'

Adding elements:

const people = [];
people.push('Valdemar');
console.log(people); // ['Valdemar']

Array methods:

const significantMathNumbers =
    [0, 2.718, 3.14159, 1729];

// indexOf - find the position of a value
console.log(
    significantMathNumbers.indexOf(1729)
); // 3

// splice - insert or remove elements
const diet = ['tomato', 'cucumber', 'rocket'];
diet.splice(2, 0, 'hamburger', 'pizza', 'soda');
// ['tomato', 'cucumber', 'hamburger',
// 'pizza', 'soda', 'rocket']

// pop - remove last element
diet.pop();

// Array.from - copy an array
const dinnerTray = Array.from(diet);

Objects

Objects store data as key-value pairs. Just like you might see in JSON (JavaScript Object Notation), except that JSON requires quoted keys and can't use comments - which is the key difference between the two.

Creating an object:

const person = {
    name: 'Mathias'
};

Accessing properties:

const greetings = {
    message: 'Hello, earthling! I bring peace.'
};
console.log(greetings.message);

Modifying objects:

// Change existing property
person.name = 'Gustav';

// Add new property
person.age = 31;

// Add to empty object
const stackOverflow = {};
stackOverflow.isAllowed = true;

Removing properties:

const thisSong = {
    description: 'The best song in the world.'
};
delete thisSong.description;
thisSong.about = 'Just a tribute.';

Code Conventions

ASI (Automatic Semicolon Insertion)

JavaScript automatically inserts semicolons at the end of statements. However, it is considered best practice to include them explicitly to avoid unexpected behavior.

Best Practices:

  • We want to use const by default, let when reassignment is needed
  • Use template literals (backticks) for string interpolation
  • Use strict equality (===) instead of loose equality (==)
  • Use variable names that are meaningful and purpose minded
  • Include semicolons explicitly
  • Use proper indentation

Linter

Install ESLint or the Prettier extension and use this to format your code. It will ensure that your code is readable and therefore easily maintained and understandable for others.

ESLint

npm install -g eslint

Create a global config at ~/.eslintrc.json

{
  "extends": "eslint:recommended",
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  },
  "rules": {
    "semi": ["error", "always"],
    "quotes": ["error", "single"]
  }
}

Prettier

npm install -g prettier

Create a global config at ~/.prettierrc.json

{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5"
}

VS Code Integration

Add this JSON to settings.json:

{
  "eslint.enable": true,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "prettier.configPath": "~/.prettierrc"
}

Code Style Documentation


REST API Design

REST (Representational State Transfer) is an architectural style for designing networked applications. A REST API uses HTTP requests to perform operations on resources (resources = data).

Core Principles

HTTP Methods

Each HTTP method has a specific purpose:

  • GET - Retrieve data (Read)
  • POST - Create new data (Create)
  • PUT - Update/replace existing data (Update)
  • PATCH - Partially update existing data (Update)
  • DELETE - Remove data (Delete)

These methods map to CRUD operations:

  • Create → POST
  • Read → GET
  • Update → PUT/PATCH
  • Delete → DELETE

Method Ordering

When documenting or implementing REST APIs, methods should be presented in a standard order: GET, POST, PUT, PATCH, DELETE.

Endpoint Standardization

Endpoints should be:

  • Noun-based (not verb-based) - represent resources, not actions
  • Plural - use collection names (/beers not /beer)
  • Hierarchical - show relationships between resources
  • Consistent - follow the same patterns throughout your API

Example: Beer API

EndpointMethodDescription
/beersGETRetrieve all beer resources.
/beers/{id}GETRetrieve a beer resource by id.
/beersPOSTCreate a beer resource.
/beers/{id}PUTUpdate a beer resource.
/beers/{id}PATCHUpdate parts of a beer resource.
/beers/{id}DELETEDelete a beer resource.