In JS, the type is dynamic and defined at compilation, based on the value assigned to the variable.
You can therefore assign a value of any type to a variable.
You can also change the type of the variable depending on the value assigned.
You can also declare a variable without assigning a value, and define it later.
Variable Types
Number
We have "special numeric values"
- Infinity
- -Infinity
- NaN -> comes from an invalid mathematical operation
!!! It's important to know that math is 'safe' in JS; you can't crash the script. The worst-case scenario is that the result is 'NaN'.
This also means you have to pay attention to what you're doing, because the code won't warn you!
Also, numbers in JS are almost limitless; you can go up to 2^53 - 1.
But at this point, you lose precision and can have calculation errors!
Then the actual real limit is 1.7976931348623157 * 10^308
according to MDN documentation.
If you happen to exceed the limit, you can add 'n' to the end of the number to make it 'bigint'.
const bigInt = 1234567890123456789012345678901234567890n; // this is a 'bigint'
const bigInt2 = 1234567890123456789012345678901234567890; // this is a 'number'
String
Several ways to have strings
let string1 = 'Hello World'; // string in single quotes
let string2 = "Hello World"; // string in double quotes
let string3 = `Hello World and we can insert variables ${string1}`; // string in backticks + variable interpolation
Boolean
true or false
const boolean1 = true;
const boolean2 = false;
Null
null is an object that represents a null value.
It's the default value when it doesn't exist! (no initialization, or a key of an object that doesn't exist for example)
Undefined
undefined is an object that represents an undefined value.
It's the default value of all uninitialized variables.
Object
We'll see this later!
Function
function function3 () {
console.log('Hello World');
}
// or we can put a function in a variable
const function1 = function() {
console.log('Hello World');
};
// or put an arrow function in a variable
const function2 = () => {
console.log('Hello World');
};
Examples of variables
let variable1 = 'Hello World';
const variable2 = 'Hello World';
var variable3 = 'Hello World';
let variable4 = {};
let variable5 = [];
let variable6 = function() {};
let variable7 = () => {};
let variable8 = 1;
let variable9;