In: Computer Science
/*
Here is an example of a conditional in JavaScript
*/
var numberOfParticipants = 5;
var maxNumberOfParticipants = 10;
if (numberOfParticipants < maxNumberOfParticipants)
{
console.log("You can add another participant now");
}
else
{
console.log("Sorry, you have reached the max number of participants and cannot add another");
}
/*
Now it's your turn - create a simple conditional like my example. You can setup variables like I did or just use
hard-coded numbers
*/
/*
Here is an example of creating a list in JavaScript it is called an array. Here I am creating a list of my favorite songs:
*/
var myFavoriteSongs = ["Shake It Off by Taylor Swift", "12 Shots by Vic Mensa", "LSD by A$AP Rocky"];
/*
Now it's your turn. Create an array of the colors in a rainbow (ROYGBIV)
*/
/*
Here is an example of creating a for loop in JavaScript. There is no foreach in JavaScript so we have to do it slightly differently than
in App Inventor. Notice how it counts from zero not one!
*/
for (var index = 0; index < myFavoriteSongs.length; index++)
{
var favoriteSong = myFavoriteSongs[index];
console.log((index + 1) + ") " + favoriteSong + "\n");
}
/*
Now it's your turn. print out the array of the colors in a rainbow using a for loop
*/
/*
Here is an example of adding an event listener to my button. Notice how the inline-function has a
single line of coded within the {}: console.log("I was clicked!");
*/
var myButton = document.getElementById("myButton");
myButton.addEventListener("click", function () {console.log("I was clicked!");} );
/*
Now it's your turn to do something when your button is clicked. I've created the variable "yourButton" for you already
*/
var yourButton = document.getElementById("yourButton");
Program 1
//conditional statement to check if a person can vot or not
var ageLimit = 18;
var currentAge = 12;
if (currentAge >= ageLimit)
{
console.log("Allowed to vote");
}
else
{
console.log("Sorry , you are too young to vote.");
}
Screenshot
Output
Program 2 and 3
Code
//array to store colours of rainbow
var colours = ["Violet","Indigo","Blue","Green","Yellow","Orange","Red"];
//itearte the array
for (var index = 0; index < colours.length; index++)
{
var color = colours[index];
console.log((index + 1) + ") " + color + "\n");
}
Screenshot
Output
Program 4
Code
//when clicked this will show alert dialog
var yourButton = document.getElementById("yourButton");
yourButton.addEventListener("click", function () {alert("My button was clicked");} );
Screenshot