Skip to content

JavaScript

This content is for Frontend. Switch to the latest version for up-to-date documentation.

JavaScript is a versatile, high-level, and interpreted programming language. In the context of frontend development, it is the “brain” of the web page, enabling interactivity beyond static HTML and CSS.

To master JavaScript, it is crucial to distinguish between the language itself (ECMAScript) and the Web APIs provided by the browser environment.


Part 1: Language Fundamentals (ECMAScript)

Section titled “Part 1: Language Fundamentals (ECMAScript)”

These concepts are the core of JavaScript. They work the same way whether you are running code in a browser, on a server (Node.js), or in other environments.

Variables store data. Modern JavaScript uses let and const.

  • const: For values that won’t be reassigned. (Default choice).
  • let: For values that will be reassigned.
  • var: Legacy variable declaration. Avoid using it due to hoisting and lack of block scope.
const birthYear = 1995; // Cannot be changed
let age = 30; // Can be changed
age = 31;
if (true) {
let blockScoped = 'I only exist here';
var functionScoped = 'I leak out of this block';
}
// console.log(blockScoped); // ReferenceError
console.log(functionScoped); // works

JavaScript has 7 primitive types and an Object type.

  • Primitives: String, Number, Boolean, null, undefined, Symbol, BigInt.
  • Objects: Objects, Arrays, Functions.
const name = 'Alice'; // String
const total = 42; // Number
const isStudent = true; // Boolean
let data = null; // null (intentional empty value)
let result; // undefined (not yet assigned)

Functions are blocks of code designed to perform a particular task.

  • Function Declaration: Hoisted, can be called before they are defined.
  • Function Expression: Not hoisted.
  • Arrow Functions: Concise syntax, useful for callbacks. Note: They do not have their own this.
// Declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow Function
const multiply = (a, b) => a * b;
// Higher-Order Function (takes another function as argument)
[1, 2, 3].forEach((num) => console.log(num));

Arrays are used to store lists of data.

Common methods:

  • map(): Transforms every element, returns a new array.
  • filter(): Returns a new array with elements that pass a test.
  • reduce(): Aggregates the array into a single value.
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, current) => acc + current, 0); // 15
// Useful for checking conditions
const hasLargeNum = numbers.some((n) => n > 10); // false
const allPositive = numbers.every((n) => n > 0); // true

Strings in JavaScript are immutable, meaning methods return a new string rather than modifying the original.

  • Template Literals: Use backticks (`) for interpolation and multi-line strings.
  • Methods: trim(), includes(), split(), slice().
const str = ' JavaScript is Awesome! ';
console.log(str.trim()); // "JavaScript is Awesome!"
console.log(str.includes('Script')); // true
console.log(str.toLowerCase()); // " javascript is awesome! "
const words = str.trim().split(' '); // ["JavaScript", "is", "Awesome!"]
const firstWord = str.trim().slice(0, 10); // "JavaScript"

Objects are used to store keyed collections. Classes (ES6) are syntactic sugar over prototypal inheritance.

// Object Literal
const user = {
name: 'John',
greet() {
console.log(`Hello, I'm ${this.name}`);
},
};
// Class (Template for objects)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog('Mitzie');
d.speak(); // "Mitzie barks."

JavaScript is single-threaded, meaning it can only do one thing at a time. Asynchronous patterns allow it to handle long-running tasks (like fetching data) without freezing the UI.

  • Promises: Represents a value that will be available in the future.
  • Async/Await: Modern, readable way to handle Promises.
// Using Promises
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data loaded!'), 1000);
});
};
// Using Async/Await
async function displayData() {
console.log('Loading...');
const result = await fetchData();
console.log(result); // "Data loaded!"
}

Browser APIs are tools provided by the browser environment. These are not part of the core JavaScript language, but they are accessible via JavaScript when running in a browser.

The DOM is a structural representation of the HTML document. JavaScript uses it to change content and styles.

// Selecting elements
const title = document.querySelector('h1');
const buttons = document.querySelectorAll('.btn');
// Modifying content and style
title.textContent = 'New Title';
title.style.color = 'blue';
// Creating and Appending
const newDiv = document.createElement('div');
newDiv.innerHTML = '<p>Newly created paragraph</p>';
document.body.appendChild(newDiv);

Events allow you to make the page interactive by responding to user actions.

const btn = document.querySelector('#submit');
btn.addEventListener('click', (event) => {
console.log('Button clicked!');
console.log('Event details:', event);
});

The modern way to make network requests (AJAX).

async function getUser() {
try {
const response = await fetch('https://api.github.com/users/octocat');
if (!response.ok) throw new Error('User not found');
const data = await response.json();
console.log(data.login);
} catch (error) {
console.error('Error fetching data:', error);
}
}

Used to save data in the user’s browser.

  • localStorage: Persists even after the browser is closed.
  • sessionStorage: Persists only for the duration of the page session.
// Saving data
localStorage.setItem('theme', 'dark');
// Retrieving data
const currentTheme = localStorage.getItem('theme');
console.log(currentTheme); // 'dark'

ConceptLayerExamples
Variables/LoopsLanguage (Engine)let, for, if
Logic/MathLanguage (Engine)Math.random(), typeof
DOMBrowser APIdocument.body, window.innerWidth
NetworkBrowser APIfetch(), XMLHttpRequest
TimersBrowser APIsetTimeout(), setInterval()
StorageBrowser APIlocalStorage, IndexedDB
Built with passion by Ngineer Lab