JavaScript Documentation

Student-friendly JavaScript reference with examples

Sections

Getting Started

How Exercises Work (Input and Output)

In Tinkr, you write code that takes input, processes it, and produces output.

Getting Input

Input values are available as input1, input2, input3, etc:

input1  // First piece of data
input2  // Second piece of data

Processing

Do something with the input:

const result = input1 * 2;

Producing Output

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.

Complete Example

// Get input
const number = input1;

// Process it
const doubled = number * 2;

// Create output
const output = doubled;

Code Syntax Basics

Programming requires exact precision - every bracket, semicolon, and keyword must be exactly right.

Key Points

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

Common Mistakes

// 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);
}

Practice Makes Perfect

Type code carefully. Pay attention to every character.

Programming Basics

What is a Variable?

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

Creating Variables with const

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:

  1. const keyword
  2. A name you choose
  3. = sign
  4. The value to store

Changing Variables with let

Use let to create a variable whose value can change.

let score = 0;
let lives = 3;

Updating a Variable

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.

Multiple Updates

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.

Choosing const vs let

Choose between const and let based on whether the value will change.

Use const for Fixed Values

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.

Use let for Changing Values

let score = 0;
let currentLevel = 1;

Use let when the value might change later. Scores, counters, and other changing values should use let.

Decision Guide

Ask yourself: “Will this value change during my program?”

  • If yes → use let
  • If no → use const

Text Values (Strings)

Text values in programming are called strings. They must be wrapped in quotes.

const city = "Paris";
const greeting = "Hello";
const message = "Welcome to coding!";

Quote Rules

  • Use double quotes (“) for consistency
  • The text inside quotes is the actual value
  • You can include spaces, punctuation, and any characters

Using String Variables

const name = "Alice";
const output = name;  // output now contains "Alice"

Number Values

Numbers in programming don’t need quotes. They can be positive, negative, or decimals.

const temperature = 72;
const score = -5;
const price = 19.99;

Using Number Variables

const age = 25;
const output = age;  // output now contains 25

You can use numbers directly in calculations or store them in variables first.

Math Operations

Basic Math Operators

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)

Using Variables

const price = 10;
const quantity = 3;
const total = price * quantity;  // 30

You can use these operators with numbers directly or with variables containing numbers.

Order of Operations with Parentheses

Parentheses () force operations to happen first. Everything inside parentheses is calculated before anything outside.

Step by Step Example

For (4 + 1) * 3:

  1. First: 4 + 1 = 5 (inside parentheses)
  2. Then: 5 * 3 = 15 (multiply result)

Without vs With Parentheses

const result1 = 6 + 3 * 4;    // 18 (multiplication first)
const result2 = (6 + 3) * 4;  // 36 (addition first)

When to Use Parentheses

const average = (x + y) / 2;
const total = (a + b) * multiplier;

Use parentheses when you need to add or subtract before multiplying or dividing.

Rounding Numbers with Math.round()

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

Rounding to Decimal Places

To round to 2 decimal places (like money):

Math.round(amount * 100) / 100

How It Works

  1. Multiply by 100 to shift decimals: 115.7625 * 100 = 11576.25
  2. Round to nearest integer: Math.round(11576.25) = 11576
  3. Divide by 100 to shift back: 11576 / 100 = 115.76

Examples

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

Why Use It

When dealing with money or percentages, you often get long decimals. Rounding keeps values clean.

Working with Text

Joining Strings with +

The + operator joins strings together. This is called “concatenation”.

const greeting = "Hello" + "World";  // "HelloWorld"

Adding Spaces

To add a space between words, include " " (a string with just a space):

const message = "Good" + " " + "Morning";  // "Good Morning"

Using Variables

const firstName = "John";
const lastName = "Smith";
const fullName = firstName + " " + lastName;  // "John Smith"

Multiple Additions

You can chain multiple + operations. They work left to right:

  • greeting + " " + name
  • First: greeting + " " creates “Hello “
  • Then: "Hello " + name creates “Hello Alice”

Accessing Characters with Brackets

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"

