JavaScript
Complete guide to learning JavaScript
JavaScript
JavaScript is the programming language of the web. It allows you to create interactive and dynamic websites.
Basics
Variables
In JavaScript, you can declare variables with let, const, or var:
// Use const for values that do not change
const name = "TechYouHigh";
// Use let for values that can change
let age = 25;
age = 26; // OK
// Avoid var (old syntax)
var oldVariable = "to avoid";Data Types
JavaScript has several primitive data types:
// String
const text = "Hello";
// Number
const number = 42;
const decimal = 3.14;
// Boolean
const isTrue = true;
const isFalse = false;
// Null and Undefined
const empty = null;
let notDefined;
// Array
const fruits = ["apple", "banana", "orange"];
// Object
const person = {
name: "John",
age: 30,
city: "Paris",
};Functions
Function Declaration
// Classic function
function greet(name) {
return `Hello ${name}!`;
}
// Arrow function
const greetArrow = (name) => {
return `Hello ${name}!`;
};
// Short arrow function
const greetShort = (name) => `Hello ${name}!`;
console.log(greet("Mary")); // "Hello Mary!"Array Manipulation
Common Methods
const numbers = [1, 2, 3, 4, 5];
// map: transform each element
const doubles = numbers.map((n) => n * 2);
// [2, 4, 6, 8, 10]
// filter: filter elements
const evens = numbers.filter((n) => n % 2 === 0);
// [2, 4]
// reduce: reduce to a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
// find: find an element
const found = numbers.find((n) => n > 3);
// 4Asynchronous
Promises and Async/Await
// Promise
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data loaded");
}, 1000);
});
}
// Async/Await
async function loadData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
loadData();Best Practices
- Use const by default, let if necessary
- Prefer arrow functions for callbacks
- Use async/await instead of
.then() - Destructure objects and arrays
- Use template literals for strings
// Destructuring (standalone example)
const person2 = { name: "John", age: 30, city: "Paris" };
const fruits2 = ["apple", "banana", "orange"];
const { name: name2, age: age2 } = person2;
const [first, second] = fruits2;
// Template literals
const message = `${name2} is ${age2} years old`;
// Spread operator
const newArray = [...fruits2, "kiwi"];
const newObject = { ...person2, city: "Lyon" };