Understand Javascript error - javascript

This is my very first program in javascript! I've been trying to go through tutorials and I kind of get it. But my code doesn't work! I want to find out why??? An explanation of the error would help me understand.
document.write("Random # (1-5) = ", Math.floor((Math.random() * 5) + 1), "<br />");
if(Random = 2){
alert("Your names Bob");
}else {
alert("Your names Superman");
}
This program writes to the page a random number between 1 and 5, (works fine...) then, say, if the random number is 2, I want to alert the user that their name is Bob, and if the number isn't 2, alert them that their name is Superman...
Complete noob/beginner here, sorry if this frustrates you, but I appreciate your understanding! The only way to learn!!! Cheers :)

your code is wrong, the first thing is that you should use "==" for comparison into if() (or "===" if you also want to check the type).
The second thing that I see is that you are checking the value of a variable called Random but the first line wrote some text on the page (document.write()) but it doesn't set the value of the Random variable, try replacing the first line with:
var Random = Math.floor((Math.random() * 5) + 1)
and this should work

Related

In school and trying to create the classic guess a number game. What did I do wrong?

This code is supposed to be a guess the number game. The object is to get JS to display an alert box that asks the user to guess a number. When they guess a number, the code is supposed to return the values of what they have guessed until they get it correct.
When I run the play key, an alert box does pop up, and says:
"Enter a guess between 1 and 100"
After that, even if I enter all 100 numbers, the box re-loads forever.
Here's what I have:
const game = {
title: 'Guess the Number!',
biggestNum: 100,
smallestNum: 1,
playerChoice: null,
secretNum: null,
//1. Add a prevGuesses property to the game object initialized to an empty array.
prevGuesses: [],
//2. Add a getGuess method to game that prompts the player to enter a guess with a message formatted as: Enter a guess between [smallestNum] and [biggestNum]: Hint- Use a template literal for the prompt message.
//3. Ensure that the getGuess method returns a value that is:
//-is a number, not a string
// -is between smallestNum and biggestNum, inclusive
// -Hints: This is a great use case for a while loop. parseInt returns NaN if the string cannot be parsed into a number
getGuess: function() {
while (this.playerChoice !== this.secretNum) {
var playerChoice = prompt(`Enter a guess between ${this.smallestNum} and ${this.biggestNum}: `);
var wholeNumber = parseInt(this.playerChoice);
if (this.wholeNumber > this.biggestNum) {
var wholeNumber = 100;
}
if (this.wholeNumber < this.smallestNum) {
var wholeNumber = 1;
}
if (typeof this.wholeNumber !== "number")) {
var wholeNumber = Math.floor(Math.random() * 100)
}
}
},
//4. From within the play method, invoke the getGuess method and add the new guess to the prevGuesses array
play: function() {
this.secretNum = Math.floor(Math.random() *
(this.biggestNum - this.smallestNum + 1)) + this.smallestNum;
game.getGuess();
this.prevGuesses.push(this.wholeNumber);
//6 the play method should end(return) when the guess matches the secretNum
if (typeof(this.wholeNumber) === "number" && this.wholeNumber !== this.secretNum) {
game.render();
}
},
// 5. Add a render method to game that play will call after a guess has been made that alerts:
// -if the secret has been guessed: "Congrats! you guessed the number in [x] guesses!"
// otherwise
// -"Your guess is too [high|low]"
// "Previous guesses: x, x, x, x"
// Hints: render wont be able to access any of play's local variables, e.g., guess, so be sure to pass render any arguments as needed. Template literals not only have interpolation, they honor whitespace - including line breaks! The list of previous guesses can be generated using the array join method.
render: function() {
if (this.wholeNumber === secretNum) {
alert(`Congrats! You guessed the number in ${game.prevGuesses.length} guesses!
Previous guesses: ${prevGuesses}`);
} else if (this.wholeNumber > this.secretNum) {
alert(`Your guess is too high!
Previous guesses: ${this.prevGuesses}`);
game.guess();
} else if (this.wholeNumber < this.secretNum) {
alert(`Your guess is too low!
Previous guesses: ${this.prevGuesses}`);
game.guess();
}
}
};
game.play();
/*
Allow the player to continually be prompted to enter their guess of what the secret number is until they guess correctly
If the player has an incorrect guess, display an alert message that informs the player:
Whether their guess is too high, or too low, and...
A list of all the previously guessed numbers (without showing the square brackets of an array)
If the player has guessed the secret number:
Display an alert message that congrats the player and informs them of how many guesses they took
End the game play*/
/*
Bonus: when play is run, immediately prompt the player to enter the smallest and biggest numbers instead of having them pre-set*/
The research that I've done: I've googled as many pages as I could find and youtube tutorials on functions, play object, loops within arrays, anything that I could think of that's related to the types of objects in this code.
the comment text is from the assignment. While I was working on it, I put the comments next to the code that I was working on.
I really am only a few weeks into coding and appreciate any feedback.
This is the original code that I was provided:
const game = {
title: 'Guess the Number!',
biggestNum: 100,
smallestNum: 1,
secretNum: null,
play: function() {
this.secretNum = Math.floor(Math.random() *
(this.biggestNum - this.smallestNum + 1)) + this.smallestNum;
}
};
There are several issues with your code:
this.wholeNumber never receives a value, so that will not work. Also, it does not seem the purpose of this exercise to have such a property. You should not have to store the user's guess in a new property this.wholeNumber. See next point:
The goal of getGuess is to return a number, but there is no return statement. You seem to want to store the number in a property, but that is not the assignment.
Related to this: in play you should get the guessed number as a return value from the call to getGuess
The goal of getGuess is not to wait for the user to guess right, only for the user to make a valid guess (within range and not NaN). So the condition of your while loop is not correct.
getGuess does not verify that parseInt returned NaN. Note that the type of NaN is "number", so the last if's condition will never be true. You should use the isNaN function, or better Number.isNaN.
play should always call render, not only when the guess is right.
render should be called by passing it an argument (the guessed number), and thus the render method should define a parameter for it.
The render method should not call game.guess(). That is not its job.
The play method should not put a new value in secret, otherwise the user will be playing against a moving target :) The secret should be set once in the main program
The main program -- where you currently just have game.play() -- should have the looping logic, which you had tried to implement elsewhere. Here is where you should repeat calling game.play() until the guess is right. It is also here where you should display alert messages about guesses that are too low, too high, ...etc.
There is no clear instruction where the main program should get the latest guess from. It can get it from game.prevGuesses, but I would suggest that the play method also returns the latest guess, just like getGuess should do.
Take note of the other instructions that are given in comments for the main program. For instance, when the user has guessed right you should alert after how many attempts they got it right. Think of which property can help you to know this number of attempts. Hint: length.
I will not provide the corrected code here, as I think with the above points you have enough material to bring this exercise to a good end. Happy coding.
Use parentheses to invoke the play function.
game.play();

