Curriculum
Course: JavaScript Basics
Login

Curriculum

JavaScript Basics

Text lesson

Lesson 4: Variables and Data Types

Variables and Data Types

Variables are used to store data that can be referenced and manipulated in a program. In this lesson, we’ll learn how to declare variables and explore different data types in JavaScript.

1. Declaring Variables:

  • Use var, let, or const to declare variables.
  • let and const are preferred over var due to better scoping rules.

2. Variable Assignment:

  • Assign values to variables using the assignment operator (=).
  • Example:
let name = 'John';
const age = 25;
var isStudent = true;

 

3. Data Types:

  • JavaScript supports various data types, including:
    • String: Text enclosed in single or double quotes.
    • Number: Numeric values.
    • Boolean: True or false values.
    • Array: Ordered collections of values.
    • Object: Collections of key-value pairs.
    • Null: Represents the intentional absence of any value.
    • Undefined: Variables that have been declared but not assigned a value.

Example Code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Variables and Data Types</title>
</head>
<body>
<h1>Variables and Data Types</h1>
<script>
let name = 'Alice';
const age = 30;
var isStudent = false;

console.log('Name:', name); // Output: Name: Alice
console.log('Age:', age); // Output: Age: 30
console.log('Is Student:', isStudent); // Output: Is Student: false

let hobbies = ['reading', 'sports', 'music'];
let person = {firstName: 'John', lastName: 'Doe'};

console.log('Hobbies:', hobbies); // Output: Hobbies: ["reading", "sports", "music"]
console.log('Person:', person); // Output: Person: {firstName: "John", lastName: "Doe"}
</script>
</body>
</html>

 

Conclusion: Understanding variables and data types is essential for managing and manipulating data in JavaScript. Practice declaring variables and using different data types to become comfortable with these fundamental concepts.

Layer 1
Login Categories
This website uses cookies and asks your personal data to enhance your browsing experience.