JavaScript

#2
TIOBE#6
PYPL#3
GitHub#2
RedMonk#1
IEEESpectrum#3
JetBrains#1
programming languageweb developmentfrontendbackendfunctionalobject-oriented

Programming Language

JavaScript

Overview

JavaScript is an essential dynamic programming language for web development.

Details

JavaScript is a prototype-based object-oriented programming language developed by Brendan Eich in 1995. Originally designed for client-side processing in web browsers, the advent of Node.js made server-side development possible, making it one of the most widely used programming languages today. It features dynamic typing, first-class functions, and prototype-based inheritance, excelling at event-driven programming and asynchronous processing using callback functions. Continuously evolving based on the ECMAScript standard, JavaScript is utilized across a wide range of applications from frontend, backend, mobile, to desktop application development through modern syntax and a rich library ecosystem.

Code Examples

Hello World

// Basic output
console.log("Hello, World!");

// Output using variables
const message = "Hello, JavaScript!";
console.log(message);

// Output using template literals
const name = "John";
const age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);

// Browser alert display
alert("Hello, JavaScript!");

Variables and Data Types

// Variable declarations
let number = 42;           // Number
const text = "Hello";      // String
let isTrue = true;         // Boolean
let array = [1, 2, 3];     // Array
let obj = { name: "John" }; // Object

// Check data types
console.log(typeof number);  // "number"
console.log(typeof text);    // "string"
console.log(typeof isTrue);  // "boolean"
console.log(typeof array);   // "object"
console.log(typeof obj);     // "object"

// Array operations
array.push(4);               // Add element
console.log(array.length);   // Array length
console.log(array[0]);       // Access first element

Conditional Statements

// Basic if statement
const score = 85;
let grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else {
    grade = "D";
}

console.log(`Score: ${score}, Grade: ${grade}`);

// Ternary operator
const result = score >= 80 ? "Pass" : "Fail";
console.log(result);

// Switch statement
const day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("Almost weekend");
        break;
    default:
        console.log("Keep going!");
}

Arrays and Objects

// Array operations
const fruits = ["apple", "banana", "orange"];
fruits.push("grape");        // Add element
console.log(`Fruit list: ${fruits}`);

// Array iteration
fruits.forEach((fruit, index) => {
    console.log(`${index}: ${fruit}`);
});

// Array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);          // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0);   // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15

// Object operations
const person = {
    name: "John Doe",
    age: 30,
    city: "Tokyo",
    greet: function() {
        return `Hello, I'm ${this.name}`;
    }
};

person.job = "Engineer";  // Add property
console.log(person.greet());
console.log(`Job: ${person.job}`);

// Object destructuring
const { name, age } = person;
console.log(`Name: ${name}, Age: ${age}`);

Loops and Iteration

// for loop
for (let i = 0; i < 5; i++) {
    console.log(`Count: ${i}`);
}

// for...of loop for arrays
const colors = ["red", "blue", "green"];
for (const color of colors) {
    console.log(`Color: ${color}`);
}

// for...in loop for objects
const student = { name: "John", age: 20, grade: "A" };
for (const key in student) {
    console.log(`${key}: ${student[key]}`);
}

// while loop
let count = 0;
while (count < 3) {
    console.log(`while count: ${count}`);
    count++;
}

// Array method iteration
const items = ["a", "b", "c"];
items.forEach((item, index) => {
    console.log(`${index}: ${item}`);
});

Function Definition and Calling

// Basic function
function greet(name) {
    return `Hello, ${name}!`;
}

// Function expression
const add = function(a, b) {
    return a + b;
};

// Arrow function
const multiply = (a, b) => a * b;

// Default parameters
const calculateArea = (width, height = 10) => {
    return width * height;
};

// Function calls
console.log(greet("Alice"));
console.log(add(5, 3));
console.log(multiply(4, 7));
console.log(calculateArea(5)); // height uses default value 10

// Higher-order function example
const processNumbers = (numbers, callback) => {
    return numbers.map(callback);
};

const squares = processNumbers([1, 2, 3, 4], n => n * n);
console.log(squares); // [1, 4, 9, 16]

Classes and Object-Oriented Programming

// ES6 class syntax
class Car {
    constructor(make, model, year) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.mileage = 0;
    }
    
    drive(distance) {
        this.mileage += distance;
        console.log(`Drove ${distance}km. Total mileage: ${this.mileage}km`);
    }
    
    getInfo() {
        return `${this.year} ${this.make} ${this.model}`;
    }
    
    // Getters and setters
    get description() {
        return `${this.getInfo()} (Mileage: ${this.mileage}km)`;
    }
    
    set totalMileage(miles) {
        if (miles >= 0) {
            this.mileage = miles;
        }
    }
}

