JavaScript
JavaScript is a high-level, interpreted programming language with dynamic typing and multi-paradigm support. Originally developed to add interactivity to web pages, it is now used on both the frontend and backend, making it one of the most popular and versatile languages in the programming world.
Key Features
1. Scripting Language
JavaScript is a scripting language, which means the code is interpreted at runtime, without the need for prior compilation. This allows for a fast and iterative development cycle.
2. Dynamic Typing
In JavaScript, variables are not associated with a specific type. A variable's type is determined at runtime and can change during the program's lifecycle.
let variable = 42; // number
variable = "Hello, world!"; // now it's a string
variable = true; // now it's a boolean
3. Multi-paradigm
JavaScript supports multiple programming paradigms, including:
- Imperative Programming: Based on commands that change the program's state.
- Functional Programming: Treating functions as first-class citizens.
- Object-Oriented Programming: Based on prototypes and, more recently, classes.
- Asynchronous Programming: Using callbacks, promises, and async/await.
4. Execution in Different Environments
JavaScript can be executed in various environments:
- Browsers: The traditional environment for JavaScript.
- Node.js: A server-side execution environment.
- Deno: A more recent JavaScript/TypeScript runtime.
- Mobile apps: Through frameworks like React Native.
- Desktop apps: With Electron or similar tools.
Basic Syntax
Variables and Constants
// Variable declaration
var x = 10; // Function scope (legacy)
let y = 20; // Block scope (ES6+)
const z = 30; // Constant (ES6+)
Data Types
JavaScript has the following primitive data types:
- Number: Represents both integer and floating-point numbers.
- String: A sequence of characters.
- Boolean: Logical values (true/false).
- Null: Represents the intentional absence of any object value.
- Undefined: Represents a variable that has been declared but not yet assigned a value.
- Symbol: A data type whose instances are unique and immutable (ES6+).
- BigInt: Represents integers with arbitrary precision (ES2020).
And one complex data type:
- Object: A collection of properties.
// Data type examples
let number = 42;
let text = "JavaScript";
let boolean = true;
let nullValue = null;
let undefinedValue = undefined;
let symbol = Symbol("description");
let bigNumber = 9007199254740991n;
let object = { key: "value" };
let array = [1, 2, 3]; // Arrays are objects in JavaScript
Control Structures
Conditionals
// If-else
if (condition) {
// code if true
} else if (anotherCondition) {
// code if the first condition is false and the second is true
} else {
// code if both conditions are false
}
// Ternary operator
let result = condition ? valueIfTrue : valueIfFalse;
// Switch
switch (variable) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// default code
}
Loops
// For
for (let i = 0; i < 10; i++) {
// code to be repeated
}
// While
while (condition) {
// code to be repeated as long as the condition is true
}
// Do-While
do {
// code to be executed at least once
} while (condition);
// For...of (to iterate over values of iterable objects)
for (const element of array) {
// code to process each element
}
// For...in (to iterate over enumerable properties of an object)
for (const key in object) {
// code to process each key
}
Functions
// Function declaration
function sum(a, b) {
return a + b;
}
// Function expression
const multiplication = function(a, b) {
return a * b;
};
// Arrow function (ES6+)
const division = (a, b) => a / b;
// Function with default parameters (ES6+)
function greet(name = "Visitor") {
return `Hello, ${name}!`;
}
// Rest parameters (ES6+)
function sumAll(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
Object-Oriented Programming
Object Literals
// Object literal
const person = {
name: "John",
age: 30,
profession: "Developer",
introduce() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
};
// Accessing properties
console.log(person.name); // Dot notation
console.log(person["profession"]); // Bracket notation
Prototypes
JavaScript is prototype-based, where objects can inherit properties and methods from other objects.
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}
// Adding a method to the prototype
Person.prototype.introduce = function() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
};
// Creating instances
const person1 = new Person("Maria", 25);
const person2 = new Person("Carlos", 35);
console.log(person1.introduce()); // "Hello, my name is Maria and I am 25 years old."
Classes (ES6+)
// Class declaration
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
return "Generic animal sound";
}
}
// Inheritance
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
makeSound() {
return "Woof woof!";
}
wagTail() {
return `${this.name} is wagging its tail`;
}
}
const rex = new Dog("Rex", "Labrador");
console.log(rex.makeSound()); // "Woof woof!"
console.log(rex.wagTail()); // "Rex is wagging its tail"
Asynchronous Programming
Callbacks
function fetchData(callback) {
setTimeout(() => {
const data = { id: 1, name: "Product" };
callback(null, data);
}, 1000);
}
fetchData((error, data) => {
if (error) {
console.error("Error:", error);
} else {
console.log("Data:", data);
}
});
Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: "Product" };
// Simulating success
resolve(data);
// Simulating error
// reject(new Error("Failed to fetch data"));
}, 1000);
});
}
fetchData()
.then(data => console.log("Data:", data))
.catch(error => console.error("Error:", error));
Async/Await
async function fetchAndProcessData() {
try {
const data = await fetchData();
console.log("Data:", data);
return data;
} catch (error) {
console.error("Error:", error);
throw error;
}
}
fetchAndProcessData();
Modern Features (ES6+)
Destructuring
// Object destructuring
const person = { name: "Ana", age: 28, profession: "Designer" };
const { name, age } = person;
// Array destructuring
const colors = ["red", "green", "blue"];
const [firstColor, secondColor] = colors;
Spread Operator
// Spread with arrays
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const allNumbers = [...numbers1, ...numbers2];
// Spread with objects
const personalData = { name: "Pedro", age: 32 };
const professionalData = { profession: "Engineer", company: "ABC" };
const fullProfile = { ...personalData, ...professionalData };
Template Literals
const name = "Maria";
const age = 30;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
Modules
// Exporting (file: module.js)
export const PI = 3.14159;
export function calculateArea(radius) {
return PI * radius * radius;
}
export default class Circle {
constructor(radius) {
this.radius = radius;
}
area() {
return calculateArea(this.radius);
}
}
// Importing (file: app.js)
import Circle, { PI, calculateArea } from './module.js';