For Day 1, we're diving straight into what I consider the absolute core concepts of JavaScript: Variables(like a box to hold information)and Data Types (what kind of information is in the box, e.g., text or numbers) .
How We Declare Variables in JavaScript:
In modern JavaScript, we primarily use two keywords to create these containers:
-
let
: Uselet
when you expect the value stored in your variable to change (or be reassigned) later in your program.
let firstNumber = 1000; // 'firstNumber ' holds the number 1000
console.log(firstNumber ); // Output: 1000
firstNumber = 1200; // We can change its value later!
console.log(firstNumber ); // Output: 1200
-
const
: Useconst
when the value of the variable should never change after you've set it. If you try to reassign a const variable, JavaScript will throw an error. This is perfect for values that truly are constant, like a fixed mathematical constant or a username that shouldn't be altered.
//const example
const PIN = 3.14159; // PIN will always be this value
console.log(PIN); // Output: 3.14159
// PIN = 3.0; // This would cause an error! (Try it in your console!)
-
var
: You might seevar
in older code examples. While it still works,let
andconst
were introduced in ES6 (a newer version of JavaScript) to address some confusing behaviors ofvar
. For any new code you write, it's a best practice to stick withlet
andconst
.
Naming Our Boxes:
"Just like labeling real-world boxes, there are rules for naming variables: you can use letters, numbers, underscores, and dollar signs, but they must start with a letter, _
, or $
. Also, JavaScript is case-sensitive, so myName
is different from myname
."
Code Example:
// Storing text in a variable
const user_Name = "AnsiKadeeja";
console.log(user_Name); // Output: AnsiKadeeja
// Using a boolean
let isLoggedIn = true;
console.log(isLoggedIn); // Output: true
// Showing how 'let' allows changes
let $temperature = 20;
console.log("Current temp:", $temperature); // Output: Current temp: 20
$temperature = 22; // Changing the value
console.log("New temp:", $temperature); // Output: New temp: 22
Top comments (0)