REST API with Express.js
JavaScript

Traditionally JavaScript has been used only in the frontend, so the code was loaded to the browser and executed there. But in the late-2000s Node.js was created and that made possible to use it also in the backend.

This is not a JavaScript tutorial, so I will introduce only those things which are the most relevant in order to be able to understand the REST API examples.

To make REST API with JavaScript, you need to learn how to use Node.js and here is one tutorial for that https://www.w3schools.com/nodejs/default.asp.

Variables: var, let, const

JavaScript provides three ways to declare variables: var, let, and const. They differ in terms of scope, reassignment rules, and usage.

var
  • An older way to declare variables (before ES6).
  • Has function scope: it is visible throughout the function, but does not respect block boundaries (e.g., if, for).
  • Allows variable redeclaration within the same scope.
var x = 10;
if (true) {
    var x = 20; // Same variable!
    console.log(x); // Outputs 20
}
console.log(x); // Outputs 20
let
  • A modern way to declare variables (introduced in ES6).
  • Has block scope: visible only within the block where it is declared.
  • Does not allow variable redeclaration within the same block.
let y = 10;
if (true) {
    let y = 20; // Different variable!
    console.log(y); // Outputs 20
}
console.log(y); // Outputs 10
const
  • A modern way to declare constants (introduced in ES6).
  • Has block scope, similar to let.
  • Does not allow variable reassignment.
  • However, objects and arrays can still be modified.
const z = 10;
z = 20; // Error: constants cannot be reassigned!

const arr = [1, 2, 3];
arr.push(4); // Allowed, modifying the contents
console.log(arr); // Outputs [1, 2, 3, 4]
Comparison: var vs let vs const

Here is a quick comparison of the three declaration types:

Feature var let const
Scope Function scope Block scope Block scope
Reassignment ✓ Allowed ✓ Allowed ✗ Not allowed
Redeclaration ✓ Allowed ✗ Not allowed ✗ Not allowed
Hoisting Yes (initialized as undefined) Yes (not initialized - temporal dead zone) Yes (not initialized - temporal dead zone)
When to use Avoid in modern code When value needs to change Default choice (use when possible)

Best Practice: In modern JavaScript, use const by default. Only use let when you know the variable value will need to be reassigned. Avoid using var in new code.

Associative array

If you know how to handle associative arrays, you can easily handle the data which you will get from the database.

Associative array is an array where the fields have names. Here is an example of that

const bookData=[
    {'name' :"C++", 'author' :"Jim Smith"},
    {'name' :"Java", 'author' :"Lisa Jones"},
    {'name' :"MySQL", 'author' :"Bob Daniels"}
];
You can print all books from the array like this
console.log(bookData);
And you can print the first row from the array like this
console.log(bookData[0]);

Objects

Here is an example about using objects in JavaScript

//person is an object
const person={
    fname:'Teppo',
    lname:'Testi',
    showData: function(){
        console.log(this.fname+ " "+this.lname);
    }
};
//calling the showData method of the person object 
person.showData();
And another example where the object includes associative array
const person={
    personData:[
        {'fn' :"Jim", 'ln' :"Smith"},
        {'fn' :"Lisa", 'ln' :"Smith"},
        {'fn' :"Ann", 'ln' :"Jones"},
    ],
    showData: function(){
        console.log(this.personData);
    },
    insertData: function(addFn, addLn){
        this.personData.push({fn:addFn, ln:addLn});
    }
};

person.insertData('Teppo','Testi');
person.showData();

Callbacks

A callback is a function that is passed as an argument to another function, which then executes it at an appropriate time. This pattern is not unique to JavaScript - it exists in many programming languages like Python, C++, Java, and others.

Callbacks are used in several scenarios:

  • Asynchronous operations - handling tasks that take time (file I/O, network requests, timers)
  • Event handling - responding to user actions (clicks, keyboard input)
  • Higher-order functions - operations on collections (filtering, mapping, sorting)
  • Custom behavior - allowing code to be extended or customized
Simple callback example

Here is a simple example showing how callbacks work with array operations:

const numbers = [1, 2, 3, 4, 5];

// The function 'double' is passed as a callback to 'map'
function double(num) {
    return num * 2;
}

const doubled = numbers.map(double);
console.log(doubled); // [2, 4, 6, 8, 10]
In this example, the double function is a callback that gets executed for each element in the array.

Asynchronous callback example

Callbacks are especially important for asynchronous operations - tasks that don't complete immediately. Here is an example that demonstrates asynchronous callbacks:

setTimeout(doSomething,2000);

function doSomething(){
    console.log("Demonstrating the callbacks");
}
console.log("The application is started");
The setTimeout function takes two parameters: a callback function (doSomething) and a delay in milliseconds. The callback will be executed after the specified delay.

Because setTimeout is asynchronous, it doesn't block the execution of subsequent code. The program continues immediately to the next line, which is why "The application is started" appears in the console before "Demonstrating the callbacks", even though the setTimeout call appears first in the code.

Callback & Asynchronous Execution

Click "Run Code" to see execution flow
JavaScript Code:
1 setTimeout(doSomething, 2000);
2
3 function doSomething() {
4   console.log("Demonstrating the callbacks");
5 }
6 console.log("The application is started");
Console Output:
0s
2s
Time: 0.0s
Key Concepts:
  • Callback: The function doSomething is passed as an argument to setTimeout
  • Asynchronous: setTimeout doesn't block execution - code continues immediately
  • Execution Order: Line 6 runs before line 4, even though line 1 comes first!
Anonymous functions

An anonymous function is a function without a name. These are commonly used when you need a function only once, typically as a callback.

Instead of defining a separate named function, you can write the function directly as an argument:

// Anonymous function as callback
setTimeout(function(){
    console.log("Demonstrating the callbacks");
}, 2000);

console.log("The application is started");

When to use anonymous functions:

  • When the function is used only once and doesn't need to be reused
  • As event handlers or callbacks
  • To keep code concise and avoid polluting the namespace with function names

Here are more examples:

// Array operations
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(function(n) {
    return n * n;
}); // [1, 4, 9, 16, 25]

// Event listener
button.addEventListener('click', function() {
    console.log('Button clicked!');
});

Arrow functions

Arrow functions (introduced in ES6) provide a shorter syntax for writing functions. They use the => syntax and are commonly used for callbacks and short function expressions.

Note: In this material, all examples use traditional function syntax for clarity and readability. Arrow functions are presented here as additional information for those who want to learn the modern syntax used in many JavaScript projects.

Click the buttons below to see different aspects of arrow functions:

Beyond Callbacks: Promises and Async/Await

While callbacks are fundamental to JavaScript, they can lead to complex, nested code structures often referred to as "callback hell" when dealing with multiple asynchronous operations. Modern JavaScript offers cleaner alternatives: Promises and async/await.

Note: This material focuses on callback-based examples for clarity. Promises and async/await are presented here as additional information to help you understand modern JavaScript patterns you'll encounter in real-world projects.

Click the buttons below to learn about modern alternatives to callbacks:

Here is a short article about callbacks https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/



Toggle Menu