How can i fix this undefined output text in javascript function [duplicate] - javascript

This question already has an answer here:
Why does this JavaScript code print "undefined" on the console?
(1 answer)
Closed 1 year ago.
I make a simple calculator using javascript. I am providing those code below. But the problem is when i run those code. i saw a undefined output. I dont know why that text is showing. I want to remove that.
function addition(x, y) {
var sum = x + y;
document.write("Addition of two number is : " + sum);
}
function substract(x, y) {
var sub = x - y;
document.write("Subtraction of two number is : " + sub);
}
function multiply(x, y) {
var multiply = x * y;
document.write("Multipication of two number is : " + multiply);
}
function division(x, y) {
var division = x / y;
document.write("Division of two number is : " + division);
}
var x = parseInt(prompt("Enter the first number : "));
var y = parseInt(prompt("Enter the second number : "));
var operator = prompt("Enter the operator : ");
if (operator == "+") {
document.write(addition(x, y));
} else if (operator == "-") {
document.write(substract(x, y));
} else if (operator == "*") {
document.write(multiply(x, y));
} else if (operator == "/") {
document.write(division(x, y));
} else {
document.write("Invalid Operator. Please choose operator between +,-,* or /. <br> Thanks for using our calculator. ");
}

Calling document.write(x) causes x to be written. If x is a function call, it will write whatever that function call returns. Since all of your functions don't explicitly return something, they return (here it comes) undefined.

Your operator functions don't return anything, they write directly to the page.
However the lines that execute these functions write to the page the return of these functions, which is undefined
So to solve this, you have 2 options:
replace document.write("blah") with return "blah" in operator functions
remove document.write() from the caller: document.write(addition(x, y))

Related

Generate a new random number each time function is called in Javascript

I am trying to learn javascript, I am playing with a game that picks a random number.
I would like to have 2 functions, random and guess. Random generates a new number between 1-10. Guess is where it checks if the number was guessed, if not re-runs the random function and generates a new number to try.
var x;
function random(){
let x = Math.floor((Math.random() * 10) + 1);
guess();
}
function guess(x){
if(x === 3){
alert('you are correct!');
}else{
alert('try again');
random();
}
}
random();
This just alerts try again every time, i'm guessing because it's not generating a new number each time the function is called?
How can you create the random function so it generates a new number each time its called?
***** Correction, it appears to generate a new number but x is undefined within the guess function**
The x in the guess() is the x that gets passed to it as a parameter. I would remove the var x; declaration and pass a value when calling like guess(x)
function random(){
const x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x){
if(x === 3){
alert('you are correct!');
}else{
alert('try again');
random();
}
}
random();
The guess function's signature says that it takes a parameter x, but you're not passing any value to the function when it's called, so it's assigning undefined to x when it runs guess, which will never equal 3. You can take 2 approaches to fix this. First, you could make x a global variable by getting rid of the let where you define x in the random function and removing x from guess's function signature, like so:
var x;
function random() {
x = Math.floor((Math.random() * 10) + 1);
guess();
}
function guess() {
if (x === 3) {
alert(x + '- you are correct!');
}
else {
alert(x + '- try again');
random();
}
}
random();
Or, you could use x as a parameter for the guess function by removing the var x; global declaration and passing x to guess when you call it in the random function, like so:
function random() {
let x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x) {
if (x === 3) {
alert(x + '- you are correct!');
}
else {
alert(x + '- try again');
random();
}
}
random();
I personally wouldn't even have a random function. I'd just define x within guess and call guess from within itself. And, I'd use randojs.com to make the randomness more readable. Here's how I'd do it:
function guess() {
let x = rando(1, 10);
if (x === 3) return alert(x + '- you are correct!');
alert(x + '- try again');
guess();
}
guess();
<script src="https://randojs.com/1.0.0.js"></script>
Note that the return statement would stop the execution of the function right then and there, so it wouldn't progress to the "try again" alert if the number was guessed correctly.
Here's some detailed code that will help you understand how to run such a game in the browser.
See the comments for explanation of how it works (and search for information on MDN to learn more about any particular topic.)
Happy coding!
// Identifies HTML elements
const
guessInput = document.getElementById("guessInput"),
outputParagraph = document.getElementById("outputParagraph");
// Makes a global variable that all functions can access
let globalNum;
// Invokes the main function
playGame();
function playGame(){
// Invokes the randomizer function and stores the result in the global variable
globalNum = getRandomNumber();
//console.log(globalNum);
// Invokes the output function
setOutput("Guess a number from 1 to 10");
// Assigns a function that will be invoked whenever the user changes the input field
guessInput.addEventListener("change", respondToGuess);
// Puts the focus in the input element
guessInput.focus();
}
// Defines a listener function that can automatically see the triggering event
function respondToGuess(event){
// Gets the `target` element of the event and stores it in a local variable
const localReferenceToInputElement = event.target
// The text of an `<input>` element lives in its "value" property
const inputText = localReferenceToInputElement.value;
// Tries to convert the text string to an integer (and store it locally as 'guess')
let guess = parseInt(inputText);
// If the conversion failed, changes the output accordingly
if(!guess){ setOutput("Please enter a valid number"); }
// If the number is out of range, changes the output
else if(guess < 1 || guess > 10){ setOutput("Only numbers from 1 to 10 are allowed"); }
// If the guess doesn't match the stored number, changes the output
else if(guess !== globalNum){ setOutput("Try again..."); }
// If we got this far, the guess was correct, so changes output and ends game
else{
setOutput("You guessed it!");
reset();
}
}
function getRandomNumber(){
// Returns a random number into whatever function called this function
const x = Math.floor((Math.random() * 10) + 1);
return x;
}
function setOutput(outputText){
// The text of a paragraph element lives in its `innerHTML` property
outputParagraph.innerHTML = outputText;
}
function reset(){
// Clears the input and stops listening for changes
guessInput.value = "";
guessInput.removeEventListener("change", respondToGuess);
}
<input id="guessInput" />
<p id="outputParagraph"></p>
I have done some changes to your code.
You have problem with the concept of function calling function.
In real code it will kill your memory.. your function calls function the function not close and call the function again and again... and its fill the memory .
var x;
// flag correct will close the loop when you have right umber
var correct = false;
function random() {
x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x) {
if (x === 3) {
alert('you are correct!');
// if number is right flag is up
correct = true;
} else {
alert('the number is ' + x + ' try again');
}
}
// loop until the number is right
while (correct != true) {
random();
}

