A
These types include:
- String - a group of characters.
- Number - any combination of numbers.
- Boolean - returns true or false.
- null - intentional absence of an object value.
- undefined - a variable declared but not given a value (automatic).
- Symbol - this is a unique type generated by the Symbol() function.
const aString = "John Smith";
const aNumber = 2000;
const aBoolean = true;
const aNullType = null;
const anUndefinedType = undefined;
Let undefinedIsAutomatic; // All variables start out as "undefined"
typeOf aString : string
typeOf aNumber : number
typeOf aBoolean : boolen
typeOf aNullType : null
typeOf anUndefinedType : undefined
typeOf undefinedIsAutomatic : undefined
String
In JavaScript, the
const aString = "Hello World!";
aString.length // 12
aString.indexOf('o') //
4
aString.lastIndexOf('o') // 7
aString.toLowerCase() // "hello world!"
aString.toUpperCase() // "HELLO WORLD!"
aString.bold() // "<b>Hello World!</b>"
aString.replace('H', 'Z') // "Zello World!"
aString.replace('World', 'JavaScript') // "Hello JavaScript!"
Boolean
Common in computer science, a Boolean data type provides an "on/off" sort of data value, often in the form of true or false. In JavaScript, a common use-case would be to set up a conditional (meaning "if this happens, then do this") to decide if a group of code should run. It will then use a Boolean return of "true" to run or "false" not to run the code. Below are the results of creating a boolean with different types of data. Essentially, 0, an empty string, false, Nan, null and undefined register as false and any other value is true, including a string with the word "false".
var b1 = new Boolean(0); // false
var b2 = new Boolean(1); // true
var b3 = new Boolean(false); // false
var b4 = new Boolean(""); // false
var b5 = new Boolean("false"); // true
var b6 = new Boolean(NaN); // false
var b7 = new Boolean(null); // false
var b8 = new Boolean("Hello"); // true
var b9 = new Boolean(-0.1); // true
Null
const aNullType = null; // null
Undefined
const anUndefinedType = undefined; // undefined
let undefinedIsAutomatic; // undefined
Symbol
Symbol()
is used to create a completely unique type. This can be used to prevent conflicts, especially in an object with a large number of properties. In these cases Symbol() can be used to create custom identifiers ensuring they will be completely unique.
// without Symbol()
let sym1 = "foo";
let sym2 = "foo";
console.log(sym1 === sym2);RESULT: true;
// WIth Symbol()
let sym1 = Symbol('foo');
let sym2 = Symbol('foo');
console.log(sym1 === sym2); // RESULT: false;