In JavaScript, every value is either an object or a primitive value. A value is only a primitive when it is not an object.
Note
JavaScript is dynamically typed, so we do not need to manually define the data type stored in a variable; this is done automatically.
Note
In JavaScript, the value has a type, not the variable
Primitive Data Types
- String → defined with single or double quotes or backticks (for use as f-string)
- Numbers → as in Python (note that all numbers are floating point numbers)
- Boolean →
true/false - null →
null - undefined →
undefined - Symbol (not very common)
- BigInt → Larger integers that
numbercannot hold (likesmallInt,int, andbigintin SQL)
We can test types with `console.log(typeof
const name = "John"
console.log(typeof name);-> string
console.log(typeof 30.5); -> number
console.log(typeof null); -> "object"
console.log(typeof undefined);-> undefinedInfo
typeof nullreturns “object” due to an early implementation of JavaScript, wherein objects had tags and values, and null was given a value of 0
Strings
String concatenation can be used by operator overloading or with template literals. The latter is like Python f-strings, except that it requires the use of back-ticks (`) when writing the string.
// Operator overloading
const name = "John";
const age = 30;
console.log("My name is " + name + " and I am " + age);// Template String (like Python f-string)
console.log(`My name is ${name} and I am ${age}`)We can also use template literals to create multi-line strings. Without the template literals we can to use the /n character plus a termination \ for each line:
console.log("String with \n\
multiple \n\
lines")With a template literal we can do:
console.log(`String with
multiple
lines`)Note
The use of backticks for template literals is mandatory. However, it is also possible to default to always using backticks for all strings.
Arrays
Arrays are much like Python lists. We initialize an array either via a constructor, or by using Python list-like syntax:
const numbers = new Array(1,2,3,4,5);
console.log(numbers);
const fruits = ["apples", "bananas", "oranges"]
console.log(fruits[1]); // Prints "bananas"
fruits[3] = "grapes";
fruits.push("mangoes") // Adds value to end of array
fruits.unshift("lemons") // Adds value to beginning of array
fruits.pop() // Remove last item
fruits.indexOf("bananas")Note
In the example above I used
constto declare thefruitsarray. I then modified the array, whichconstallows us to do. We just can’t re-declare it.