Chapter 2: Basic Syntax
Variables and Data Types
Variables
Variables are like containers that store data values. In JavaScript, you use variables to hold and manipulate information.
- Declaration: You declare variables using
var,let, orconst.varis the oldest way to declare variables and has some quirks.letallows you to declare variables that can be reassigned.constis used for variables that should not be reassigned after their initial value is set.
Example:
let age = 25; // A variable that can be changed
const name = "Alice"; // A variable that cannot be changed
Data Types
JavaScript has several types of data:
-
Numbers: Represents both integers and floating-point numbers.
- Example:
let temperature = 22.5;
- Example:
-
Strings: Represents sequences of characters, enclosed in quotes.
- Example:
let greeting = "Hello, world!";
- Example:
-
Booleans: Represents
trueorfalsevalues.- Example:
let isStudent = true;
- Example:
-
Null: Represents a deliberate non-value or empty value.
- Example:
let emptyValue = null;
- Example:
-
Undefined: Represents a variable that has been declared but not yet assigned a value.
- Example:
let notAssigned; // undefined
- Example:
-
Objects: Represents collections of related data and functions.
- Example:
let person = { name: "John", age: 30, };
- Example:
-
Arrays: Represents ordered lists of values.
- Example:
let colors = ["red", "green", "blue"];
- Example:
Operators
Operators perform operations on variables and values.
-
Arithmetic Operators: Perform mathematical operations.
+(Addition):5 + 3results in8-(Subtraction):10 - 4results in6*(Multiplication):2 * 3results in6/(Division):8 / 2results in4%(Modulus):5 % 2results in1
-
Comparison Operators: Compare values and return
trueorfalse.==(Equal to):5 == 5istrue===(Strict equal to):5 === '5'isfalse(type matters)!=(Not equal to):5 != 4istrue>(Greater than):10 > 5istrue<(Less than):3 < 7istrue
-
Logical Operators: Combine boolean values.
&&(Logical AND):true && falseisfalse||(Logical OR):true || falseistrue!(Logical NOT):!trueisfalse
Example:
let a = 10;
let b = 20;
let result = a + b; // result is 30
let isEqual = a == b; // isEqual is false
let isGreater = b > a; // isGreater is true
Control Flow
Control flow statements allow you to execute code based on certain conditions or repeatedly.
1. If Statement
The if statement allows you to execute a block of code only if a specified condition evaluates to true.
Syntax:
if (condition) {
// code to execute if the condition is true
}
Example:
let temperature = 25;
if (temperature > 20) {
console.log("It's warm outside.");
}
In this example, the message "It's warm outside." will be printed if temperature is greater than 20.
2. If/Else Statement
The if/else statement allows you to execute one block of code if the condition is true, and another block of code if the condition is false.
Syntax:
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
Example:
let score = 75;
if (score >= 60) {
console.log("You passed!");
} else {
console.log("You failed.");
}
In this example, if score is 60 or higher, it will print "You passed!". If score is below 60, it will print "You failed."
3. Else If Statement
The else if statement allows you to check multiple conditions sequentially. It’s used when you have more than two conditions to test.
Syntax:
if (condition1) {
// code to execute if condition1 is true
} else if (condition2) {
// code to execute if condition2 is true
} else {
// code to execute if none of the conditions are true
}
Example:
let age = 18;
if (age < 13) {
console.log("You are a child.");
} else if (age < 20) {
console.log("You are a teenager.");
} else {
console.log("You are an adult.");
}
In this example:
- If
ageis less than 13, it will print "You are a child." - If
ageis between 13 and 19 (inclusive of 13, but less than 20), it will print "You are a teenager." - If
ageis 20 or older, it will print "You are an adult."
4. Loops
Loops are used to execute a block of code multiple times.
-
For Loop: Executes a block of code a fixed number of times.
Example:
for (let i = 0; i < 5; i++) { console.log(i); }This loop prints numbers from 0 to 4.
-
While Loop: Executes a block of code as long as a condition is
true.Example:
let count = 0; while (count < 5) { console.log(count); count++; }This loop prints numbers from 0 to 4, incrementing
counteach time. -
Do-While Loop: Similar to the
whileloop, but guarantees that the code block is executed at least once.Example:
let num = 0; do { console.log(num); num++; } while (num < 5);This loop prints numbers from 0 to 4, incrementing
numeach time. It will run at least once, even if the condition isfalseinitially.