JavaScript Syntax
Now that you know what JavaScript is and how to include it in a webpage, it's time to learn how to write it.
This lesson covers variables, data types, arrays, objects, and functions β the core building blocks you'll use in every D3 chart. Packed with interactive examples and exercises.
π¦ Variables: const and let
Like most programming languages, JavaScript stores values in variables. You'll use two keywords to create them:
constβ creates a variable that cannot be reassigned. Use this by default.letβ creates a variable that can be reassigned. Use it only when you need to change the value later.
var in older code. It's the legacy way of declaring variables β don't use it.// const = constant, cannot be reassigned const name = "Alice"; console.log(name); // let = can be reassigned let score = 10; console.log(score); score = 20; // β This works console.log(score); // name = "Bob"; // β This would throw an error!
Note: the sandbox above shows code on the left and output on the right. The output panel is called the console β we cover it in the Developer Tools lesson.
π§± Primitive Types
JavaScript has a few basic data types called primitives. These are the simplest building blocks of the language.
Note: You can check the type of any value using typeof:
console.log(typeof "hello"); // string console.log(typeof 42); // number console.log(typeof true); // boolean console.log(typeof undefined); // undefined console.log(typeof null); // object (a famous JS quirk!)
π Arrays
An array is an ordered list of values. In D3, your data will almost always be an array. Think of it like a list where values can have mixed types.
Creating and accessing
An array is created using square brackets ([]). Once it's there you can access its elements by their index using array[index]:
const numbers = [10, 20, 30, 40]; const fruits = ["apple", "banana", "cherry"]; // Access by index (starts at 0!) console.log(numbers[0]); // 10 console.log(numbers[2]); // 30 console.log(fruits[1]); // banana
Arrays are zero-indexed β the first element is at position 0, not 1. This trips up everyone at first!
Useful properties and methods
Every array comes with built-in properties and methods. Properties are values you can read (like .length), while methods are functions you can call (like .includes()).
You access them with a dot: myArray.length gives you the number of items, myArray.includes("apple") checks if "apple" is in the array.
Here are a few you'll use often. We'll cover the most powerful ones (map, filter) in detail later.
const numbers = [5, 2, 8, 1, 9]; // Get the length console.log(numbers.length); // 5 // Check if element exists console.log(numbers.includes(8)); // true // Find index of element console.log(numbers.indexOf(8)); // 2 // Join into a string console.log(numbers.join(" - "));