How to swap two numbers using javascript function with one parameter

My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.
function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed
I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!
Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.

How to check if a variable has increased (JavaScript)

I want my code to check if a variable has increased. For example, I have a function that looks for the letter A in a text box, which runs every time a key is pressed. Then it counts the number of A's it has found. Then I want to alert me everytime a new A is written. I thought I could do this easily by just checking if the var numberOfA has increased in an if statement, and if it has to alert me, but I can't figure it out. I have tried using ++ and =/== in my if statement, but it alerts me every single time a letter is typed, instead of only everytime an A has been typed. All help is appreciated, I'm pretty new at this.
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
var numberOfA = sentence.length;
if (numberOfA = numberOfA +1) {
alert(" The letter A has been typed ");
}
}
Several problems.
When you write numberOfA = numberOfA + 1, you actually assign a value to numberOfA. Use a === b if you want to test equality.
Also, if you decide to use numberOfA to store the previous count, then you need to compare that with the current sentence.length value.
As a side note: if you are new, then invest time in learning how to use the debugger (e.g. in the browser dev tools). It will save you a lot of time and help you really understand what is happening.
You can not check numberOfA = numberOfA + 1 in your if statement. You can try this -
var numberOfA = 0;
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
if (sentence.length > numberOfA) {
numberOfA = sentence.length;
alert("The letter A has been typed. In your sentence A has found "+numberOfA+" times.");
}
}

