Chapter 9: JavaScript Basics
Chapter 9 of 15
Chapter 9: JavaScript Basics
9.1 Variables and Data Types
Variables store data that can be used and modified in your code. JavaScript has three ways to declare variables.
Variable Declaration:
// let - can be reassigned, block-scoped
let name = "John";
name = "Jane"; // OK
// const - cannot be reassigned, block-scoped
const age = 30;
age = 31; // Error: Assignment to constant variable
// var - can be reassigned, function-scoped (avoid using)
var city = "NYC";
city = "Boston"; // OK
Data Types:
- String: Text data ("Hello", 'World', `Template`)
- Number: Numeric data (42, 3.14, -10)
- Boolean: True or false (true, false)
- Null: Intentional absence of value (null)
- Undefined: Variable declared but not assigned (undefined)
- Object: Collection of key-value pairs ({name: "John"})
- Array: Ordered list of values ([1, 2, 3])
Type Checking:
typeof "hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof null; // "object" (quirk)
typeof undefined; // "undefined"
typeof {}; // "object"
typeof []; // "object"
Type Conversion:
// String to number
Number("123"); // 123
parseInt("123"); // 123
parseFloat("3.14"); // 3.14
// Number to string
String(123); // "123"
(123).toString(); // "123"
// Boolean conversion
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
9.2 Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.
Function Declaration:
function greet(name) {
return "Hello, " + name;
}
greet("John"); // "Hello, John"
Function Expression:
const greet = function(name) {
return "Hello, " + name;
};
greet("John"); // "Hello, John"
Arrow Functions (ES6+):
// Single parameter, single expression
const greet = name => "Hello, " + name;
// Multiple parameters
const add = (a, b) => a + b;
// Multiple statements
const process = (data) => {
const result = data * 2;
return result;
};
Function Parameters:
// Default parameters
function greet(name = "Guest") {
return "Hello, " + name;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
Higher-Order Functions:
// Functions that take other functions as arguments
const numbers = [1, 2, 3, 4, 5];
// map - transform each element
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
// filter - select elements
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
// reduce - combine elements
const sum = numbers.reduce((a, b) => a + b, 0); // 15
9.3 Control Flow
Control flow statements determine the order in which code executes.
Conditional Statements:
// if/else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Ternary operator
const status = age >= 18 ? "Adult" : "Minor";
// switch
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("End of week");
break;
default:
console.log("Midweek");
}
Loops:
// for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// while loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// for...of (arrays)
for (const item of array) {
console.log(item);
}
// for...in (objects)
for (const key in object) {
console.log(key, object[key]);
}
9.4 Objects and Arrays
Objects and arrays are fundamental data structures in JavaScript.
Objects:
// Object literal
const person = {
name: "John",
age: 30,
city: "NYC"
};
// Access properties
person.name; // "John"
person["age"]; // 30
// Add properties
person.email = "john@example.com";
// Methods
const person = {
name: "John",
greet: function() {
return "Hello, " + this.name;
}
};
Arrays:
// Array literal
const fruits = ["apple", "banana", "orange"];
// Access elements
fruits[0]; // "apple"
// Array methods
fruits.push("grape"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("mango"); // Add to beginning
fruits.shift(); // Remove from beginning
fruits.length; // Get length