Beginner · JavaScript basics · topic 19 of 64 · 25 min
Values, types and variables
Explanation
What is a program?
A program is a list of instructions the computer follows, one after another, from top to bottom. JavaScript instructions are called statements, and each usually ends with a semicolon.
console.log('Namaste!');
console.log(2 + 3); // 5Types of values
| Type | Examples | Used for |
|---|---|---|
| number | 42, 3.5, -10 | Prices, ages, counts |
| string | 'Asha', "Pune" | Any text, written in quotes |
| boolean | true, false | Yes/no answers: isLoggedIn |
| undefined | undefined | A variable that has no value yet |
| null | null | "Empty on purpose", set by you |
Arrays (lists) and objects (groups of named values) are also values; you will meet them soon. The typeof operator tells you the type: typeof 42 is "number", typeof "hi" is "string".
Variables: names for values
const shopName = 'Sharma Kirana';
let itemsInCart = 0;
itemsInCart = itemsInCart + 1; // let can change
// shopName = 'Other'; // Error: const cannot be reassigned
console.log(shopName, itemsInCart); // Sharma Kirana 1Use const by default. Switch to let only when you really need to change the value. Do not use var: it is the old way and has confusing rules about where the variable can be seen.
Naming rules
- Names can contain letters, digits, _ and $, but cannot start with a digit.
- JavaScript is case-sensitive: total and Total are different variables.
- Use camelCase: first word lowercase, each next word starts with a capital (totalPrice, isPaid).
- Choose names that explain: priceInRupees is better than p.
Strings and numbers mix carefully
console.log(10 + 5); // 15
console.log('10' + 5); // '105' (text joined, not added!)
console.log(Number('10') + 5); // 15
console.log(typeof '10'); // 'string'Watch the lesson
Values, types and variables · 1/6
A program is a list of instructions the computer runs from top to bottom.
Prefer a video by a teacher? Find free videos on “javascript variables let const data types for beginners” on YouTube ↗
In real life: A shopping cart counter
On a grocery app, const deliveryFee = 25 never changes during your visit, while let cartCount starts at 0 and goes up each time you tap "Add". The shop name is a string, the fee a number, and isFreeDelivery a boolean that becomes true when the cart total crosses 499 rupees.
Practice (0/2 done)
Create a const called city with the value "Jaipur", a let called visitors with the value 0, then add 3 to visitors (so it becomes 3).
Write a function addStrings(a, b) that receives two numbers written as strings (like "10" and "5") and returns their sum as a number (15).
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.