JavaScript adds real-time calculation and behavior to frontend interfaces. Use it when a layout, animation, or visual response depends on user input, changing dimensions, incoming data, or logic that CSS cannot express alone. Arithmetic operators and the Math object let code calculate values, while browser APIs let those results update the page immediately. section 1.3.2 section 1.3.3 section 6.5.7
For everyday UI math, JavaScript supplies:
- Arithmetic with +, -, *, /, %, and ** for dimensions, animation frames, and computed values. section 1.3.2 section 2.1.1
- Math.round(), Math.floor(), and Math.ceil() when a calculation needs a whole-number result; Math.random() for randomized effects or game logic. section 1.3.2
- Math.max(), Math.min(), Math.abs(), Math.pow(), Math.sqrt(), and trigonometric functions for bounds, change, distance, angles, curves, and circular motion. section 1.3.2
- Explicit comparisons such as >=, <, !==, and === for conditions, including responsive breakpoints and input validation. section 1.4.6
Allocate dashboard space from runtime data
When widget weights arrive from an API, JavaScript can create the widgets, total their weights, measure the container and gaps, then calculate each widget’s flex-basis. CSS can lay out known values, but JavaScript handles data-dependent sizing and conditional decisions at runtime. section 6.5.7 section 1.3.3
Listing 6.6 Setting flex-basis dynamically
const widgetData = [ #1
{ name: 'Widget A', weight: 2 }, #1
{ name: 'Widget B', weight: 1 }, #1
{ name: 'Widget C', weight: 3 }, #1
{ name: 'Widget D', weight: 4 }, #1
]; #1
#1
const dash = document.getElementById('dashboard'); #2
const gap = parseFloat(getComputedStyle(dash).gap) || 0; #2
widgetData.forEach(widget => { #3
const el = document.createElement('div');
el.className = 'widget';
el.textContent = widget.name;
dash.appendChild(el);
});
const widgets = dash.querySelectorAll('.widget'); #4
const totalWeight = widgetData.reduce((sum, w) => #4
sum + w.weight, 0); #4
const widgetCount = widgets.length;
const totalGapWidth = gap * (widgetCount - 1); #5
const containerWidth = dash.clientWidth; #5
const usableWidth = containerWidth - totalGapWidth; #5
widgets.forEach((widget, i) => { #6
const weight = widgetData[i].weight; #6
const width = (weight / totalWeight) * usableWidth; #6
widget.style.flexBasis = `${width}px`; #6
}); #6
Inspect a complete weighted-widget calculation that derives usable width from the container and gaps before distributing space. section 6.5.7