compare math equations prior to evaluation javascript

I'm running through algebra and attempting to create a JavaScript tester function which compares two equations and determines if they are considered associative properties. In other words, if I group (a + b) + c vs. a + (b + c) the result will be the same. Multiplication and addition only.
Up to this point, I've attempted to build a simple function that resolves whether the final value is equal to the compared equation value. What I would like is if I was able to compare both equations without their parenthesis. Thinking I need to look up regular expressions... but looking for a little help on direction.
let a = 1,
b = 2,
c = 3,
number1 = (a * b) * c,
number2 = a * (b * c);
function isAssociative(num1, num2) {
let answer = num1 === num2;
return `Are ${num1} and ${num2} associative... ${answer}`;
}
console.log(isAssociative(number1, number2));
Currently, this results in, 'Are 6 and 6 associative... true'. This is what I want, but if I changed the second argument to a static 6 when calling the function... then this is not an associative combo and I would like it to return false.
You can use Mathjs and the simplify method:
console.clear();
term_a = 'a + ( b + c )'
term_b = '( a + b ) + c';
tree_a = math.simplify(term_a);
tree_b = math.simplify(term_b);
console.log(term_a, tree_a.equals(tree_b) ? 'equals' : 'differs from', term_b);
term_a = 'a + ( b + c + d )'
term_b = '( a + b ) + c';
tree_a = math.simplify(term_a);
tree_b = math.simplify(term_b);
console.log(term_a, tree_a.equals(tree_b) ? 'equals' : 'differs from', term_b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.4.2/math.min.js"></script>
I found an answer I'm satisfied with.
let number1 = prompt('Enter an equation').toString().replace(/[^0-9,+,*]+/g,''),
number2 = prompt('Enter equation 2').toString().replace(/[^0-9,+,*]+/g,'');
function isAssociative (num1, num2) {
if (num1 === num2) {
return eval(num1) === eval(num2);
} else {
return false;
}
}
alert(isAssociative(number1, number2));
I could wait for the numbers to enter the function as a string, check for parenthesis first to verify it even qualifies... if parenthesis exist, then I could execute the regEx code and if they don't exist return 'not associative' at that point. For now, this works as well as I want it to.

JavaScript if answer is correct, generate new string

I have a program that randomly generates two numbers (x and y) and asks the user to multiply them. Once they multiply them, it will tell them if they get it right or wrong. The thing I'm having problems with is that if they get the answer correct, it should then generate a new set of numbers. I'm not sure how to make the program perform that function again. Also it has to clear the answer field no matter if they get it right or wrong. Thanks!
var x, y; // global variables for randomly generated numbers
var correct = ['Very good!', 'Excellent!', 'Correct - Nice work!', 'Correct - Keep up the good work!'];
var incorrect = ['No. please try again.', 'Wrong. Try once more.', 'Incorrect - Dont give up!', 'No - Keep trying.'];
// getting two random numbers between 1-12 then assigning them to x and y
function generateNumbers() {
function aNumber() {
return Math.floor((Math.random() * 12) + 1);
}
x = aNumber();
y = aNumber();
}
// generating the question that will be used with the random numbers x and y
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
window.alert(correctans);
var total = document.getElementById('total').value++;
}
else { // incorrect
window.alert(incorrectans);
}
}
You're not calling the genQuestion function, and it makes little sense to redefine it.
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
//call genQuestion to create new question
genQuestion();
window.alert(correctans);
var total = parseInt(document.getElementById('total').value)++;
}
else { // incorrect
window.alert(incorrectans);
}
//clear 'answer' field
document.getElementById('answer').value = '';
}

