Skip to main content

Module 2: Variables, Data Types & Operators

This module covers the fundamental building blocks of JavaScript: how to store data (variables), what types of data exist (data types), and how to manipulate data (operators).


1. Variables in JavaScript

A variable is a named container that stores a value.

1.1 Variable Declaration Keywords

var (Legacy - Avoid)

var name = 'John';
var age = 30;

Problems with var:

  • Function-scoped (not block-scoped)
  • Can be redeclared
  • Hoisting issues
  • Global scope pollution
Avoid var

var has been superseded by let and const. Use them instead.

let (Block-scoped, Reassignable)

let name = 'John';
name = 'Jane'; // ✅ Can be reassigned

let count = 0;
count++; // ✅ Can be modified

const (Block-scoped, Cannot be Reassigned)

const PI = 3.14159;
const API_KEY = 'abc123';

PI = 3.14; // ❌ Error: Assignment to constant variable

Important: const prevents reassignment, not mutation:

const user = { name: 'John' };
user.name = 'Jane'; // ✅ Allowed (mutation)
user = {}; // ❌ Error (reassignment)

const numbers = [1, 2, 3];
numbers.push(4); // ✅ Allowed (mutation)
numbers = []; // ❌ Error (reassignment)
Best Practice

Always use const by default. Only use let when you know the variable will be reassigned.

1.2 Variable Naming Rules

Valid:

let userName = 'John';
let _private = true;
let $element = document.querySelector('.btn');
let user2 = 'Jane';

Invalid:

let 2user = 'John'; // ❌ Cannot start with number
let user-name = 'John'; // ❌ Hyphen not allowed
let let = 'value'; // ❌ Reserved keyword
let class = 'A'; // ❌ Reserved keyword

Naming Conventions:

// camelCase for variables and functions
let firstName = 'John';
let calculateTotal = () => {};

// PascalCase for classes
class UserProfile {}

// UPPER_SNAKE_CASE for constants
const MAX_RETRY_COUNT = 3;
const API_BASE_URL = 'https://api.example.com';

2. Data Types in JavaScript

JavaScript has 8 data types (7 primitive + 1 reference type).

2.1 Primitive Types

1. String

const name = 'John';
const greeting = "Hello";
const template = `Hello, ${name}!`; // Template literal

// String properties and methods
console.log(name.length); // 4
console.log(name.toUpperCase()); // JOHN
console.log(name.toLowerCase()); // john

2. Number

const age = 25;
const price = 99.99;
const negative = -10;
const exponential = 1e6; // 1000000

// Special numeric values
const infinity = Infinity;
const notANumber = NaN;

console.log(typeof NaN); // "number" (weird but true)

3. BigInt (ES2020)

const bigNumber = 1234567890123456789012345678901234567890n;
const anotherBig = BigInt('9007199254740991');

console.log(bigNumber + 1n); // BigInt arithmetic

4. Boolean

const isActive = true;
const isDeleted = false;

// Truthy and Falsy values
// Falsy: false, 0, '', null, undefined, NaN
// Everything else is truthy

5. Undefined

let x;
console.log(x); // undefined

function test() {
// no return statement
}
console.log(test()); // undefined

6. Null

let user = null; // Intentional absence of value

console.log(typeof null); // "object" (JavaScript bug!)

7. Symbol (ES6)

const id1 = Symbol('id');
const id2 = Symbol('id');

console.log(id1 === id2); // false (always unique)

2.2 Reference Type

Object

// Object literal
const person = {
name: 'John',
age: 30,
city: 'New York'
};

// Array
const numbers = [1, 2, 3, 4, 5];

// Function
const greet = function() {
console.log('Hello!');
};

// Date
const now = new Date();

// All are objects
console.log(typeof person); // "object"
console.log(typeof numbers); // "object"
console.log(typeof greet); // "function"
console.log(typeof now); // "object"

3. Type Checking

3.1 typeof Operator

console.log(typeof 'hello'); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (bug)
console.log(typeof Symbol()); // "symbol"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function() {}); // "function"

3.2 Better Type Checking

// Array check
Array.isArray([]); // true
Array.isArray({}); // false

// Null check
const value = null;
value === null; // true

// Object check (excluding null)
typeof value === 'object' && value !== null;

// instanceof for classes
const date = new Date();
date instanceof Date; // true

4. Type Conversion

4.1 String Conversion

// Explicit
String(123); // "123"
String(true); // "true"
(123).toString(); // "123"

// Implicit
123 + ''; // "123"
'Value: ' + 42; // "Value: 42"

4.2 Number Conversion

// Explicit
Number('123'); // 123
Number('12.5'); // 12.5
Number('hello'); // NaN
parseInt('123px'); // 123
parseFloat('12.5em'); // 12.5

