Variables and Data Types
What are variables?
A variable is a named container for a value. You store something in a variable so you can use it later, change it, or pass it to a function.
JavaScript has two modern ways to declare variables:
let and const.let vs const
const — use this by default. It means the variable can't be reassigned:JavaScript
const name = "Manish";
const pi = 3.14159;
name = "Someone"; // Error! Can't reassign a constlet — use this when you need to reassign the value:JavaScript
let score = 0;
score = score + 10; // Works fine
score += 5; // Shorthand — score is now 15What about
var? You'll see it in older code, but avoid it. var has confusing scoping behavior that let and const fix. Always use const first; switch to let only if you need to reassign.Data types
JavaScript has several built-in types:
Strings — text wrapped in quotes:
JavaScript
const greeting = "Hello, world!";
const name = 'Manish';
const message = `Welcome, ${name}!`; // Template literal (backticks)Template literals (backticks) let you embed expressions with `$
` — extremely useful.
Numbers — integers and decimals are the same type:
Numbers — integers and decimals are the same type:
JavaScript
const age = 25;
const price = 9.99;
const total = price * 3; // 29.97Booleans —
true or false:JavaScript
const isLoggedIn = true;
const hasPermission = false;null and undefined:
JavaScript
let user = null; // Explicitly "no value"
let address; // undefined — declared but not assignedArrays — ordered lists:
JavaScript
const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors.length); // 3Objects — key-value pairs:
JavaScript
const person = {
name: "Manish",
age: 25,
isStudent: true,
};
console.log(person.name); // "Manish"Naming conventions
- Use camelCase for variables:
firstName,isLoggedIn,totalPrice. - Make names descriptive:
userCountis better thanx. - Constants that never change are sometimes written in UPPERSNAKECASE:
const MAX_RETRIES = 3.
Common mistakes
Using
== instead of ===:JavaScript
console.log(2 == "2"); // true (loose equality — converts types!)
console.log(2 === "2"); // false (strict equality — compares type too)Always use
=== (strict equality). The loose == operator has surprising type coercion rules that lead to bugs.Key takeaway
Start with
const for everything. Switch to let only when you need to reassign. Learn the basic types — strings, numbers, booleans, arrays, and objects — and you'll have the foundation for everything else in JavaScript.