Index Numbers Start at 0

  • First character is at index 0
  • Second character is at index 1
  • Third character is at index 2
  • And so on…

Visual Guide

Word:  "Code"
Index:  0123

C = index 0
o = index 1  
d = index 2
e = index 3

Using with Variables

const name = "Alice";
const firstChar = name[0];  // "A"

String Length Property

Every string has a .length property that tells you how many characters it contains.

const word = "Hello";
const size = word.length;  // 5

Important Notes

  • Spaces count as characters
  • Empty string "" has length 0
  • It’s a property, not a method (no parentheses needed)

Examples

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

toUpperCase() Method

The .toUpperCase() method converts all characters in a string to uppercase.

const text = "hello";
const loud = text.toUpperCase();  // "HELLO"

How It Works

  • The original string is not changed
  • Creates a new string with uppercase letters
  • Works with any string

Examples

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!"

replace() Method

The .replace() method replaces text in a string.

const text = "I hate broccoli";
const newText = text.replace("hate", "love");
// Result: "I love broccoli"

Syntax

string.replace(searchFor, replaceWith)
  • searchFor: The text to find
  • replaceWith: The text to replace it with

Important Notes

  • Only replaces the FIRST match
  • Case sensitive (“Cat” ≠ “cat”)
  • Returns a new string (doesn’t change original)

Examples

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)

slice() Method

The .slice() method extracts part of a string.

const word = "Hello";
const part = word.slice(1);  // "ello" (from index 1 to end)

How It Works

string.slice(startIndex)

Starts at startIndex and goes to the end of the string.

Examples

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"

With Two Parameters

const word = "Hello";
const middle = word.slice(1, 4);  // "ell" (from index 1 to 4, not including 4)

Combining Strings and Numbers

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"

How It Works

When you use + with strings, numbers convert to text automatically:

const score = 100;
const text = "Score: " + score;  // "Score: 100"

Building Messages

const firstName = "John";
const points = 50;
const info = firstName + " has " + points + " points";
// "John has 50 points"

Step by Step

  1. firstName + " has " creates “John has “
  2. "John has " + points creates “John has 50”
  3. "John has 50" + " points" creates “John has 50 points”

Comparing Strings Alphabetically

Strings compare in alphabetical order, like words in a dictionary.

const result = "Apple" < "Banana";  // true (A comes before B)

How It Works

  • < 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)

Important Rules

Case matters: Uppercase letters come before lowercase

"Apple" < "apple"  // true (uppercase comes first)

First different letter decides:

"Car" < "Cat"  // true (r comes before t)

Real Example

const cityA = "Boston";
const cityB = "Denver";
const bostonFirst = cityA < cityB;  // true

Splitting Strings into Arrays

The .split() method breaks a string into an array of parts.

const sentence = "hello world";
sentence.split(" ");  // ["hello", "world"]

How It Works

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"]

Splitting on Spaces

const phrase = "Learning To Code";
const words = phrase.split(" ");  // ["Learning", "To", "Code"]

Using the Result

const input = "JavaScript is fun";
const words = input.split(" ");
for (const word of words) {
  console.log(word);
}
// Prints: "JavaScript", "is", "fun"

Arrays

Creating an Array

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!

Accessing Array Elements

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];

Adding to Arrays with push()

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]

Building an Array in a Loop

const result = [];
for (const val of [1, 2, 3, 4]) {
  if (val % 2 === 0) {
    result.push(val);
  }
}
// result is [2, 4]

Step by Step

  1. Start with empty array: []
  2. Check condition for each element
  3. If true, add element with push()
  4. Result builds up over time

More Examples

const evens = [];
evens.push(2);  // [2]
evens.push(4);  // [2, 4]
evens.push(6);  // [2, 4, 6]

Adding to Start with unshift()

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]

Difference from push()

  • 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]

Reversing an Array

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]

Making Decisions

If Statement Basics

If statements let you run code only when a condition is true.

if (condition) {
  // This code runs only if condition is true
}

Setting Default Values

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';
}

