Strings

Code Runner Challenge

Create

View IPYNB Source
%%js

// CODE_RUNNER: Create

let part1 = "h";
let part2 = "i";
let part3 = "!";

let secretbase = "mysecret";
let codeword = "hello";
let symbol = "!";

let baseLength = secretbase.length;
let fullCode = codeword.toUpperCase();
let fullSecret = secretbase + fullCode + symbol;

console.log("The number of characters in the secret base is:");
console.log(baseLength);
console.log("The secret code is: ");
console.log(fullCode);
console.log("The full secret is: ");
console.log(fullSecret);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Snack Message

View IPYNB Source
%%js

// CODE_RUNNER: Snack Message

let ingredient = "chips";
let price = "$100";
let store = "Chips and dips";

let snackMessage =
"Attention chip lovers!\n" +
"For a limited time only, get freshly fried " + ingredient + " " +
"at " + store + " for just " + price + ".\n" +
"Don't miss your chance to taste happiness today!";

console.log("The full message is " + snackMessage.length + " characters long.");
console.log(snackMessage);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Lucky Seven

View IPYNB Source
%%js

// CODE_RUNNER: Lucky Seven

const UPGRADE_NAME = "Lucky Seven";
let cost = 7777;
let EMOJI = "🍀";
let message = "Insufficient Cookies";

const DISPLAY_NAME = UPGRADE_NAME.toUpperCase();
const NAME_LENGTH = UPGRADE_NAME.length;

console.log(DISPLAY_NAME);
console.log("Name Character Count: " + NAME_LENGTH);
console.log(EMOJI + " " + UPGRADE_NAME + " (" + cost + " Cookies)");
const errorDisplay = "Error: " + EMOJI + " " + UPGRADE_NAME + " purchase failed: \"" + message + "\"";
console.log(errorDisplay);
let HINT_TEXT = "The \"Lucky Seven\" upgrade multiplies your clicks by 7.";
console.log(HINT_TEXT);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Classes and Constructors

Code Runner Challenge

Tennis Player

View IPYNB Source
%%js

// CODE_RUNNER: Tennis Player

class TennisPlayer {
    constructor(name, rank, rankPoints, age) {
        this.name = name;
        this.rank = rank;
        this.rankPoints = rankPoints;
        this.age = age;
    }
    profile() {
        console.log("Hi my name is " + this.name + ", my rank is " + this.rank + ", I have " + this.rankPoints + " ranking points, and I am " + this.age + " years old.");
    }
}

let player1 = new TennisPlayer("Novak Djokovic", 1, 16000, 38);
player1.profile();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Library

View IPYNB Source
%%js

// CODE_RUNNER: Library

class Library {
    constructor(name) {
        this.name = name;
        console.log(`Welcome to the`, this.name, `Library!`);
    }
    static Book = class {
        constructor() { this.books = []; }
        addBook(title) {
            this.books.push(title);
            console.log(`Added "${title}" to the library.`);
        }
        removeBook(title) {
            const index = this.books.indexOf(title);
            if (index > -1) { this.books.splice(index, 1); console.log(`Removed "${title}".`); }
            else { console.log(`"${title}" not found.`); }
        }
    }
    static Computers = class {
        constructor(computersOn) { this.computersOn = computersOn; }
        showComputersOn() { console.log(`There are ${this.computersOn} computers currently on.`); }
    }
}

const myLibrary = new Library("Downtown");
const bookManager = new Library.Book();
const techRoom = new Library.Computers(8);
bookManager.addBook("The Hobbit");
bookManager.addBook("1984");
bookManager.removeBook("The Hobbit");
techRoom.showComputersOn();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Cookie Clicker

View IPYNB Source
%%js

// CODE_RUNNER: Cookie Clicker

class CookieClicker {
  constructor(cookies, cookiesPerClick, cookieType) {
    this.cookies = cookies;
    this.cookiesPerClick = cookiesPerClick;
    this.cookieType = cookieType;
  }
  click() {
    this.cookies += this.cookiesPerClick;
    console.log("You clicked a " + this.cookieType + " cookie!");
    console.log("You have " + this.cookies + " cookies.");
  }
  applyUpgrade(upgrade) {
    this.cookiesPerClick *= upgrade.multiplier;
    console.log("Upgrade applied! Multiplier: " + upgrade.multiplier);
    this.showStatus();
  }
  showStatus() {
    console.log("Each click gives " + this.cookiesPerClick + " cookies. Total: " + this.cookies);
  }
}
class Upgrade {
  constructor(multiplier) { this.multiplier = multiplier; }
}

