Datatypes in JS and relational databases
There are two principal differences between the way we model data in javascript and in a relational database.
Strict vs. weakly typed
In javascript the language determines the datatype at runtime. This means we can have code such as:
function Pizza(pizzaName, pizzaType, pizzaPrize, garlic) {
this.pizzaName = pizzaName;
this.pizzaType = pizzaType;
this.pizzaPrize = pizzaPrize;
this.garlic = garlic;
}
In the above example we do not specify that pizzaName
and pizzaType
are of type String
or that pizzaPrize
is of type Int
and garlic
of type boolean
.
If we were creating a table in a database we would have to specify the datatypes like this:
CREATE TABLE pizzas
(id INTEGER PRIMARY KEY,
pizzaName TEXT,
pizzaType TEXT,
pizzaPrize INTEGER,
garlic BOOLEAN);
Counting from zero or 1
In javascript the first object to be pushed onto the Array is number zero. So in a for
loop we would write the following - counting the loop from zero:
function displayAllPizzas(pizzas) {
let pizzaString = "";
let pizzaArraySize = pizzas.length;
for (i = 0; i < pizzaArraySize; i++) {
pizzaString += pizza.pizzaName + ", "
+ pizza.pizzaType + ", "
+ pizza.pizzaPrize + ", "
+ pizza.garlic + "<br/>";
}
return pizzaString;
}
In a database the first id
will normally be 1. So the first pizza in the table will be number 1.
Further reading: JavaScript Essentials: Types & Data Structures