Example

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

Comparison operators compare two values and return true or false.

The Six Operators

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)

Examples

15 > 10      // true
8 >= 8       // true (equal counts!)
5 < 12       // true
20 === 20    // true
5 !== 10     // true (they are different)

Storing Results

const temp = 75;
const isWarm = temp > 20;     // true
const isCool = temp <= 15;    // false
const isExact = temp === 75;  // true

Strict Equality (=== and !==)

Strict equality operators check if values are exactly the same, including their type.

Strict Equal (===)

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.

Not Equal (!==)

5 !== 10          // true (different values)
5 !== '5'         // true (different types)
'cat' !== 'cat'   // false (exactly the same)

Returns true if type OR value are different.

Why Type Matters

const age = 18;
const input = '18';
age === input  // false! (number !== string)

Always use === and !== in JavaScript to avoid surprises.

Type Checking with typeof

The typeof operator returns the type of a value as a string.

typeof 5           // 'number'
typeof 'hello'     // 'string'
typeof true        // 'boolean'
typeof undefined   // 'undefined'

Comparing Types

You can check if two values have the same type:

typeof input1 === typeof input2

Examples

const value1 = 5;
const value2 = '5';

typeof value1            // 'number'
typeof value2            // 'string'
typeof value1 === typeof value2  // false

Use Cases

const sameType = typeof input1 === typeof input2;
const isNumber = typeof age === 'number';
const isText = typeof name === 'string';

Logical Operators (AND, OR, NOT)

Logical operators combine multiple conditions.

AND Operator (&&)

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

OR Operator (||)

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

NOT Operator (!)

Returns the opposite:

!isRaining  // NOT raining (so it's dry)

Grouping with Parentheses

Control evaluation order:

hasCard && (age >= 18 || hasPermission)
// Must have card AND (be 18 OR have permission)

Loops

For-Of Loop Basics

A for-of loop goes through each element in an array, one by one.

for (const item of array) {
  // code runs for each item
}

How It Works

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

With Strings

const names = ["Alice", "Bob", "Carol"];
for (const name of names) {
  console.log(name);
}

Key Points

  • Use const for the loop variable (it changes each iteration)
  • The loop runs once for each element
  • You get the value directly, not the index

Starting Counters and Sums

When adding numbers or counting in a loop, start with 0 or an empty array.

Starting a Sum at 0

let total = 0;
for (const num of [1, 2, 3]) {
  total = total + num;
}
// total is now 6

Starting a Counter at 0

let count = 0;
for (const item of array) {
  if (condition) {
    count = count + 1;
  }
}

Starting with an Empty Array

const result = [];
for (const item of array) {
  if (condition) {
    result.push(item);
  }
}

Why Start at 0?

  • For sums: 0 + 1 = 1 (doesn’t change the first number)
  • For counts: Start from nothing and add 1 each time
  • For arrays: Start empty and add items one by one

Modulo Operator (%)

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)

Checking if Even

Even numbers have no remainder when divided by 2:

4 % 2 === 0  // true (even)
7 % 2 === 0  // false (odd)

Checking if Odd

Odd numbers have remainder 1 when divided by 2:

5 % 2 === 1  // true (odd)
6 % 2 === 1  // false (even)

Example in Loop

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"

Traditional For Loop (for-i)

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
}

Three Parts

  1. let i = 0 - start counter at 0
  2. i < array.length - continue while i is less than array length
  3. i++ - add 1 to i after each iteration

Accessing Elements by Index

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

When to Use For-i

Use for-i when you need:

  • The index (position)
  • To compare value with its position
  • To access elements by index

The Index Variable

The variable i IS the index itself:

if (array[i] > i) {
  // element is greater than its position
}

Nested For-Of Loops

Nested loops are loops inside loops. Use them for arrays inside arrays (2D arrays).

Arrays of Arrays

const grid = [[1, 2], [3, 4], [5, 6]];

Outer Loop

for (const innerArray of grid) {
  // innerArray is each sub-array
}

The outer loop goes through each sub-array.

