javascript
examples
examples.js⚡javascript
/**
* ============================================
* 2.2 Data Types - Examples
* ============================================
*
* Examples of all JavaScript data types
*/
// ============================================
// NUMBER TYPE
// ============================================
console.log('=== NUMBER TYPE ===\n');
// Different ways to create numbers
let integer = 42;
let negative = -17;
let decimal = 3.14159;
let scientific = 5e6; // 5,000,000
let binary = 0b1010; // 10 in decimal
let octal = 0o755; // 493 in decimal
let hex = 0xff; // 255 in decimal
console.log('Integer:', integer);
console.log('Decimal:', decimal);
console.log('Scientific:', scientific);
console.log('Binary 0b1010:', binary);
console.log('Octal 0o755:', octal);
console.log('Hex 0xFF:', hex);
// Special values
console.log('\nSpecial Number Values:');
console.log('1 / 0 =', 1 / 0); // Infinity
console.log('-1 / 0 =', -1 / 0); // -Infinity
console.log("'hello' * 2 =", 'hello' * 2); // NaN
// NaN peculiarities
console.log('\nNaN behavior:');
console.log('NaN === NaN:', NaN === NaN); // false!
console.log('isNaN(NaN):', isNaN(NaN));
console.log('Number.isNaN(NaN):', Number.isNaN(NaN));
console.log("Number.isNaN('hello'):", Number.isNaN('hello')); // false
// Precision issues
console.log('\nPrecision:');
console.log('0.1 + 0.2 =', 0.1 + 0.2);
console.log('0.1 + 0.2 === 0.3:', 0.1 + 0.2 === 0.3);
console.log('MAX_SAFE_INTEGER:', Number.MAX_SAFE_INTEGER);
// Number methods
console.log('\nNumber Methods:');
console.log("Number('42'):", Number('42'));
console.log("parseInt('42px'):", parseInt('42px'));
console.log("parseFloat('3.14abc'):", parseFloat('3.14abc'));
console.log('(3.14159).toFixed(2):', (3.14159).toFixed(2));
// ============================================
// STRING TYPE
// ============================================
console.log('\n=== STRING TYPE ===\n');
// Creating strings
let singleQuote = 'Hello';
let doubleQuote = 'World';
let templateLiteral = `Hello World`;
console.log('Single quote:', singleQuote);
console.log('Double quote:', doubleQuote);
console.log('Template literal:', templateLiteral);
// Template literal features
let name = 'Alice';
let age = 25;
let greeting = `My name is ${name} and I am ${age} years old.`;
console.log('\nInterpolation:', greeting);
let multiLine = `Line 1
Line 2
Line 3`;
console.log('\nMulti-line string:\n', multiLine);
// String methods
let str = 'Hello, World!';
console.log('\nString methods on:', str);
console.log('length:', str.length);
console.log('toUpperCase():', str.toUpperCase());
console.log('toLowerCase():', str.toLowerCase());
console.log("indexOf('World'):", str.indexOf('World'));
console.log("includes('World'):", str.includes('World'));
console.log('slice(0, 5):', str.slice(0, 5));
console.log("split(', '):", str.split(', '));
console.log("replace('World', 'JS'):", str.replace('World', 'JS'));
// Escape sequences
console.log('\nEscape sequences:');
console.log('Tab:\tafter tab');
console.log('Newline:\nafter newline');
console.log('Quote: "quoted"');
// String immutability
let immutable = 'Hello';
immutable[0] = 'Y'; // Doesn't work
console.log('\nAfter trying to change first char:', immutable); // "Hello"
// ============================================
// BOOLEAN TYPE
// ============================================
console.log('\n=== BOOLEAN TYPE ===\n');
// Boolean values
let isTrue = true;
let isFalse = false;
console.log('true:', isTrue);
console.log('false:', isFalse);
// Booleans from comparisons
console.log('\nFrom comparisons:');
console.log('5 > 3:', 5 > 3);
console.log('5 === 5:', 5 === 5);
console.log("'a' < 'b':", 'a' < 'b');
// Truthy and Falsy
console.log('\nFalsy values:');
console.log('Boolean(false):', Boolean(false));
console.log('Boolean(0):', Boolean(0));
console.log("Boolean(''):", Boolean(''));
console.log('Boolean(null):', Boolean(null));
console.log('Boolean(undefined):', Boolean(undefined));
console.log('Boolean(NaN):', Boolean(NaN));
console.log('\nTruthy values:');
console.log('Boolean(true):', Boolean(true));
console.log('Boolean(1):', Boolean(1));
console.log("Boolean('hello'):", Boolean('hello'));
console.log('Boolean([]):', Boolean([])); // true!
console.log('Boolean({}):', Boolean({})); // true!
console.log("Boolean('false'):", Boolean('false')); // true!
// Double negation to convert to boolean
let value = 'hello';
console.log('\nDouble negation !!:', !!'hello', !!0, !!null);
// ============================================
// NULL TYPE
// ============================================
console.log('\n=== NULL TYPE ===\n');
let empty = null;
console.log('null value:', empty);
console.log('typeof null:', typeof null); // "object" - historical bug!
console.log('null === null:', null === null);
// Null vs undefined
console.log('\nNull vs Undefined:');
console.log('null == undefined:', null == undefined); // true
console.log('null === undefined:', null === undefined); // false
// ============================================
// UNDEFINED TYPE
// ============================================
console.log('\n=== UNDEFINED TYPE ===\n');
// Ways to get undefined
let notAssigned;
console.log('Variable not assigned:', notAssigned);
console.log('typeof undefined:', typeof undefined);
let obj = { a: 1 };
console.log('Non-existent property:', obj.b);
function noReturn() {
let x = 5;
}
console.log('Function without return:', noReturn());
// Checking for undefined
console.log('\nChecking for undefined:');
console.log('notAssigned === undefined:', notAssigned === undefined);
console.log(
"typeof notAssigned === 'undefined':",
typeof notAssigned === 'undefined'
);
// ============================================
// SYMBOL TYPE
// ============================================
console.log('\n=== SYMBOL TYPE ===\n');
// Creating symbols
let sym1 = Symbol();
let sym2 = Symbol();
console.log('Symbol() === Symbol():', sym1 === sym2); // false - always unique!
// Symbols with description
let id = Symbol('id');
console.log('Symbol with description:', id);
console.log('Symbol description:', id.description);
// Symbols as object keys
const SECRET_KEY = Symbol('secret');
let user = {
name: 'John',
[SECRET_KEY]: 'hidden value',
};
console.log('\nSymbol as object key:');
console.log('user.name:', user.name);
console.log('user[SECRET_KEY]:', user[SECRET_KEY]);
console.log('Object.keys(user):', Object.keys(user)); // Symbol not included!
console.log(
'Object.getOwnPropertySymbols:',
Object.getOwnPropertySymbols(user)
);
// Global symbols
let globalSym = Symbol.for('shared');
let sameSym = Symbol.for('shared');
console.log('\nGlobal symbols:');
console.log(
"Symbol.for('shared') === Symbol.for('shared'):",
globalSym === sameSym
);
console.log('Symbol.keyFor(globalSym):', Symbol.keyFor(globalSym));
// ============================================
// BIGINT TYPE
// ============================================
console.log('\n=== BIGINT TYPE ===\n');
// Creating BigInt
let bigNum = 9007199254740991n;
let hugeNum = 123456789012345678901234567890n;
console.log('BigInt:', bigNum);
console.log('Huge BigInt:', hugeNum);
console.log('typeof BigInt:', typeof bigNum);
// BigInt arithmetic
let a = 100n;
let b = 30n;
console.log('\nBigInt arithmetic:');
console.log('100n + 30n =', a + b);
console.log('100n * 30n =', a * b);
console.log('100n / 30n =', a / b); // 3n (truncated)
// BigInt vs Number
console.log('\nBigInt vs Number:');
console.log('1n == 1:', 1n == 1); // true (loose equality)
console.log('1n === 1:', 1n === 1); // false (strict equality)
// Cannot mix in operations
// console.log(100n + 50); // TypeError!
console.log('100n + BigInt(50):', 100n + BigInt(50));
// ============================================
// REFERENCE TYPES (OBJECTS)
// ============================================
console.log('\n=== REFERENCE TYPES ===\n');
// Object literal
let person = {
name: 'John',
age: 30,
};
console.log('Object:', person);
// Array
let numbers = [1, 2, 3, 4, 5];
console.log('Array:', numbers);
// Function
function greet() {
return 'Hello!';
}
console.log('Function:', greet);
console.log('Function call:', greet());
// Type checking
console.log('\nType checking:');
console.log('typeof object:', typeof person);
console.log('typeof array:', typeof numbers);
console.log('typeof function:', typeof greet);
console.log('Array.isArray(numbers):', Array.isArray(numbers));
console.log('Array.isArray(person):', Array.isArray(person));
// Reference vs Value
console.log('\nReference behavior:');
let original = { x: 10 };
let copy = original;
copy.x = 20;
console.log('original.x after modifying copy:', original.x); // 20!
let primitive = 10;
let primitiveCopy = primitive;
primitiveCopy = 20;
console.log('primitive after modifying copy:', primitive); // 10
// ============================================
// TYPE CHECKING TECHNIQUES
// ============================================
console.log('\n=== TYPE CHECKING TECHNIQUES ===\n');
// typeof operator
console.log('typeof results:');
console.log(' typeof 42:', typeof 42);
console.log(" typeof 'hello':", typeof 'hello');
console.log(' typeof true:', typeof true);
console.log(' typeof undefined:', typeof undefined);
console.log(' typeof null:', typeof null); // "object" - bug!
console.log(' typeof Symbol():', typeof Symbol());
console.log(' typeof 42n:', typeof 42n);
console.log(' typeof {}:', typeof {});
console.log(' typeof []:', typeof []);
console.log(' typeof function(){}:', typeof function () {});
// Better type checking function
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
console.log('\nObject.prototype.toString results:');
console.log(' getType(42):', getType(42));
console.log(" getType('hello'):", getType('hello'));
console.log(' getType(null):', getType(null));
console.log(' getType([]):', getType([]));
console.log(' getType({}):', getType({}));
console.log(' getType(new Date()):', getType(new Date()));
console.log(' getType(/regex/):', getType(/regex/));
// ============================================
// PRACTICAL EXAMPLES
// ============================================
console.log('\n=== PRACTICAL EXAMPLES ===\n');
// Example 1: Type-safe function
function add(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new TypeError('Both arguments must be numbers');
}
return a + b;
}
console.log('Type-safe add(5, 3):', add(5, 3));
// console.log(add("5", 3)); // Would throw TypeError
// Example 2: Default values with nullish check
function greetUser(name) {
const displayName = name ?? 'Guest';
return `Hello, ${displayName}!`;
}
console.log("greetUser('Alice'):", greetUser('Alice'));
console.log('greetUser(null):', greetUser(null));
console.log('greetUser(undefined):', greetUser(undefined));
// Example 3: Working with different types
function processValue(value) {
const type = typeof value;
switch (type) {
case 'number':
return `Number: ${value * 2}`;
case 'string':
return `String: ${value.toUpperCase()}`;
case 'boolean':
return `Boolean: ${!value}`;
case 'object':
if (value === null) return 'Null value';
if (Array.isArray(value)) return `Array with ${value.length} items`;
return `Object with keys: ${Object.keys(value).join(', ')}`;
default:
return `Type: ${type}`;
}
}
console.log('\nProcessing different types:');
console.log(' 42:', processValue(42));
console.log(" 'hello':", processValue('hello'));
console.log(' true:', processValue(true));
console.log(' null:', processValue(null));
console.log(' [1,2,3]:', processValue([1, 2, 3]));
console.log(' {a:1}:', processValue({ a: 1 }));