// Inheritance
class ElectricCar extends Car {
    constructor(make, model, year, batteryCapacity) {
        super(make, model, year);
        this.batteryCapacity = batteryCapacity;
        this.charge = 100;
    }
    
    chargeBattery() {
        this.charge = 100;
        console.log("Battery charged");
    }
}

// Class usage
const myCar = new Car("Toyota", "Prius", 2022);
console.log(myCar.getInfo());
myCar.drive(50);
console.log(myCar.description);

const electricCar = new ElectricCar("Tesla", "Model 3", 2023, 75);
electricCar.drive(30);

Asynchronous Programming

// Promise
const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const success = Math.random() > 0.5;
            if (success) {
                resolve("Data fetched successfully");
            } else {
                reject("An error occurred");
            }
        }, 1000);
    });
};

// Using Promise
fetchData()
    .then(data => console.log(data))
    .catch(error => console.error(error));

// async/await
async function getData() {
    try {
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

getData();

// Parallel execution of multiple async operations
const urls = [
    'https://api.example1.com/data',
    'https://api.example2.com/data'
];

Promise.all(urls.map(url => fetch(url)))
    .then(responses => Promise.all(responses.map(r => r.json())))
    .then(data => console.log('All data:', data))
    .catch(error => console.error('Error:', error));

DOM Manipulation (Browser Environment)

// Element selection
const title = document.getElementById('title');
const buttons = document.querySelectorAll('.button');
const firstParagraph = document.querySelector('p');

// Element creation and addition
const newDiv = document.createElement('div');
newDiv.textContent = 'New element';
newDiv.className = 'new-element';
document.body.appendChild(newDiv);

// Event listener addition
const button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
    console.log('Button clicked');
    event.preventDefault(); // Prevent default behavior
});

// Style changes
title.style.color = 'blue';
title.style.fontSize = '24px';

// Class manipulation
newDiv.classList.add('active');
newDiv.classList.remove('inactive');
newDiv.classList.toggle('highlight');

// Form handling
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(form);
    const data = Object.fromEntries(formData);
    console.log('Form data:', data);
});

Special Features

Destructuring Assignment

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first);  // 1
console.log(second); // 2
console.log(rest);   // [3, 4, 5]

// Object destructuring
const user = { name: "John", age: 25, city: "Tokyo" };
const { name, age, city = "Unknown" } = user;
console.log(`${name}, ${age} years old, lives in ${city}`);

// Destructuring in function parameters
const displayUser = ({ name, age }) => {
    console.log(`Name: ${name}, Age: ${age}`);
};
displayUser(user);

Spread Operator

// Array spread
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

// Object spread
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }

// Spread in function arguments
const numbers = [1, 2, 3, 4, 5];
const max = Math.max(...numbers); // 5
console.log(max);

Module System

// export
// utils.js
export const PI = 3.14159;
export function add(a, b) {
    return a + b;
}
export class Calculator {
    multiply(a, b) {
        return a * b;
    }
}

// Default export
export default function subtract(a, b) {
    return a - b;
}

// import
// main.js
import subtract, { PI, add, Calculator } from './utils.js';
import * as Utils from './utils.js';

console.log(PI);
console.log(add(5, 3));
console.log(subtract(10, 4));

const calc = new Calculator();
console.log(calc.multiply(6, 7));

Versions

Version Official Name Release Date Key Features
ES2024 (ES15) ECMAScript 2024 2024-06 Object.groupBy(), Well-Formed Unicode Strings
ES2023 (ES14) ECMAScript 2023 2023-06 Array findLast(), toSorted(), Hashbang Grammar
ES2022 (ES13) ECMAScript 2022 2022-06 Top-level await, Private fields, at() method
ES2021 (ES12) ECMAScript 2021 2021-06 String replaceAll(), Promise.any(), Logical Assignment
ES2020 (ES11) ECMAScript 2020 2020-06 Optional chaining, Nullish coalescing, BigInt
ES2019 (ES10) ECMAScript 2019 2019-06 Array flat(), Object.fromEntries()
ES2018 (ES9) ECMAScript 2018 2018-06 Async iteration, Rest/Spread properties
ES2017 (ES8) ECMAScript 2017 2017-06 async/await, Object.entries(), String padding
ES2016 (ES7) ECMAScript 2016 2016-06 Array includes(), Exponentiation operator
ES2015 (ES6) ECMAScript 2015 2015-06 Classes, Modules, Arrow functions, let/const

Reference Pages

Official Documentation

Learning Resources

Development Tools and Libraries

  • Node.js - Server-side JavaScript runtime
  • npm - Node.js package manager
  • Babel - JavaScript transpiler
  • ESLint - JavaScript linter
  • Prettier - Code formatter

Frameworks and Libraries