Variables
A variable stores a value under a name. Modern JavaScript uses let and const.
let age = 20; // can change later
const name = "Asha"; // cannot be reassigned
age = 21;
console.log(name, age);- Use
constby default, andletwhen the value must change. - Avoid
var, which has confusing scope rules. - Names are case-sensitive and cannot start with a number. Use camelCase:
totalMarks.
Data types
let text = "Hello"; // string
let count = 42; // number
let price = 99.5; // number (decimals too)
let isOpen = true; // boolean
let nothing = null; // intentionally empty
let notSet; // undefined
let big = 12345678901234567890n; // BigIntCheck a type with typeof:
console.log(typeof "hi"); // "string"
console.log(typeof 5); // "number"
console.log(typeof true); // "boolean"Strings
<script>
const first = "Asha";
const msg = `Hello, ${first}! You have ${3 + 2} new messages.`;
document.write(msg + "<br>");
document.write(msg.length + " characters, uppercase: " + msg.toUpperCase());
</script>Template literals (backticks) let you insert values with ${...}.
Type conversion
Number("42"); // 42
Number("abc"); // NaN (not a number)
String(100); // "100"
parseInt("15px"); // 15
"5" + 2; // "52" (string joining)
"5" - 2; // 3 (number maths)Tip: Use === (strict equality) instead of == to avoid surprising conversions.
Practice
Create variables for a student's name, marks in three subjects and calculate the average. Print a sentence using a template literal.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Declare variables using let and const and try reassigning each.
- Check the type of five values with typeof.
- Explain what undefined and null mean in your own words.
Common mistakes
- Using var out of habit.
- Comparing a string and a number without realising the type.
Quick check
When should you use const?
When the variable will not be reassigned.
What does typeof null return?
"object", a well-known quirk of the language.