Variables & Data Types

📚 Lesson 2 of 40  •  ⏱ 12 min read  •  Beginner

Declaring Variables

Variables store data. JavaScript has three ways to declare them:

JavaScript
// let — can be changed later (block-scoped). Use this most often.
let age = 21;
age = 22;  // OK — can reassign

// const — cannot be changed (block-scoped). Use for values that don't change.
const PI = 3.14159;
const siteName = "AnnaUniversityPlus";
// PI = 3;  ← ERROR: cannot reassign a const

// var — old way (function-scoped). Avoid in modern code.
var score = 100;  // works but has quirks

Data Types

Primitive Types

JavaScript
// String — text, in quotes
let name = "Mohan";
let dept = 'CSE';
let msg  = `Hello, ${name}!`;  // template literal (backticks)

// Number — integers and decimals
let cgpa = 8.5;
let semester = 5;
let negative = -10;
let big = 1_000_000;  // underscores allowed for readability

// Boolean — true or false only
let isLoggedIn = true;
let hasArrear  = false;

// null — intentionally empty value
let selectedCourse = null;

// undefined — variable declared but not assigned
let result;
console.log(result);  // undefined

// BigInt — very large integers
let bigNum = 9007199254740991n;

// Symbol — unique identifier (advanced)
const id = Symbol('id');

Non-Primitive Types

JavaScript
// Object — key: value pairs
const student = {
  name: "Mohan",
  dept: "CSE",
  cgpa: 8.5,
  hasArrear: false
};
console.log(student.name);   // "Mohan"
console.log(student["cgpa"]); // 8.5

// Array — ordered list of values
const subjects = ["Maths", "Physics", "Web Tech"];
console.log(subjects[0]);    // "Maths" (index starts at 0)
console.log(subjects.length); // 3

typeof Operator

JavaScript
typeof "hello"     // "string"
typeof 42          // "number"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object" ← known JS bug, it's actually null
typeof {}          // "object"
typeof []          // "object" (arrays are objects in JS)
typeof function(){} // "function"

Type Conversion

JavaScript
// String to Number
Number("42")       // 42
parseInt("42px")   // 42 (stops at non-numeric)
parseFloat("3.14") // 3.14
+"42"               // 42 (unary + shorthand)

// Number to String
String(42)         // "42"
(42).toString()    // "42"
(3.14159).toFixed(2) // "3.14"

// To Boolean
Boolean(0)    // false  (falsy)
Boolean("")   // false  (falsy)
Boolean(null) // false  (falsy)
Boolean(1)    // true   (truthy)
Boolean("hi") // true   (truthy)