const game = new CookieClicker(0, 1, "Chocolate chip");
game.click();
game.click();
const upgrade = new Upgrade(2);
game.applyUpgrade(upgrade);
game.click();
game.showStatus();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Iterations

Code Runner Challenge

Count Stars

View IPYNB Source
%%js

// CODE_RUNNER: Count Stars

function countStars(limit) {
  let count = 1;
  while (count <= limit) {
    console.log(`Star #${count} shining bright!`);
    count += 1;
  }
  console.log("All the stars have been counted.");
}

countStars(5);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Playlist Shuffle

View IPYNB Source
%%js

// CODE_RUNNER: Playlist Shuffle

function playlistShuffle(playlist) {
  for (const song of playlist) {
    console.log(`Now playing: "${song}"`);
  }
  console.log("Playlist finished!");
}

const mySongs = ["Song A", "Song B", "Song C"];
playlistShuffle(mySongs);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Data Abstraction

Code Runner Challenge

Account

View IPYNB Source
%%js

// CODE_RUNNER: Account

let username = "Hi";
let password = "hi_very_awesome_password";

function Account() { console.log(username, password); }
function ChangeUsername(newUserName) { username = newUserName; }
function ChangePassword(newPassword) { password = newPassword; }
function Login(_username, _password) {
    if (_username === username && _password === password) {
        console.log("Login Success!"); return true;
    } else {
        console.log("Login Failure"); return false;
    }
}

ChangeUsername("Krish");
ChangePassword("password");
Account();
Login("Krish", "password");
Login("Krish", "P@ssword");
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

House

View IPYNB Source
%%js

// CODE_RUNNER: House

class House {
    constructor(cost, age, size) {
        this.cost = cost;
        this.age = age;
        this.size = size;
    }
}

let anishsHouse = new House(700000, 1, 7000);
console.log(anishsHouse);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Player

View IPYNB Source
%%js

// CODE_RUNNER: Player

class Player {
    constructor() {
        this.positionX = 0;
        this.velocityX = 0;
    }
    moveLeft() { this.velocityX = -100; }
    moveRight() { this.velocityX = 100; }
    updatePosition() {
        this.positionX += this.velocityX;
        console.log("Position updated to:", this.positionX);
    }
}

let player = new Player();
player.moveLeft();
player.updatePosition();
player.moveRight();
player.updatePosition();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Classes and Variables

Code Runner Challenge

Name and Age

View IPYNB Source
%%js

// CODE_RUNNER: Name and Age

let name = "Sam";
let age = 10;
console.log("Hi, my name is", name);
console.log("I am", age, "years old.");
let nextYearAge = age + 1;
console.log("Next year I will be " + nextYearAge + " years old");
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Animal Zoo

View IPYNB Source
%%js

// CODE_RUNNER: Animal Zoo

class Animal {
  constructor(name, sound, kind) {
    this.name = name;
    this.sound = sound;
    this.kind = kind;
  }
  speak() { console.log(`${this.name} the ${this.kind} says ${this.sound}!`); }
  describe() { console.log(`${this.name} is a ${this.kind} and is very friendly!`); }
}

let zoo = [];
zoo.push(new Animal("Buddy", "Woof", "Dog"));
zoo.push(new Animal("Mittens", "Meow", "Cat"));
zoo.push(new Animal("Polly", "Squawk", "Parrot"));
zoo.forEach(animal => { animal.speak(); animal.describe(); });
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Rock Paper Scissors

View IPYNB Source
%%js

// CODE_RUNNER: Rock Paper Scissors

const choices = ["rock", "paper", "scissors"];
const computerChoice = choices[Math.floor(Math.random() * choices.length)];
const userChoice = "rock";
console.log("You chose:", userChoice);
console.log("Computer chose:", computerChoice);

