JavaScript Variables HW
JavaScript Variables
Variables Homework (Show what you know!)
Homework Problem: Understanding JavaScript Variables
Creating Variables
- Create three variables as an object variable:
- A variable called
studentName
that stores your name as a string. - A variable called
age
that stores your age as a number. - A variable called
isStudent
that stores a boolean value indicating whether you are a student (usetrue
orfalse
).
-
Create a function variable that displays that your favorite song is playing:
- A variable called
favoriteSong
that stores the name of your favorite song. - A variable called
songArtist
that stores the song’s artist. - A function called
playFavoriteSong
that logs a message saying “Now playing [favoriteSong] by [songArtist]”.
- A variable called
- A variable called
- Using the variables you created, write a sentence using
console.log()
to display:- Your name.
- Your age.
- Whether you are a student.
- An output that states that your favorite song is now playing
Example output: My name is [Your Name], I am [Your Age] years old, and it is [true/false] that I am a student. Now playing Champion by Kanye West
%%html
<div id="songName">song Name</div>
<div id="artistName">artist Name</div>
<div id="stats"></div>
<button onclick="nextSong()">Play Next Song</button>
<button onclick="FavoriteSong()">Play Favorite Song</button>
song Name
artist Name
%%javascript
/*
CODE DOES NOT RUN ON THE WEBSITE!!!
TO MAKE IT RUN IN JUPY RUN HTML THEN THE JS
*/
console.log("Loaded the js")
let songs = [
{ name: "Peanut Butter Jelly Time", artist: "DJ Chipman" },
{ name: "Raining Tacos", artist: "Parry Gripp" },
{ name: "The Duck Song", artist: "Bryant Oden" },
{ name: "I'm a Coconut", artist: "Coconut Hen" },
{ name: "Cheese Tax", artist: "Puppy Songs" }
];
let student = {
Name : "Larry",
Age : "-76",
Demon : true,
FavSong : songs[1]
}
const songName = document.getElementById("songName");
const artistName = document.getElementById("artistName");
const stats = document.getElementById("stats")
stats.innerHTML = ("Picked by: " + student.Name)
let currentSong = 1;
window.nextSong = function() {
if (currentSong > songs.length) {
currentSong = 1;
}
let song = songs[currentSong - 1];
console.log(song)
if (song) {
songName.innerHTML = "Song: " + song.name;
artistName.innerHTML = "Artist: " + song.artist;
} else {
console.log("Song not found at index:", currentSong - 1);
}
currentSong = currentSong + 1;
};
window.nextSong(window.currentSong);
window.FavoriteSong = function(){
songName.innerHTML = "Song: " + student.FavSong.name;
artistName.innerHTML = "Artist: " + student.FavSong.artist;
}
<IPython.core.display.Javascript object>