JavaScript Variables and Data Types Guide

javascript
variables
data-types
coercion
scope

Variables

Declaration Types

  • var: Function-scoped, can be redeclared, hoisted.
  • let: Block-scoped, cannot be redeclared, not hoisted.
  • const: Block-scoped, immutable reference.
// Example
var a = 10; // Function-scoped
let b = 20; // Block-scoped
const c = 30; // Block-scoped and constant

Scope

  • Global Scope: Variables accessible everywhere.
  • Function Scope: Variables declared with var inside a function.
  • Block Scope: Variables declared with let or const inside {}.
function example() {
  if (true) {
    let blockScoped = 'Visible here only';
    var functionScoped = 'Visible throughout the function';
  }
  console.log(functionScoped); // Accessible
  console.log(blockScoped); // Error: Not defined
}

Data Types

Primitive Types

  1. string: "Hello, World!"
  2. number: 42, 3.14, -7
  3. boolean: true, false
  4. undefined: Declared but not assigned.
  5. null: Intentionally empty value.
  6. symbol: Unique and immutable identifiers.
  7. bigint: Large integers (12345678901234567890n).

Reference Types

  1. Object: { key: 'value' }
  2. Array: [1, 2, 3]
  3. Function: () => {}

Type Conversion

Implicit Conversion (Type Coercion)

'5' + 5; // "55" (string concatenation)
'5' - 2; // 3 (number subtraction)
true + 2; // 3

Explicit Conversion

Number('123'); // 123
String(123); // "123"
Boolean(0); // false