Part 2: JavaScript Basics
Variables and Data Types
In this section, we'll learn about variables, which are containers for storing data, and the various data types supported in JavaScript.
Variables
Variables are declared using the var
, let
, or const
keyword. They can hold various types of data, including numbers, strings, booleans, arrays, objects, and more.
// Variable declaration
var message = "Hello, world!";
let count = 10;
const PI = 3.14;
// Variable usage
console.log(message); // Output: Hello, world!
console.log(count); // Output: 10
console.log(PI); // Output: 3.14
Data Types
JavaScript supports several data types:
- Primitive Types: Numbers, strings, booleans, null, undefined, and symbols.
- Composite Types: Arrays and objects.
Operators
Operators allow you to perform operations on variables and values. JavaScript supports various types of operators:
- Arithmetic Operators: Addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--).
- Comparison Operators: Equal to (==), not equal to (!=), strict equal to (===), strict not equal to (!==), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
- Logical Operators: AND (&&), OR (||), and NOT (!).
- Assignment Operators: Assigns a value to a variable (e.g., =, +=, -=, *=, /=).
- Ternary Operator: A conditional operator that assigns a value based on a condition.
Control Structures
Control structures allow you to control the flow of your program based on conditions.
- If-Else Statements: Execute a block of code if a condition is true; otherwise, execute another block of code.
- Switch Statement: Evaluate an expression and execute different code blocks based on matching cases.
- Loops: Repeat a block of code until a specified condition is met. JavaScript supports
for
,while
, anddo-while
loops.
Functions
Functions are blocks of reusable code that perform a specific task. They allow you to write code once and reuse it multiple times.
// Function declaration
function greet(name) {
return "Hello, " + name + "!";
}
// Function usage
console.log(greet("John")); // Output: Hello, John!
console.log(greet("Emily")); // Output: Hello, Emily!
These are the fundamental concepts of JavaScript that we'll explore in the next part of the course.