6. Data Types
Primitive Data Types
Number
Represents numeric values:
let integer = 42;
let float = 3.14;
let negative = -10;
let scientific = 1.23e5; // 123000
let infinity = Infinity;
let notANumber = NaN;
String
Represents text:
let singleQuotes = 'Hello';
let doubleQuotes = "World";
let templateLiteral = `Hello ${name}!`; // ES6+
let multiline = `Line 1
Line 2`;
Boolean
Represents true/false values:
let isTrue = true;
let isFalse = false;
let comparison = 5 > 3; // true
let equality = '5' == 5; // true (loose equality)
undefined
Represents uninitialized variables:
let uninitialized;
console.log(uninitialized); // undefined
null
Represents intentional absence of value:
let empty = null;
Symbol (ES6+)
Unique identifiers:
let sym1 = Symbol('description');
let sym2 = Symbol('description');
console.log(sym1 === sym2); // false
BigInt (ES11+)
For large integers:
let bigInt = 123456789012345678901234567890n;
let bigInt2 = BigInt('123456789012345678901234567890');
Reference Data Types
Object
Collections of key-value pairs:
let person = {
name: 'John',
age: 30,
isStudent: false
};
let emptyObject = {};
Array
Ordered collections:
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, 'hello', true, null];
let emptyArray = [];
Function
Callable objects:
function greet(name) {
return `Hello, ${name}!`;
}
let arrowFunction = (name) => `Hello, ${name}!`;
Type Checking
typeof Operator
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (quirk)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
console.log(typeof Symbol()); // "symbol"
console.log(typeof 42n); // "bigint"
instanceof Operator
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
let date = new Date();
console.log(date instanceof Date); // true
Type Conversion
Implicit Conversion (Type Coercion)
console.log(5 + "5"); // "55" (number to string)
console.log("5" - 2); // 3 (string to number)
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(0 == false); // true
console.log(0 === false); // false
Explicit Conversion
// To String
String(123); // "123"
(123).toString(); // "123"
123 + ""; // "123"
// To Number
Number("123"); // 123
parseInt("123px"); // 123
parseFloat("3.14"); // 3.14
+"42"; // 42
// To Boolean
Boolean(0); // false
Boolean(1); // true
Boolean(""); // false
Boolean("hello"); // true
!!0; // false
!!"hello"; // true
Truthy and Falsy Values
Falsy Values (evaluate to false)
false
0
-0
0n
""
null
undefined
NaN
Truthy Values (evaluate to true)
Everything else:
true
42
"hello"
[]
{}
function(){}
Next Steps
Understanding data types is fundamental. Next, let's explore operators that work with these types.