JavaScript Fundamentals
Master arrays, strings, and core concepts. Learn by solving real problems.
0/44
Challenges Completed
0%
Progress
0
Your Total Score
1. Hello Variables
Welcome to JavaScript! Let's start by creating variables to store data. Variables are containers for values.
### Your Task:
- Create a variable called `name` and set it to `"Alice"`
- Create a variable called `greeting` using `const` that contains the string `"Hello, "` (note the space)
- Create a variable called `message` that combines the greeting with the name using the `+` operator
- The final message should be `"Hello, Alice!"`
2. Number Magic
Now let's do some math! JavaScript can handle calculations for you. Use `*` for multiplication, `+` for addition, and `Math.round()` for rounding.
### Your Task:
- Create a variable `subtotal` that multiplies `price` by `quantity`
- Create a variable `tax` that is 10% of the subtotal (multiply by `0.1`)
- Create a variable `total` that adds `subtotal` and `tax`
- Create a variable `roundedTotal` using `Math.round(total * 100) / 100` to keep 2 decimal places
3. Level Checker
Let's make decisions with code! Use `if/else` statements to check conditions.
### Your Task:
- Create a variable `statusMessage` using `let` (so we can change it)
- Use `if/else` statements to set the message based on `playerLevel`
- If level < 5: set message to `"Beginner player"`
- Else if level >= 15: set message to `"Advanced player"`
- Else: set message to `"Intermediate player"`
4. Access Control
Safeguard your app with logic! Use `&&` (AND) and `||` (OR) to combine conditions.
### Your Task:
- Create a variable `hasBasicAccess` (true if free OR premium)
- Create a variable `hasAdminAccess` (true if admin AND active)
- Create a variable `canModerate` (true if (admin OR moderator) AND active)
5. User Profile Builder
Objects group related data together. Use dot notation to access properties.
### Your Task:
- Create a `user` object with `name`, `age`, `email`, and `isActive` (set to `true`)
- Create a variable `welcomeMessage` using the user's name: `"Welcome back, " + user.name + "!"`
6. Modern Profile Builder
Modern JavaScript offers cleaner syntax. Use **property shorthand** and **template literals**.
### Your Task:
- Create a `profile` object using shorthand: `{ name, age, city }`
- Create a `bio` string using backticks: `Hello, I'm ${profile.name} and I'm ${profile.age} years old`
7. Backticks vs Quotes
Strings can be tricky when they contain quotes. Backticks make it easier.
### Your Task:
- Create `message` using normal quotes: `"She said, \"I can't do this!\" and walked away."` (use escaping)
- Create `cleanMessage` using backticks: `` `She said, "I can't do this!" and walked away.` `` (no escaping)
8. Array Explorer
Arrays are lists of items. You can access items using their index (starting from 0) and check the length.
### Your Task:
- Create `firstItem` = first item in the cart (index 0)
- Create `lastItem` = last item (using `length - 1`)
- Create `totalItems` = total number of items in the cart
9. Inventory Counter
Loops let you repeat code. Let's count how many items are in stock.
### Your Task:
- Create a variable `count` starting at 0
- Loop through `products` array
- If `product.inStock` is true, increment `count`
10. Order Processing Helper
Functions are reusable blocks of code. Let's create helper functions to calculate totals.
### Your Task:
- Create a function `calculateSubtotal(items)` that sums up item prices
- Create a function `calculateDiscount(subtotal, percent)` that returns discount amount
- Use them to calculate `subtotal`, `discount`, and `finalTotal`
11. Dynamic Shopping Cart
Arrays can change size! Use `.push()` to add to end, `.pop()` from end, `.unshift()` to start, and `.shift()` from start.
### Your Task:
- Create a copy of `initialCart` called `cart`
- Loop through `actions`
- Perform the requested operation on your `cart`
12. To Spread or Not to Spread
Arrays are reference types! If you assign `arr1 = arr2`, they point to the same list. Use `[...arr]` to make a real copy.
### Your Task:
- Create `referenceCopy = originalItems`
- Create `spreadCopy = [...originalItems]`
- Add "New Item" to all 3 arrays (original, reference, spread) using push
- Notice how original and reference stay in sync?
13. Order Status Manager
Switch statements check one value against many options. It's cleaner than many if/else blocks.
### Your Task:
- Use `switch(status)` to set `message` and `canCancel`
- pending/processing: "Processing...", true
- shipped: "Shipped...", false
- delivered: "Delivered...", false
- cancelled: "Cancelled...", false
- default: "Unknown...", false
14. Time Traveler (Dates)
Dates are built-in objects that store time data. Let's work with the `Date` object.
### Your Task:
- Create a new Date object representing right now and store it in `now`
- Create a specific date for "2025-01-01" and store it in `futureDate`
- Get the full year from `futureDate` using `.getFullYear()` and store it in `futureYear`
15. Scope Hunter
Understanding scope is key to mastering variables. `var` is function-scoped (or global), while `let` and `const` are block-scoped (only exist inside `{}`).
### Your Task:
- Inside the `if` block:
- Create a variable `blockScoped` using `let` and set it to "I am safe"
- Create a variable `leakyVar` using `var` and set it to "I leak out"
- Outside the block (after the closing `}`):
- Assign `leakyVar` to a variable `capturedLeak` (it should still exist!)
- Try to assign `blockScoped` to `capturedBlock` (it would error, so just set `capturedBlock` to "Error caught" string for this exercise)
16. Quick Decisions (Ternary)
The ternary operator `? :` is a condensed if/else. Also learn `typeof` and the `in` operator.
### Your Task:
- Use ternary to set `status` = "adult" if age >= 18, else "minor"
- Use `typeof` to check if `value` is a "string" → `isString`
- Use `in` operator to check if "name" exists in `user` object → `hasName`
17. Number Wizard
JavaScript has powerful Math methods and number parsing utilities.
### Your Task:
- Use `Math.floor()` on `decimal` to round down → `floored`
- Use `Math.max()` to find the largest of 5, 10, 3 → `largest`
- Use `parseInt()` to convert "42px" to a number → `parsed`
- Use `Math.random()` to generate a random number 0-1 → `random`
18. Text Processor
String methods allow you to manipulate text. Let's practice splitting and joining strings.
### Your Task:
- Split `text` into an array called `parts` using `separator`
- Get the first element (`productName`) and last 10 chars (`lastChars`)
- Rejoin parts with `" | "` into `rejoined`
19. Dynamic Product Title Generator
Let's format some text! Use case conversion and concatenation.
### Your Task:
- Convert `brand` to uppercase
- Convert `product` to lowercase
- Capitalize `category` (first letter upper, rest lower)
- Create `formattedTitle` pattern: `"BRAND product - Category"`
20. Smart Product Classifier
Classify products based on their description. Use `includes()` and `startsWith()`.
### Your Task:
- Create `hasSearchTerm` (true if description contains `searchTerm`)
- Create `isHighPerformance` (true if description starts with "High-performance")
- Create `categoryMessage` based on conditions:
- Both true: "Premium [term] device"
- Term only: "Great [term] product"
- HighPerf only: "High-end device"
- Neither: "Standard product"
21. String Reverser
Algorithmic thinking time! Reverse a string manually (without using `.reverse()`).
### Your Task:
- Loop backwards through `text` starting from the last character
- Build a new string called `reversedText`
- Add each character to `reversedText` one by one
22. Clean Up Crew
Clean and transform strings with `.trim()`, `.replace()`, and `.replaceAll()`.
### Your Task:
- Use `.trim()` on `messy` to remove leading/trailing whitespace → `cleaned`
- Use `.replace()` on `cleaned` to replace the first 'error' with 'success' → `fixed`
- Use `.replaceAll()` on `text` to replace all 'old' with 'new' → `updated`
23. String Detective
Search within strings using `.startsWith()`, `.endsWith()`, and `.includes()`.
### Your Task:
- Check if `filename` starts with 'file' → `startsWithFile`
- Check if `filename` ends with '.txt' → `isTxtFile`
- Check if `message` includes the word 'error' → `hasError`
24. Array Mapping
Transform data with `.map()`! It creates a new array by applying a function to each item.
### Your Task:
- Create `productNames` array by mapping over `products`
- Extract just the `name` property from each product
25. Affordable Products Filter
Filter data with `.filter()`! It creates a new array with items that match a condition.
### Your Task:
- Create `affordableProducts` array
- Keep only products where `price` is less than `maxPrice`
26. Product Name Finder
Find a specific item with `.find()`! It returns the first item that matches a condition, or `undefined`.
### Your Task:
- Create `foundProduct` variable
- Find the product with `searchName` (case-insensitive)
- Use `.toLowerCase()` for comparison
27. Cart Total Calculator
Calculate a single value from an array with `.reduce()`! It accumulates a result as it loops.
### Your Task:
- Calculate `total` price of all items
- Use `.reduce()` with an initial value of 0
- Add `item.price * item.quantity` to the accumulator
28. Sort Squad
The `.sort()` method sorts arrays in place. By default it sorts as strings, so you need a compare function for numbers!
### Your Task:
- Sort `names` alphabetically (default sort is fine)
- Sort `prices` numerically using `(a, b) => a - b` as the compare function
- Store results in `sortedNames` and `sortedPrices`
29. Truth Checkers
Use `.some()` to check if **any** element passes a test, and `.every()` to check if **all** elements pass.
### Your Task:
- Check if `ages` has any adult (>= 18) using `.some()` → store in `hasAdult`
- Check if all ages are positive using `.every()` → store in `allPositive`
30. Slice & Dice
`.slice()` extracts a portion (**doesn't modify** original), while `.splice()` modifies the array in place.
### Your Task:
- Use `.slice(1, 3)` on `items` to get elements at index 1 and 2 → `middle`
- Make a copy of `items` using spread or slice
- Use `.splice(0, 1)` on the **copy** to remove the first element → `withoutFirst`
31. Order Up! (Callbacks)
Understanding asynchronous callbacks is the first step to mastering Async JS! Let's simulate a food order.
### Your Task:
- Create a function called `prepareOrder` that takes a `callback` as an argument
- Inside `prepareOrder`, use `setTimeout` to wait for 100 milliseconds
- Inside the `setTimeout` callback, call the passed `callback` function with the string "Burger Ready!"
- Call `prepareOrder` and pass a callback that saves the result to a variable named `orderStatus`
32. Promising Future
Promises are a modern way to handle async operations. They represent a value that might be available now, later, or never.
### Your Task:
- Create a function `makePromise` that returns a new `Promise`
- The promise should `resolve` with the string "Success!"
- Call `makePromise` and use `.then()` to update the `result` variable with the resolved value
33. Async Kitchen
`async/await` makes asynchronous code look and behave like synchronous code! It's syntactic sugar built on top of Promises.
### Your Task:
- Create an `async` function called `kitchenFlow`
- Inside it, `await` the `cookSteak` function (provided)
- Save the result to a variable `dinner`
- Return the `dinner` variable
34. Handling Mistakes
Things don't always go according to plan. In async code, we use `try/catch` to handle errors elegantly.
### Your Task:
- Create an `async` function `safeCall`
- Inside a `try` block, `await` the `riskyOperation` function
- If it succeeds, return the result
- Inside a `catch` block, return the string "Recovered from error"
35. Secret Keeper (Closures)
Closures allow a function to remember the scope in which it was created, even after that scope has finished executing. This causes 'state' to be preserved.
### Your Task:
- Create a function `createSecretHolder` that takes a `secret` argument
- Return an inner function that returns the `secret`
- Create a `getSecret` function by calling `createSecretHolder` with the secret "MySecret"
- Call `getSecret()` and store the result in `revealedSecret`
36. Classy Animals
Classes are blueprints for creating objects. They encapsulate data and behavior.
### Your Task:
- Define a class named `Animal`
- Add a `constructor` that takes a `name` and stores it as property
- Add a method `speak()` that returns "[name] makes a noise."
- Create an instance `dog` with name "Rex"
- Call `dog.speak()` and store it in `sound`
37. Inheritance Chain
Inheritance allows a class to derive features from another class. The `extends` keyword is used for this.
### Your Task:
- Create a class `Dog` that `extends` `Animal` (Animal is pre-defined for you in the background setup, but you need to redefine it or assume it exists. For this script, define both or just Dog if you can)
- Let's define `Animal` first (copy from previous if needed) then `Dog`
- `Dog` should override `speak()` to return "[name] barks."
- Create a `myDog` instance named "Buddy"
- Call `myDog.speak()`
38. Who is 'this'?
The `this` keyword refers to the object it belongs to. However, it can lose context when passed around.
### Your Task:
- We have an object `person` with a `greet` method
- When we assign `person.greet` to `greetFn`, it loses context (this becomes undefined or global)
- Fix this by binding `greetFn` to `person` using `.bind()`
- Call the bound function
39. Arrow's Aim
Arrow functions `() => {}` behave differently than regular functions. They don't have their own `this`; they inherit it from the surrounding scope.
### Your Task:
- We have a `target` object with a score
- Inside `shootArrow`, `this.score` works because it's a normal function
- But inside `setTimeout`, a normal function would lose `this`. Use an **arrow function** inside `setTimeout` so it keeps looking at the `target` object.
- Update `score` to 100 inside the callback
40. Master of Control (Call/Apply)
Sometimes you want to borrow a function and use it on a different object. `call()` and `apply()` let you explicitly set what `this` refers to.
### Your Task:
- We have a `wizard` object and a `warrior` object
- `wizard` has a `castSpell` method
- Use `call()` to make the `warrior` cast the spell! `wizard.castSpell.call(...)`
- Pass 'Fireball' as the argument
41. Unpacking the Box (Destructuring)
Destructuring allows you to unpack values from arrays or properties from objects into distinct variables. It makes extracting data much cleaner!
### Your Task:
- Use object destructuring to extract `name` and `age` from the `user` object
- Use array destructuring to extract `firstColor` and `secondColor` from the `colors` array
42. Gather 'em Up (Rest)
The Rest operator (`...`) collects multiple elements into a single array. It's great for functions that accept any number of arguments.
### Your Task:
- Create a function `sumAll` that accepts any number of arguments using the rest operator `...numbers`
- Inside, use `numbers.reduce()` to sum them all up
- Return the total sum
- Call `sumAll(1, 2, 3, 4)` and store it in `total`
43. Merge Logic (Spread)
The Spread operator (`...`) expands an array or object into individual elements. It's perfect for merging data.
### Your Task:
- Create `combinedArray` by merging `arr1` and `arr2` using spread
- Create `mergedObject` by merging `obj1` and `obj2` using spread
- `arr1` should come before `arr2`
- `obj2` properties should overwrite `obj1` if they share keys
44. Safety First (Optional Chaining)
Optional Chaining (`?.`) allows you to access deeply nested properties without worrying if an intermediate property is `null` or `undefined`. Accessing a missing property simply returns `undefined` instead of throwing an error.
### Your Task:
- You have a `user` object that might have a missing `profile` or `address`
- Safely extract the `zipCode` from `user.profile.address.zipCode` into a variable `zip`
- Safely call a method `user.getDetails?.()` (it might not exist!) and store in `details`
Ready to Code?
Start with the first challenge and work your way up to become a coding master!
Start First Challenge