Student-friendly JavaScript reference with examples
In Tinkr, you write code that takes input, processes it, and produces output.
Input values are available as input1, input2, input3, etc:
input1 // First piece of data
input2 // Second piece of data
Do something with the input:
const result = input1 * 2;
Every exercise must end with a variable called output containing your answer:
const output = result;
Tinkr checks this variable to see if your solution is correct.
// Get input
const number = input1;
// Process it
const doubled = number * 2;
// Create output
const output = doubled;
Programming requires exact precision - every bracket, semicolon, and keyword must be exactly right.
Brackets must match:
{ needs } ( needs ) [ needs ] Semicolons end statements:
const age = 25;
let name = "Alice";
Capitalization matters:
const is correct Const or CONST will cause errors Quotes must match:
"hello" is correct "hello' will cause an error // Wrong - missing semicolon
const x = 5
// Right
const x = 5;
// Wrong - mismatched brackets
if (x > 0 {
console.log(x);
}
// Right
if (x > 0) {
console.log(x);
}
Type code carefully. Pay attention to every character.
A variable is like a box where you can store information. You give it a name so you can find it later.
const myName = 'Alice';
const myAge = 15;
const likesPizza = true;
// Now you can use these values later:
console.log(myName); // Shows: Alice
Variables store information that you can use later. Think of them like labeled boxes that hold data.
const variableName = value;
Use const to create a variable whose value won’t change.
const playerName = "Alex";
const maxScore = 100;
const isActive = true;
The pattern is:
const keyword = sign
Use let to create a variable whose value can change.
let score = 0;
let lives = 3;
To change the value, write the variable name, =, and the new value:
score = score + 10;
This takes the current score, adds 10, and stores the result back in score.
You can update the same variable multiple times:
let counter = 0;
counter = counter + 1; // now 1
counter = counter + 1; // now 2
Notice: Don’t use let when updating - only when first creating the variable.
Choose between const and let based on whether the value will change.
const playerName = "Alex";
const maxLevel = 10;
Use const when the value won’t change. Player names, prices, limits, and other fixed values should use const.
let score = 0;
let currentLevel = 1;
Use let when the value might change later. Scores, counters, and other changing values should use let.
Ask yourself: “Will this value change during my program?”
let const Text values in programming are called strings. They must be wrapped in quotes.
const city = "Paris";
const greeting = "Hello";
const message = "Welcome to coding!";
const name = "Alice";
const output = name; // output now contains "Alice"
Numbers in programming don’t need quotes. They can be positive, negative, or decimals.
const temperature = 72;
const score = -5;
const price = 19.99;
const age = 25;
const output = age; // output now contains 25
You can use numbers directly in calculations or store them in variables first.
JavaScript has four basic math operators for calculations.
const sum = 5 + 3; // 8 (addition)
const difference = 10 - 4; // 6 (subtraction)
const product = 6 * 7; // 42 (multiplication)
const quotient = 20 / 4; // 5 (division)
const price = 10;
const quantity = 3;
const total = price * quantity; // 30
You can use these operators with numbers directly or with variables containing numbers.
Parentheses () force operations to happen first. Everything inside parentheses is calculated before anything outside.
For (4 + 1) * 3:
4 + 1 = 5 (inside parentheses) 5 * 3 = 15 (multiply result) const result1 = 6 + 3 * 4; // 18 (multiplication first)
const result2 = (6 + 3) * 4; // 36 (addition first)
const average = (x + y) / 2;
const total = (a + b) * multiplier;
Use parentheses when you need to add or subtract before multiplying or dividing.
The Math.round() function rounds a number to the nearest integer.
Math.round(4.5); // 5
Math.round(4.4); // 4
Math.round(7.8); // 8
To round to 2 decimal places (like money):
Math.round(amount * 100) / 100
115.7625 * 100 = 11576.25 Math.round(11576.25) = 11576 11576 / 100 = 115.76 const price = 19.999;
const rounded = Math.round(price * 100) / 100; // 20.00
const total = 45.678;
const money = Math.round(total * 100) / 100; // 45.68
When dealing with money or percentages, you often get long decimals. Rounding keeps values clean.
The + operator joins strings together. This is called “concatenation”.
const greeting = "Hello" + "World"; // "HelloWorld"
To add a space between words, include " " (a string with just a space):
const message = "Good" + " " + "Morning"; // "Good Morning"
const firstName = "John";
const lastName = "Smith";
const fullName = firstName + " " + lastName; // "John Smith"
You can chain multiple + operations. They work left to right:
greeting + " " + name greeting + " " creates “Hello “ "Hello " + name creates “Hello Alice”
Use square brackets [] with an index number to get a single character from a string.
const word = "Hello";
const first = word[0]; // "H"
const second = word[1]; // "e"
const third = word[2]; // "l"
0 1 2 Word: "Code"
Index: 0123
C = index 0
o = index 1
d = index 2
e = index 3
const name = "Alice";
const firstChar = name[0]; // "A"
Every string has a .length property that tells you how many characters it contains.
const word = "Hello";
const size = word.length; // 5
"" has length 0 const text = "JavaScript";
const count = text.length; // 10
const sentence = "Hello World";
const total = sentence.length; // 11 (space counts!)
const empty = "";
const zero = empty.length; // 0
The .toUpperCase() method converts all characters in a string to uppercase.
const text = "hello";
const loud = text.toUpperCase(); // "HELLO"
const city = "paris";
const capital = city.toUpperCase(); // "PARIS"
const phrase = "good morning";
const emphasized = phrase.toUpperCase(); // "GOOD MORNING"
const mixed = "Hello World!";
const result = mixed.toUpperCase(); // "HELLO WORLD!"
The .replace() method replaces text in a string.
const text = "I hate broccoli";
const newText = text.replace("hate", "love");
// Result: "I love broccoli"
string.replace(searchFor, replaceWith)
searchFor: The text to find replaceWith: The text to replace it with const message = "Use the old system";
const updated = message.replace("old", "new");
// "Use the new system"
const text = "cat and cat";
const result = text.replace("cat", "dog");
// "dog and cat" (only first replaced)
The .slice() method extracts part of a string.
const word = "Hello";
const part = word.slice(1); // "ello" (from index 1 to end)
string.slice(startIndex)
Starts at startIndex and goes to the end of the string.
const animal = "cat";
const rest = animal.slice(1); // "at"
const text = "JavaScript";
const partial = text.slice(4); // "Script"
const greeting = "Hello World";
const end = greeting.slice(6); // "World"
const word = "Hello";
const middle = word.slice(1, 4); // "ell" (from index 1 to 4, not including 4)
You can use + to combine strings and numbers. The number automatically becomes text.
const name = "Alice";
const age = 25;
const message = name + " is " + age; // "Alice is 25"
When you use + with strings, numbers convert to text automatically:
const score = 100;
const text = "Score: " + score; // "Score: 100"
const firstName = "John";
const points = 50;
const info = firstName + " has " + points + " points";
// "John has 50 points"
firstName + " has " creates “John has “ "John has " + points creates “John has 50” "John has 50" + " points" creates “John has 50 points” Strings compare in alphabetical order, like words in a dictionary.
const result = "Apple" < "Banana"; // true (A comes before B)
< checks if left comes before right > checks if left comes after right === checks if they’re exactly equal "Cat" < "Dog" // true (C before D)
"Zebra" < "Apple" // false (Z after A)
"Hello" === "Hello" // true (exactly equal)
Case matters: Uppercase letters come before lowercase
"Apple" < "apple" // true (uppercase comes first)
First different letter decides:
"Car" < "Cat" // true (r comes before t)
const cityA = "Boston";
const cityB = "Denver";
const bostonFirst = cityA < cityB; // true
The .split() method breaks a string into an array of parts.
const sentence = "hello world";
sentence.split(" "); // ["hello", "world"]
You provide a separator (like a space), and split() breaks the string at each occurrence:
const text = "a,b,c";
text.split(","); // ["a", "b", "c"]
const phrase = "Learning To Code";
const words = phrase.split(" "); // ["Learning", "To", "Code"]
const input = "JavaScript is fun";
const words = input.split(" ");
for (const word of words) {
console.log(word);
}
// Prints: "JavaScript", "is", "fun"
The .toLowerCase() method converts a string to all lowercase letters.
Syntax:
string.toLowerCase()
Returns: A new string with all lowercase letters (doesn’t change the original)
Example:
const text = 'JavaScript';
const lower = text.toLowerCase();
console.log(lower); // 'javascript'
console.log(text); // 'JavaScript' (original unchanged)
Common Use - Case-Insensitive Comparison:
const userInput = 'HELLO';
const expected = 'hello';
if (userInput.toLowerCase() === expected.toLowerCase()) {
console.log('Match!'); // This runs
}
Common Use - Case-Insensitive Search:
const text = 'JavaScript is Great';
const search = 'JAVA';
if (text.toLowerCase().includes(search.toLowerCase())) {
console.log('Found it!'); // This runs
}
Doesn’t Modify Original:
const name = 'Alice';
name.toLowerCase(); // Returns 'alice' but doesn't change name
console.log(name); // Still 'Alice'
// Save the result if you need it:
const lowerName = name.toLowerCase();
console.log(lowerName); // 'alice'
Counterpart:
.toUpperCase() converts to all uppercase letters
The .includes() method checks if a string contains another string (substring).
Syntax:
string.includes(searchString)
Returns: true if found, false if not found
Example:
const text = 'JavaScript is awesome';
text.includes('Java'); // true
text.includes('Python'); // false
text.includes('script'); // true
text.includes('JAVA'); // false (case-sensitive!)
Case-Sensitive:
.includes() is case-sensitive, so convert both strings to lowercase for case-insensitive search:
const text = 'JavaScript';
const search = 'java';
text.toLowerCase().includes(search.toLowerCase()); // true
Use Case - Filtering:
const languages = ['JavaScript', 'Python', 'Java', 'Ruby'];
const searchText = 'java';
for (const lang of languages) {
if (lang.toLowerCase().includes(searchText.toLowerCase())) {
console.log(lang); // Shows: JavaScript, Java
}
}
Empty String:
Every string includes an empty string:
'hello'.includes(''); // true
Arrays store multiple values in a single variable. Values are separated by commas and wrapped in square brackets.
const fruits = ["apple", "banana", "orange"];
const numbers = [10, 20, 30, 40, 50];
const mixed = ["hello", 42, true]; // Can mix types!
Array positions start at 0. Use square brackets with the position number to access an element.
numbers[0] // gets first element (10)
numbers[1] // gets second element (20)
numbers[2] // gets third element (30)
You can store an array element in a variable:
const output = numbers[2];
The .push() method adds an element to the end of an array.
const numbers = [1, 2, 3];
numbers.push(4);
// numbers is now [1, 2, 3, 4]
const result = [];
for (const val of [1, 2, 3, 4]) {
if (val % 2 === 0) {
result.push(val);
}
}
// result is [2, 4]
[] push() const evens = [];
evens.push(2); // [2]
evens.push(4); // [2, 4]
evens.push(6); // [2, 4, 6]
The .unshift() method adds an element to the beginning of an array.
const numbers = [2, 3, 4];
numbers.unshift(1);
// numbers is now [1, 2, 3, 4]
push() adds to the end unshift() adds to the start const arr = [];
arr.push(3); // [3]
arr.push(4); // [3, 4]
arr.unshift(2); // [2, 3, 4]
arr.unshift(1); // [1, 2, 3, 4]
Use unshift() in a loop to reverse:
const original = [1, 2, 3];
const reversed = [];
for (const num of original) {
reversed.unshift(num);
}
// reversed is [3, 2, 1]
If statements let you run code only when a condition is true.
if (condition) {
// This code runs only if condition is true
}
A common pattern is to set a default value, then change it if a condition is met:
let message = 'default value';
if (score > 80) {
message = 'excellent';
}
let age = 20;
let status = 'minor';
if (age >= 18) {
status = 'adult';
}
// status is now 'adult'
The condition must be something that evaluates to true or false.
Comparison operators compare two values and return true or false.
a > b // greater than
a >= b // greater than or equal to
a < b // less than
a <= b // less than or equal to
a === b // exactly equal (same type and value)
a !== b // not equal (different type or value)
15 > 10 // true
8 >= 8 // true (equal counts!)
5 < 12 // true
20 === 20 // true
5 !== 10 // true (they are different)
const temp = 75;
const isWarm = temp > 20; // true
const isCool = temp <= 15; // false
const isExact = temp === 75; // true
Strict equality operators check if values are exactly the same, including their type.
5 === 5 // true (same type and value)
5 === '5' // false (number vs string)
'hello' === 'hello' // true
true === 1 // false (boolean vs number)
Returns true only if both type AND value match.
5 !== 10 // true (different values)
5 !== '5' // true (different types)
'cat' !== 'cat' // false (exactly the same)
Returns true if type OR value are different.
const age = 18;
const input = '18';
age === input // false! (number !== string)
Always use === and !== in JavaScript to avoid surprises.
The typeof operator returns the type of a value as a string.
typeof 5 // 'number'
typeof 'hello' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
You can check if two values have the same type:
typeof input1 === typeof input2
const value1 = 5;
const value2 = '5';
typeof value1 // 'number'
typeof value2 // 'string'
typeof value1 === typeof value2 // false
const sameType = typeof input1 === typeof input2;
const isNumber = typeof age === 'number';
const isText = typeof name === 'string';
Logical operators combine multiple conditions.
Returns true only when BOTH conditions are true:
age >= 18 && hasLicense // must be 18 AND have license
Truth table:
true && true = true true && false = false false && true = false false && false = false
Returns true when AT LEAST ONE condition is true:
isWeekend || isHoliday // weekend OR holiday
Truth table:
true || true = true true || false = true false || true = true false || false = false Returns the opposite:
!isRaining // NOT raining (so it's dry)
Control evaluation order:
hasCard && (age >= 18 || hasPermission)
// Must have card AND (be 18 OR have permission)
A for-of loop goes through each element in an array, one by one.
for (const item of array) {
// code runs for each item
}
The variable (item) gets each value from the array:
const numbers = [10, 20, 30];
for (const num of numbers) {
console.log(num);
}
// Prints: 10, then 20, then 30
const names = ["Alice", "Bob", "Carol"];
for (const name of names) {
console.log(name);
}
const for the loop variable (it changes each iteration) When adding numbers or counting in a loop, start with 0 or an empty array.
let total = 0;
for (const num of [1, 2, 3]) {
total = total + num;
}
// total is now 6
let count = 0;
for (const item of array) {
if (condition) {
count = count + 1;
}
}
const result = [];
for (const item of array) {
if (condition) {
result.push(item);
}
}
The modulo operator % gives the remainder after division.
10 % 3 // 1 (10 ÷ 3 = 3 remainder 1)
15 % 4 // 3 (15 ÷ 4 = 3 remainder 3)
8 % 2 // 0 (8 ÷ 2 = 4 remainder 0)
Even numbers have no remainder when divided by 2:
4 % 2 === 0 // true (even)
7 % 2 === 0 // false (odd)
Odd numbers have remainder 1 when divided by 2:
5 % 2 === 1 // true (odd)
6 % 2 === 1 // false (even)
for (const num of [1, 2, 3, 4]) {
if (num % 2 === 0) {
console.log(num + " is even");
}
}
// Prints: "2 is even" and "4 is even"
A traditional for loop gives you both the index (position) and the value.
for (let i = 0; i < array.length; i++) {
// code runs for each index
}
let i = 0 - start counter at 0 i < array.length - continue while i is less than array length i++ - add 1 to i after each iteration const numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
console.log(i, numbers[i]);
}
// Prints:
// 0 10
// 1 20
// 2 30
Use for-i when you need:
The variable i IS the index itself:
if (array[i] > i) {
// element is greater than its position
}
Nested loops are loops inside loops. Use them for arrays inside arrays (2D arrays).
const grid = [[1, 2], [3, 4], [5, 6]];
for (const innerArray of grid) {
// innerArray is each sub-array
}
The outer loop goes through each sub-array.
for (const innerArray of grid) {
for (const num of innerArray) {
// num is each number in the sub-array
}
}
The inner loop goes through each element in the current sub-array.
let total = 0;
for (const subArray of [[1, 2], [3, 4]]) {
for (const value of subArray) {
total = total + value;
}
}
// total is 10 (1 + 2 + 3 + 4)
[1, 2] [3, 4] Functions are reusable blocks of code that take inputs and return outputs.
function functionName(parameter) {
return value;
}
function keyword starts the definition functionName is the name you choose parameter is the input variable return sends a value back function double(num) {
return num * 2;
}
const result = double(5); // 10
Write the function name followed by parentheses with the argument inside.
function isPositive(n) {
return n > 0;
}
const answer = isPositive(5); // true
Functions can take multiple inputs by separating parameters with commas.
function add(a, b) {
return a + b;
}
function multiply(x, y) {
return x * y;
}
const result = multiply(5, 3); // 15
All parameters are available inside the function body.
function subtract(a, b) {
return a - b;
}
subtract(10, 3); // 7
subtract(3, 10); // -7
The order you pass arguments must match the order of parameters.
function discount(price, percent) {
return price * (percent / 100);
}
const saved = discount(50, 20); // 10
To get a percentage, divide by 100 and multiply.
Scope determines where variables can be accessed in your code.
const taxRate = 0.08; // Available everywhere
Variables defined outside functions are global - they can be used anywhere.
function process(num) {
const double = num * 2; // Only exists in this function
return double + 10;
}
Variables created inside functions are local - they only exist inside that function.
const rate = 0.05;
function calculate(amount) {
return amount * rate; // Can read global 'rate'
}
Functions can access and use global variables.
const multiplier = 5; // Global
function transform(value) {
const result = value * multiplier; // Local variable using global
return result;
}
A recursive function is a function that calls itself to solve a problem by breaking it into smaller pieces.
function countdown(n) {
if (n === 0) {
return "Done!"; // Base case
}
return countdown(n - 1); // Recursive call
}
Every recursive function needs a base case - a condition where it stops calling itself:
if (years === 0) {
return principal;
}
Without a base case, the function would run forever!
The function calls itself with different values:
return countdown(n - 1); // Calls itself with smaller value
power(2, 3)
→ 2 * power(2, 2)
→ 2 * (2 * power(2, 1))
→ 2 * (2 * (2 * power(2, 0)))
→ 2 * (2 * (2 * 1)) // Base case returns 1
→ 8
Each call waits for the next one to finish, then uses that result.
function factorial(n) {
if (n === 0) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
factorial(5); // 120 (5 * 4 * 3 * 2 * 1)
Objects store related data using key-value pairs inside curly braces.
const dog = {breed: "Poodle", age: 3};
Each pair uses the format key: value, separated by commas.
const car = {
brand: "Honda",
year: 2019,
color: "red"
};
You can have as many properties as you need.
const person = {
name: "Alice", // string
age: 25, // number
student: true // boolean
};
Property values can be any data type: strings, numbers, booleans, arrays, or even other objects.
Access property values from an object using dot notation.
const item = {title: "Book", cost: 20};
item.title // "Book"
item.cost // 20
objectName.propertyName
. Once you access a property, you can use it like any other value:
const box = {width: 10, height: 5};
const area = box.width * box.height; // 50
const user = {name: "Bob", score: 100};
const greeting = "Hello " + user.name; // "Hello Bob"
const bonus = user.score + 50; // 150
You can change existing properties or add new ones using dot notation with the assignment operator.
const user = {age: 25};
user.age = 26; // Changes age to 26
const car = {brand: "Toyota"};
car.year = 2020; // Adds a new property
To add a new property, assign a value to a key that doesn’t exist yet.
const player = {name: "Alex", score: 100};
player.score = 150; // Change score
player.level = 3; // Add level
const item = {count: 5};
item.count = 10;
item.count // 10 (new value)
Objects can contain other objects as property values. This is called nesting.
const person = {
name: "Alice",
address: {
street: "Oak Ave",
city: "Portland"
}
};
Use multiple dots to go deeper:
person.address // {street: "Oak Ave", city: "Portland"}
person.address.city // "Portland"
person.address.street // "Oak Ave"
person person.address person.address.city const car = {
model: "Civic",
specs: {
color: "blue",
year: 2021
}
};
car.specs.year // 2021
Chain dots together to navigate through nested objects.
Object.values() takes an object and returns an array of just the values (not the keys).
const scores = {math: 85, science: 90, history: 78};
Object.values(scores); // [85, 90, 78]
const values = Object.values(scores);
// values is now [85, 90, 78]
Store the result in a variable to use it.
const prices = {apple: 2, banana: 1, orange: 3};
const priceList = Object.values(prices);
for (const price of priceList) {
console.log(price);
}
// Prints: 2, 1, 3
const numbers = {a: 10, b: 20, c: 30};
const vals = Object.values(numbers);
let total = 0;
for (const num of vals) {
total = total + num;
}
// total is 60
Finds the first element that matches a CSS selector.
const button = document.querySelector('button');
const box = document.querySelector('.box');
const header = document.querySelector('#header');
Returns the element if found, or null if no match exists.
Finds all elements that match a CSS selector. Returns a NodeList (array-like).
const buttons = document.querySelectorAll('button');
const boxes = document.querySelectorAll('.box');
for (const box of boxes) {
console.log(box);
}
Use a for…of loop to iterate through the results.
Gets or sets the text inside an element.
const heading = document.querySelector('h1');
// Set text
heading.textContent = 'Hello World!';
// Get text
const text = heading.textContent;
Use this for headings, paragraphs, divs, buttons, and most elements.
Gets or sets the value in an input field.
const input = document.querySelector('input');
// Get what user typed
const userText = input.value;
// Set the input value
input.value = 'Hello!';
// Clear the input
input.value = '';
Use .value for inputs, textareas, and selects.
Loops through each item in an array or NodeList.
const buttons = document.querySelectorAll('button');
for (const button of buttons) {
button.classList.add('styled');
}
Perfect for looping through querySelectorAll results.
Adds an event listener that runs code when an event happens.
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
Common events: ‘click’, ‘input’, ‘change’, ‘submit’, ‘keydown’.
The click event fires when an element is clicked.
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
Most commonly used event for making things interactive.
The input event fires every time the user types in an input field.
const input = document.querySelector('input');
const display = document.querySelector('.display');
input.addEventListener('input', function() {
display.textContent = input.value;
});
Use for live/real-time updates as user types.
Changes CSS styles on an element using JavaScript.
const box = document.querySelector('.box');
box.style.backgroundColor = 'blue';
box.style.color = 'white';
box.style.fontSize = '20px';
box.style.padding = '10px';
CSS properties use camelCase: background-color becomes backgroundColor.
Values are strings and usually need units (‘20px’, not 20).
Adds a CSS class to an element.
const button = document.querySelector('button');
button.classList.add('active');
button.classList.add('highlight', 'large'); // Add multiple
The element now has the class and gets its styles from CSS.
Removes a CSS class from an element.
const button = document.querySelector('button');
button.classList.remove('active');
button.classList.remove('highlight', 'large'); // Remove multiple
The element no longer has the class and loses its associated styles.
Toggles a CSS class - adds it if missing, removes it if present.
const button = document.querySelector('button');
button.addEventListener('click', function() {
button.classList.toggle('active');
});
// First click: adds 'active'
// Second click: removes 'active'
// Third click: adds 'active' again
Perfect for on/off states!
Creates a new HTML element (doesn’t add it to the page yet).
const newDiv = document.createElement('div');
const newButton = document.createElement('button');
const newParagraph = document.createElement('p');
// Set properties
newDiv.textContent = 'Hello!';
newDiv.classList.add('my-class');
// Add to page
document.body.appendChild(newDiv);
Adds an element as a child of another element.
const parent = document.querySelector('.container');
const newDiv = document.createElement('div');
newDiv.textContent = 'I am new!';
parent.appendChild(newDiv);
The new element appears at the end of the parent’s children.
Removes an element from the page completely.
const box = document.querySelector('.box');
box.remove();
// The box is now gone from the page
Commonly used with delete buttons:
deleteBtn.addEventListener('click', function() {
item.remove();
});
Gets the parent element that contains this element.
const deleteBtn = document.querySelector('.delete-btn');
const item = deleteBtn.parentElement;
deleteBtn.addEventListener('click', function() {
item.remove(); // Remove the parent
});
Useful for removing an entire container when clicking a button inside it.
Gets the value of an HTML attribute.
const button = document.querySelector('button');
const tabId = button.getAttribute('data-tab');
const href = link.getAttribute('href');
Commonly used with data attributes to store custom information on elements.
Custom attributes starting with data- that store information on elements.
HTML:
<button data-tab="home">Home</button>
<button data-color="red">Red</button>
JavaScript:
const button = document.querySelector('button');
const tabName = button.getAttribute('data-tab');
Use data attributes to store IDs, settings, or any custom information you need to access with JavaScript.