That's great! Let's dive right into the very first steps of writing JavaScript: Variables and Data Types.
📝 Variables: Storing Information
A variable is essentially a named container for a value. In modern JavaScript, we use two main keywords to declare a variable:
| Keyword | Purpose | Example |
|---|---|---|
| const | Declares a constant. The value cannot be changed after it's assigned. Use this by default! | const PI = 3.14159; |
| let | Declares a variable whose value can be changed (reassigned). | let score = 0; |
Example:
// Declaring a constant (preferred)
const userName = "Alice";
// Declaring a variable that can be changed
let age = 25;
age = 26; // This is allowed!
// This would cause an error because PI is a constant!
// const PI = 3.14;
// PI = 3.14159;
🔢 Data Types: The Kinds of Values
Every value in JavaScript has a type. Here are the most common primitive data types:
* String: Used for text. Always enclosed in quotes.
const greeting = "Hello, world!";
const letter = 'A';
* Number: Used for both integers (whole numbers) and floating-point numbers (decimals).
const answer = 42;
const price = 19.99;
* Boolean: Used for logic; represents only one of two values: true or false.
let isAdult = true;
const isOverdue = false;
* Undefined: Means the variable has been declared but has not been assigned a value yet.
let city; // city is currently 'undefined'
* Null: Means the variable has been explicitly assigned to represent "no value" or "nothing."
const activeUser = null;
Checking the Type
You can check the type of any value using the typeof operator:
console.log(typeof "Bob"); // Output: "string"
console.log(typeof 100); // Output: "number"
console.log(typeof true); // Output: "boolean"
console.log(typeof city); // Output: "undefined"
💻 Activity: Try It Out!
* Open your browser's Developer Tools (usually by pressing F12 or Ctrl+Shift+I/Cmd+Option+I).
* Go to the Console tab.
* Type and execute the following lines of code:
<!-- end list -->
const favoriteColor = "blue";
let year = 2025;
let isCodingFun = true;
console.log(favoriteColor);
console.log(year);
year = year + 1; // Change the value of the 'let' variable
console.log(year);
0 Comments