Lesson 2 - Variables in JavaScript
Welcome to lesson 2. Let's learn about variables today. Here is how we create vvariables. They are like pockets, we put things inside so that we can access then anytime and reuse them.
// Declaring variables
let name = "Alice";
const age = 25;
// Output values
console.log("Name:", name);
console.log("Age:", age);
Explanation:
let
is used to declare a variable whose value can change.const
is used for constants whose values cannot be reassigned.console.log()
displays the values in the browser console.
Try your hand
1. Create a File:
- Open your favorite code editor (e.g., VS Code or Notepad++).
- Create a new file and name it day2-variables.html.
2. Write the Code:
Add the following code to your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Day 2 - Variables</title>
</head>
<body>
<script>
// Declaring variables
let name = "Alice";
const age = 25;
// Output values
console.log("Name:", name);
console.log("Age:", age);
</script>
</body>
</html>
- Save the file in a folder where you can find it easily.
3. Preview the File:
- Open the file in your browser (e.g., Chrome or Firefox). You can double-click on it or right-click -> open with... -> choose your browser
- Press
Ctrl + Shift + J
(Windows) orCmd + Option + J
(Mac) to open the browser's developer console. - Observe the output:
Name: Alice
Age: 25
4. Experiment:
Change the values of name
and age
, save the file, and refresh the browser to see the new output.
That was fantastic!