JS concatenating object property values (numeric) instead of adding

In an intersect function, that checks if two objects intersect on the canvas, I need to add the obj.x and obj.width property to get the obj.right(side). Somehow the properties are concatenated instead of added. It probably has something to do with reference-type but I don't see how I can capture the values in primitive types.
function intersects(obj1, obj2) { // checks if 2 shapes intersect
var ob2x = obj2.x;
var ob2width = obj2.width;
if (obj1.x > +obj2.x + 70 || obj2.x > +obj1.x + 70) {
console.log('false : obj1.x=' + obj1.x + ' obj2.right=' + parseInt(ob2x) + parseInt(ob2width));
return false;
}
if (obj1.y > +obj2.y + +obj2.height || obj2.y > +obj1.y + +obj1.height) {
console.log('false');
return false;
}
console.log('false');
return true;
}
I have already tried to get the number value of the object property, as you can see. Didn't work
Also tried parseInt(), which didn't work.
I suppose I can put the values seperately as parameters in the fuctions but I was hoping to keep it as short as possible, because kids need to use it.
You need to add a grouping operator:
... + (parseInt(ob2x) + parseInt(ob2width)) + ...
to isolate that part of the expression so that + is seen as addition. Otherwise, the full expression keeps it as concatenation, even though you convert those to values to numbers (because if a string is anywhere in the expression being evaluated, + means concat).
E.g.
var x = 5;
var y = 6;
console.log('Sum: ' + x + y); // 56
console.log('Sum: ' + (x + y)); // 11

JavaScript Help(It's pretty simple im a beginner)

function mathProb() {
var x = parseInt(prompt("Enter first integer", ""));
var y = parseInt(prompt("Enter the second integer", ""));
var operand = prompt("Enter type of operation", "");
if (operand == "+" || "add") {
var sum = x + y;
document.write("Your sum is " + sum);
} else if (operand == "-") {
var difference = x - y;
document.write("Your difference is " + difference);
} else if (operand == "*") {
var product = x * y;
document.write("Your product is " + product);
} else if (operand == "/") {
var quotient = x / y;
document.write("Your quotient is " + quotient);
} else {
document.write("Oops something went wrong");
}
}
Well to start I am reading a book on JavaScript and have been doing pretty well, I am now on functions and was getting those until parameters were introduced can someone explain what a parameter is in a clear simple way?
Why does this function work when named function mathProb() and function mathProb(x,y,operand)?
And a third question off of the previous one is why when I call the function in html
(<input type="button" value="Calculator" onclick="mathProb()"/>)
I have to use mathProb() even if its named mathProb(x,y,operand). If I call it using that name it wont work. Please help?
First, the line:
if(operand=="+"||"add")
Will always be true, as the expression "add" will always return a true-ish value. You probably mean to use:
if(operand=="+" || operand=="add")
Your question about parameters is probably a pretty broad topic. Basically, a parameter is a variable given to a function so that the function can be generalized to work with any data. For example, if you wanted to write a function that can add two numbers, the function must know which two numbers to add. These numbers would be supplied as parameters:
function add(x, y)
{
return x + y; // x and y are variables known within this function
}
You'd then call your function as so:
var oneplusone = add(1, 1); // Adds 1 and 1
Using this knowledge, you could rewrite your code as this:
function mathProb(x, y, operand)
{
// No need for var x, etc as these can now be passed in..
}
Then call your function:
mathProb(
parseInt(prompt("Enter first integer","")), // This is x
parseInt(prompt("Enter the second integer","")), // This is y
prompt("Enter type of operation","") // This is operand
);
Keep in mind you could still call your function mathProb without the parameters:
mathProb();
...if you really wanted to. JavaScript does allow this (unlike many other languages). However, within your function, the variables x, y and operand will be undefined which might cause unexpected results if you don't account for that.
You need call and pass function like mathProb(1,2,'+')
HTML:
<input type="button" value="Calculator" onclick="mathProb(1,2,'+')"/>
Javacript:
function mathProb(x,y,operand)
{
//var x = parseInt(prompt("Enter first integer",""));
//var y = parseInt(prompt("Enter the second integer",""));
//var operand = prompt("Enter type of operation","");
if(operand=="+"|| operand=="add")
{
var sum = x+y;
document.write("Your sum is " +sum);
}
else if(operand=="-")
{
var difference = x-y;
document.write("Your difference is " +difference);
}
else if(operand=="*")
{
var product = x*y;
document.write("Your product is " +product);
}
else if(operand=="/")
{
var quotient = x/y;
document.write("Your quotient is " +quotient);
}
else
{
document.write("Oops something went wrong");
}
}

Categories

Resources