// Implicit
+'123'; // 123 (unary plus)
'123' - 0; // 123
'10' * 2; // 20

4.3 Boolean Conversion

// Explicit
Boolean(1); // true
Boolean(0); // false
Boolean('hello'); // true
Boolean(''); // false

// Implicit (in conditions)
if ('hello') {} // true
if (0) {} // false

// Double negation trick
!!'hello'; // true
!!0; // false
Type Coercion Gotchas
'2' + 2; // "22" (string concatenation)
'2' - 2; // 0 (numeric subtraction)
true + true; // 2
'5' * '2'; // 10
[] + []; // "" (empty string)
{} + []; // 0 (in some contexts)

5. Operators

5.1 Arithmetic Operators

let x = 10, y = 3;

x + y; // 13 (Addition)
x - y; // 7 (Subtraction)
x * y; // 30 (Multiplication)
x / y; // 3.333... (Division)
x % y; // 1 (Modulus/Remainder)
x ** y; // 1000 (Exponentiation ES2016)

// Increment/Decrement
let count = 5;
count++; // 6 (post-increment)
++count; // 7 (pre-increment)
count--; // 6 (post-decrement)
--count; // 5 (pre-decrement)

5.2 Assignment Operators

let x = 10;

x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
x **= 3; // x = x ** 3 → 8

5.3 Comparison Operators

// Equality
5 == '5'; // true (loose equality, type coercion)
5 === '5'; // false (strict equality, no coercion)
5 != '5'; // false
5 !== '5'; // true

// Relational
10 > 5; // true
10 < 5; // false
10 >= 10; // true
10 <= 5; // false
Always Use Strict Equality

Use === and !== to avoid unexpected type coercion bugs.

5.4 Logical Operators

// AND (&&)
true && true; // true
true && false; // false

// OR (||)
true || false; // true
false || false; // false

// NOT (!)
!true; // false
!false; // true

// Short-circuit evaluation
const name = userName || 'Guest'; // Default value
const isAdmin = user && user.isAdmin; // Safe access

5.5 Nullish Coalescing (??) - ES2020

const value = null ?? 'default'; // "default"
const value2 = 0 ?? 'default'; // 0 (0 is not null/undefined)

// Difference from ||
0 || 'default'; // "default" (0 is falsy)
0 ?? 'default'; // 0 (0 is not nullish)

5.6 Optional Chaining (?.) - ES2020

const user = {
name: 'John',
address: {
city: 'New York'
}
};

// Without optional chaining
const zip = user && user.address && user.address.zip;

// With optional chaining
const zip = user?.address?.zip; // undefined (no error)

5.7 Ternary Operator

const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';

// Nested ternary (use sparingly)
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';

5.8 Bitwise Operators (Advanced)

5 & 1; // 1 (AND)
5 | 1; // 5 (OR)
5 ^ 1; // 4 (XOR)
~5; // -6 (NOT)
5 << 1; // 10 (Left shift)
5 >> 1; // 2 (Right shift)

6. Template Literals (ES6)

const name = 'John';
const age = 30;

// Old way
const greeting = 'Hello, ' + name + '! You are ' + age + ' years old.';

// Template literal
const greeting2 = `Hello, ${name}! You are ${age} years old.`;

// Multi-line strings
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;

// Expressions in templates
const total = `Total: ${price * quantity}`;
const upper = `Name: ${name.toUpperCase()}`;

7. Common Patterns

7.1 Variable Swapping

// Old way (with temp variable)
let a = 1, b = 2;
let temp = a;
a = b;
b = temp;

// Modern way (destructuring)
[a, b] = [b, a];

7.2 Default Values

// Old way
function greet(name) {
name = name || 'Guest';
console.log(`Hello, ${name}`);
}

// Modern way
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}

7.3 Type Guards

function processValue(value) {
if (typeof value === 'string') {
return value.toUpperCase();
} else if (typeof value === 'number') {
return value * 2;
}
return value;
}

Summary

In this module, you learned:

  • ✅ Variable declaration with let, const, and why to avoid var
  • ✅ All 8 JavaScript data types (7 primitive + 1 reference)
  • ✅ Type checking and type conversion
  • ✅ All JavaScript operators
  • ✅ Modern features: template literals, optional chaining, nullish coalescing
  • ✅ Common patterns and best practices
Next Steps

In Module 3, you'll learn about Control Flow and Conditional Statements to make your code make decisions.


Practice Exercises

  1. Declare variables using const and let for user profile data
  2. Create examples of all 8 data types
  3. Practice type conversion and observe coercion behavior
  4. Write expressions using all operator types
  5. Use template literals to create formatted strings
  6. Experiment with optional chaining and nullish coalescing
  7. Create a simple calculator using arithmetic operators

Additional Resources