Inner Loop

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.

Complete Example

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)

How It Works

  1. Outer loop gets [1, 2]
    • Inner loop: process 1, then 2
  2. Outer loop gets [3, 4]
    • Inner loop: process 3, then 4

Functions

Function Basics

Functions are reusable blocks of code that take inputs and return outputs.

Function Syntax

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

Creating a Function

function double(num) {
  return num * 2;
}

Calling a Function

const result = double(5);  // 10

Write the function name followed by parentheses with the argument inside.

Complete Example

function isPositive(n) {
  return n > 0;
}
const answer = isPositive(5);  // true

Functions with Multiple Parameters

Functions can take multiple inputs by separating parameters with commas.

Multiple Parameters

function add(a, b) {
  return a + b;
}

Using All Parameters

function multiply(x, y) {
  return x * y;
}
const result = multiply(5, 3);  // 15

All parameters are available inside the function body.

Order Matters

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.

Calculating Percentages

function discount(price, percent) {
  return price * (percent / 100);
}
const saved = discount(50, 20);  // 10

To get a percentage, divide by 100 and multiply.

Variable Scope (Global vs Local)

Scope determines where variables can be accessed in your code.

Global Variables

const taxRate = 0.08;  // Available everywhere

Variables defined outside functions are global - they can be used anywhere.

Local Variables

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.

Using Globals in Functions

const rate = 0.05;
function calculate(amount) {
  return amount * rate;  // Can read global 'rate'
}

Functions can access and use global variables.

Combining Global and Local

const multiplier = 5;  // Global

function transform(value) {
  const result = value * multiplier;  // Local variable using global
  return result;
}

Recursive Functions

A recursive function is a function that calls itself to solve a problem by breaking it into smaller pieces.

Basic Structure

function countdown(n) {
  if (n === 0) {
    return "Done!";  // Base case
  }
  return countdown(n - 1);  // Recursive call
}

Base Case

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!

Recursive Step

The function calls itself with different values:

return countdown(n - 1);  // Calls itself with smaller value

How It Works

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.

Complete Example

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

Creating Objects

Objects store related data using key-value pairs inside curly braces.

Object Syntax

const dog = {breed: "Poodle", age: 3};

Each pair uses the format key: value, separated by commas.

Multiple Properties

const car = {
  brand: "Honda",
  year: 2019,
  color: "red"
};

You can have as many properties as you need.

Different Data Types

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.

Accessing Object Properties

Access property values from an object using dot notation.

const item = {title: "Book", cost: 20};
item.title  // "Book"
item.cost   // 20

The Pattern

objectName.propertyName
  • Write the object name
  • Add a dot .
  • Add the property name

Using Properties

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

Changing and Adding Properties

You can change existing properties or add new ones using dot notation with the assignment operator.

Modifying Existing Properties

const user = {age: 25};
user.age = 26;  // Changes age to 26

Adding New Properties

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.

Multiple Changes

const player = {name: "Alex", score: 100};
player.score = 150;   // Change score
player.level = 3;     // Add level

Accessing After Modification

const item = {count: 5};
item.count = 10;
item.count  // 10 (new value)

Nested Objects

Objects can contain other objects as property values. This is called nesting.

Nested Objects

const person = {
  name: "Alice",
  address: {
    street: "Oak Ave",
    city: "Portland"
  }
};

Accessing Nested Properties

Use multiple dots to go deeper:

person.address        // {street: "Oak Ave", city: "Portland"}
person.address.city   // "Portland"
person.address.street // "Oak Ave"

Step-by-Step Access

  1. Start with outer object: person
  2. Access nested object: person.address
  3. Access inner property: person.address.city

Chaining Dots

const car = {
  model: "Civic",
  specs: {
    color: "blue",
    year: 2021
  }
};
car.specs.year  // 2021

Chain dots together to navigate through nested objects.

Object.values() Method

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]

Converting to Array

const values = Object.values(scores);
// values is now [85, 90, 78]

Store the result in a variable to use it.

Looping Through Values

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

Use Case: Summing

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