DSC 106: Introduction to Data Visualization
Understanding function and variable execution
console.log("Start");
function greet() {
console.log("Hello!");
}
greet();
console.log("End");
Understanding how JavaScript handles variables
console.log(myVar); // undefined
var myVar = 10;
console.log(myVar); // 10
// JavaScript Hoists Declarations
var myVar;
console.log(myVar); // undefined
myVar = 10;
console.log(myVar); // 10
console.log(myLet); // ReferenceError
let myLet = 20;
console.log(myLet);
Why? `let` and `const` do not initialize until execution reaches the declaration (Temporal Dead Zone).
Understanding the Call Stack
function first() {
console.log("First");
second();
console.log("First End");
}
function second() {
console.log("Second");
}
console.log("Start");
first();
console.log("End");
The Call Stack follows Last-In, First-Out (LIFO).
// Stack Operations
CALL: first() -> adds to stack
CALL: second() -> adds to stack
RETURN: second() -> removes from stack
RETURN: first() -> removes from stack
How async functions work and why they are useful
async function fetchData() {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
}
fetchData();
Key Point: `await` makes JavaScript wait for the fetch request to complete.
// Using Promises
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Using Async/Await
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
Why use Async/Await? More readable, avoids deeply nested `.then()` calls.
async function fetchData() {
try {
let response = await fetch("https://invalid-url.com/data");
if (!response.ok) throw new Error("Failed to fetch data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error.message);
}
}
fetchData();
Tip: Always use `try/catch` to handle errors properly.
Async/Await is useful for:
Understanding the JavaScript Event Loop
console.log("Start");
setTimeout(() => console.log("Inside setTimeout"), 0);
Promise.resolve().then(() => console.log("Promise resolved"));
console.log("End");
The Event Loop processes tasks in this order:
Fetch API & Promises in JavaScript
console.log("Start");
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(data => console.log("Data Loaded:", data));
console.log("End");
The Event Loop processes **fetch requests** as follows:
Understanding JavaScript Function Syntax and Execution
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice"));
Key Points: Uses `function` keyword, takes parameters, and returns a value.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Why use arrow functions? Shorter syntax, lexical `this` binding.
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
Key Difference: Function expressions are assigned to variables and cannot be called before their definition.
function operate(a, b, operation) {
return operation(a, b);
}
console.log(operate(10, 5, (x, y) => x - y)); // 5
Functions that take other functions as arguments or return functions.
Best Practices for Structuring Code
// Global Function (Avoid excessive usage)
function globalFunction() {
console.log("I am global!");
}
// Local Function (Scoped inside another function)
function localScope() {
function innerFunction() {
console.log("I am local!");
}
innerFunction();
}
Best Practice: Keep functions local unless they need global access.
// Business Logic (Pure Functions)
function calculateTotal(price, tax) {
return price + (price * tax);
}
// Event Handler (DOM Interaction)
document.getElementById("buyBtn").addEventListener("click", () => {
alert("Purchase successful!");
});
// API Call Function
async function fetchData() {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
}
Best Practice: Keep logic, event handlers, and API calls separate.
const ShoppingCart = (function() {
let cart = [];
function addItem(item) {
cart.push(item);
console.log(cart);
}
return {
add: addItem
};
})();
ShoppingCart.add("Laptop");
Why? Prevents polluting global scope and maintains data encapsulation.
// utils.js (Exporting Functions)
export function add(a, b) {
return a + b;
}
// main.js (Importing Functions)
import { add } from './utils.js';
console.log(add(2, 3)); // 5
Why? Helps maintain modular, reusable code.
// File Structure
/project-root
/js
/modules
cart.js
user.js
/utils
helpers.js
app.js
index.html
Tip: Place functions inside appropriate folders to keep code maintainable.
Step-by-step guide to building interactive charts
// Select the container and append an SVG
const svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 300);
console.log("SVG created!");
Why? Every D3 visualization starts with an svg container.
const data = [10, 30, 50, 70, 90];
// Bind data and create circles
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => d)
.attr("cy", 100)
.attr("r", 10)
.attr("fill", "blue");
Why? D3 binds data to DOM elements dynamically.
const xScale = d3.scaleLinear()
.domain([0, 100])
.range([0, 400]);
const xAxis = d3.axisBottom(xScale);
svg.append("g")
.attr("transform", "translate(50, 200)")
.call(xAxis);
Why? Scales map data values to screen coordinates.
svg.selectAll("circle")
.on("mouseover", function() {
d3.select(this).attr("fill", "red");
})
.on("mouseout", function() {
d3.select(this).attr("fill", "blue");
});
Why? Event listeners make visualizations interactive.
svg.selectAll("circle")
.transition()
.duration(1000)
.attr("r", 20);
Why? Smooth animations enhance user experience.
Real-world interactive visualizations made with D3
A curated gallery of different D3.js visualizations.
An interactive visualization of baby name trends.
A famous election visualization from The New York Times.
Explore hundreds of D3.js visualizations on CodePen.
Learn how to build interactive D3 charts step by step.