Javascript Random Guess Game

https://jsfiddle.net/andrew_jsfiddle/eyLyqajz/1/
Assignment 1 - Using your JSFiddle account you are going to create a guessing game, only it will be the computer doing the guessing. Here is how it works - the computer will ask you for a number between 1 and 1000, it will check first to make sure your input is within the bounds.
Once you enter the number it will guess the number and do a comparison with the number you entered. It will output the results of the guess and continue to do this until it gets the correct answer. This is what the output of the program will look like (if I enter 329)
For this attempt I did:
var guessnum= new Guessnum(1000);
document.getElementById("click").onclick= function() {
guesslist()};
function guesslist() {
document.getElementById('guessnum').innerHTML= InsertGuess();
}
function InsertGuess() {
for (var a= 0; a < guessnum.length; a++){
guessnum[a] = Math.floor((Math.random() * 1000) + 1);
}
var show_guess="";
for (i=0; i < guessnum.length; i++){
show_array += "You guess" + guessnum[i] + "of " + i + "<br>";
}
return document.getElementById('guess').innerHTML=show_array;
}
Use a listener on the input with a global variable that contains the random number
var myRandomNumber;
input.addEventListener('input', function(){
}
)
You'll need to click first on the button though.
Fiddle
My friend, I think you are really confused. It wouldn't help to just create it for you. Break down the requirements to actionable steps and start from scratch. You want to create a guess game that you set a number. Think it as simply as possible:
Action 1 - Set a number -->
Create the field
Action 2 - Check if number is valid(1-1000) -->
Get the value entered and make the necessary checks
Action 3 - Computer tries to guess by selecting a num up to 1000 -->
Generate random num from 1-1000
Action 4 - Compare number with the one you set before -->
Simple comparison of generated number and the selected one
Action 5 - Proceed as needed -->
If it's the exact number it won and it will stop!
If it's higher then the next guesses should have this number as highest limit.
If it's lower then the next guesses should have this number as lowest limit.
Action 6 - Show guess and result of comparison --> Simply show the results of the previous actions
Action 7 - If not successful guess --> repeat until the number is guessed
Try to apply this kind of logic to all these problems.

Javascript coding

I am going nuts trying to write a JavaScript code, which requests from the user any sequence of numbers until such user enters 'N'.
If this happens, a message should pop up indicating the user that he reached the end of that sequence and then a new message pops up showing 'all' the numbers the user entered PLUS organising them in crescent order.
Any suggestions, please?
I would appreciate any help as I'm going mad right now thinking of anything.
If the array was specified, then I wouldn't have a problem, but since it's a random array, I can not seem to find the right answer.
What you want to do is something like this:
Get the user's numbers and save them, prefably in an array.
Loop through all the numbers and check if the number is N.
If so, alert the user.
Sort the array, alert the user.
Attempt to code:
// All the user's numbers
var UserNumbers = [15, 10, 11, 12, 13];
//The value to search for
var N = 12;
//Loop through the values
for(var i = 0; i < UserNumbers.Length; i++){
if(UserNumbers[i] == N){
//The number matches
alert("You reached the end of the sequence";
}
}
// I am not sure what you mean with cresent order so that you'll have to solve for yourself.
//Sort the UserNumbers here
//Store the message to show the user
var message = "";
//Loop through the values - now in correct order and save them to the message
for(var i = 0; i < UserNumbers.Length; i++){
//Add to the message
message += UserNumbers[i] + " ";
}
//Show the message - all the containing numbers
alert(message);
Although this is an helpful community I am pretty certain that we're not made out of teachers here to teach you how to code. Since this sounds to be an homework rather than a real life scenario, talk with your teacher or classmates. Good luck and next time, try to do some research before posting a question - there are plenty of tutorials for beginners out there.

Categories

Resources