Lesson 2: Variables and Data Types
1. Introduction to Variables
Variables in programming are like containers that store data. They allow us to manipulate and work with information. In JavaScript, variables can store various types of data, including numbers, strings, and booleans.
// Example of declaring a variable and assigning a value
let age = 25;
let name = "John";
let isStudent = true;
2. Declaring Variables
In JavaScript, there are three ways to declare variables: var
, let
, and const
. They differ in terms of scope and hoisting.
var x = 10; // Function-scoped variable
let y = 20; // Block-scoped variable
const z = 30; // Block-scoped constant
3. Primitive Data Types
JavaScript has several primitive data types:
Numbers: Used for numeric values.
let age = 25; let price = 19.99;
Strings: Used for text data.
let name = "Alice"; let greeting = 'Hello, World!';
Booleans: Used for true or false values.
let isStudent = true; let isLoggedIn = false;
4. Working with Variables and Data Types
Now, let's explore how to work with variables and data types:
Math Operations:
let x = 10; let y = 5; let sum = x + y; // sum is 15 let difference = x - y; // difference is 5
String Concatenation:
let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName; // fullName is "John Doe"
Boolean Logic:
let isTall = true; let isStrong = false; let isTallAndStrong = isTall && isStrong; // isTallAndStrong is false
5. Practice and Exercises
Here are some exercises to practice the concepts:
- Declare a variable for your age and print it to the console.
- Create a variable for your favorite color and display it.
- Calculate the area of a rectangle with given width and height.
- Check if a user is eligible to vote based on their age.
6. Conclusion
In this lesson, you've learned the basics of variables and data types in JavaScript. Understanding how to declare variables and work with different data types is fundamental in programming. In the next lesson, we'll dive deeper into variable scope and more advanced data structures.