if (userChoice === computerChoice) {
  console.log("It's a tie!");
} else if (
  (userChoice === "rock" && computerChoice === "scissors") ||
  (userChoice === "scissors" && computerChoice === "paper") ||
  (userChoice === "paper" && computerChoice === "rock")
) {
  console.log("You win!");
} else {
  console.log("You lose!");
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Classes and Methods

Code Runner Challenge

Dice

View IPYNB Source
%%js

// CODE_RUNNER: Dice

class Dice {
  constructor(sides) { this.sides = sides; }
  roll() { return Math.floor(Math.random() * this.sides) + 1; }
}

let myDice = new Dice(6);
console.log(myDice.roll());
console.log(myDice.roll());
console.log(myDice.roll());
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Pet

View IPYNB Source
%%js

// CODE_RUNNER: Pet

class Pet {
  constructor(name) {
    this.name = name;
    this.hunger = 5;
    this.energy = 5;
    this.happiness = 5;
  }
  feed() {
    this.hunger -= 5;
    this.energy += 10;
    this.happiness += 10;
    console.log(this.name + "'s hunger went down by 5!");
    console.log(this.name + "'s energy went up by 10!");
    console.log(this.name + "'s happiness went up by 10!");
  }
  play() {
    this.hunger += 5;
    this.energy -= 10;
    this.happiness += 20;
    console.log(this.name + "'s hunger went up by 5!");
    console.log(this.name + "'s energy went down by 10!");
    console.log(this.name + "'s happiness went up by 20!");
  }
}

const myPet = new Pet("Pranay");
console.log("hunger: " + myPet.hunger + ", energy: " + myPet.energy + ", happiness: " + myPet.happiness);
myPet.feed();
myPet.play();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Person Book Car

View IPYNB Source
%%js

// CODE_RUNNER: Person Book Car

class Person {
  constructor(name, age) { this.name = name; this.age = age; }
  greet() { console.log(`Hello, my name is ${this.name}!`); }
}
class Book {
  constructor(title, author, pages) {
    this.title = title; this.author = author;
    this.pages = pages; this.pagesRead = 0;
  }
  read(pages) {
    this.pagesRead += pages;
    if (this.pagesRead > this.pages) this.pagesRead = this.pages;
    console.log(`You have read ${this.pagesRead} out of ${this.pages} pages.`);
  }
  isLongBook() { return this.pages > 300; }
}
class Car {
  constructor(make, model, fuel) { this.make = make; this.model = model; this.fuel = fuel; }
  drive(distance) {
    const fuelNeeded = distance * 0.1;
    if (this.fuel >= fuelNeeded) { this.fuel -= fuelNeeded; console.log(`Drove ${distance} km. Fuel left: ${this.fuel.toFixed(2)} liters.`); }
    else { console.log("Not enough fuel."); }
  }
  refuel(amount) { this.fuel += amount; console.log(`Refueled. Total fuel: ${this.fuel.toFixed(2)} liters.`); }
  static info() { console.log("Cars are vehicles."); }
}
class ElectricCar extends Car {
  constructor(make, model, fuel, battery) { super(make, model, fuel); this.battery = battery; }
  charge(amount) {
    this.battery += amount;
    if (this.battery > 100) this.battery = 100;
    console.log(`Battery charged to ${this.battery}%.`);
  }
}

const person = new Person("Alice", 30);
const book = new Book("JavaScript Basics", "Anish Gupta", 350);
const car = new Car("Toyota", "Corolla", 10);
const electricCar = new ElectricCar("Tesla", "Model 3", 0, 50);

person.greet();
book.read(120);
console.log(`Is the book long? ${book.isLongBook()}`);
car.drive(50);
car.refuel(5);
electricCar.charge(30);
Car.info();
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Array

Code Runner Challenge

Favorite Foods

View IPYNB Source
%%js

// CODE_RUNNER: Favorite Foods

let favoriteFoods = ["Ice cream", "Cookies", "Chicken", "Cake", "Apples"];
console.log("Favorite Foods: " + favoriteFoods[0]);
favoriteFoods[2] = "pizza";
favoriteFoods.push("sandwich");
console.log("Total Number of Foods: " + favoriteFoods.length);
console.log("My Favorite Foods are now: " + favoriteFoods);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Temperature Array

View IPYNB Source
%%js

// CODE_RUNNER: Temperature Array

let weekTemps = [66, 67, 62, 77, 74, 78, 76];
console.log("Monday Temperature: " + weekTemps[0] + " Friday Temperature: " + weekTemps[4]);

let total = 0;
for (let i = 0; i < weekTemps.length; i++) { total += weekTemps[i]; }
let average = total / weekTemps.length;
console.log("Average temperature:", average);

let maxTemp = Math.max(...weekTemps);
console.log("The Highest Temperature is: " + maxTemp);

let hotDay = false;
for (let i = 0; i < weekTemps.length; i++) { if (weekTemps[i] > 80) hotDay = true; }
console.log(hotDay ? "At least one day was above 80°F." : "No days were above 80°F.");
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...