Home > other >  JavaScript if function in console
JavaScript if function in console

Time:08-20

Hi I am very basic with JavaScript yet but I guess I have an understanding issue here...

I want to have at the end an output that gives the numer/age that is input and the text that is defined for each age specifically.

In the console I get it in 2 lines unfortunately and I really don't know how to change it:

Example: (input = 15)
you cannot do anything 
You are null years old and undefined! 
console.clear();

let input = prompt("Enter your age!");
let result = whatCanIDo(input);


function whatCanIDo(input) {

  if (input <= 15) {console.log("you cannot do anything")}
  if (input >= 16) {console.log("you already can do things")}
  if (input >= 18) {console.log("you can do everything")}
  
}
  
console.log("You are "   input   " years old and "   result   "!"); 

CodePudding user response:

You need to return the string value from the function whatCanIDo instead of (console.log) it, so that it is printed as undefined (nothing returned) and for the prompt, it works fine, make sure you enter something there and click ok!

Here is a working example with hard coded input (years)

console.clear();

let input = 15; //replace it with your code; prompt("Enter your age!");
let result = whatCanIDo(input);


function whatCanIDo(input) {

  if (input <= 15) {return "you cannot do anything" }
  if (input >= 16) {return "you already can do things"}
  if (input >= 18) {return "you can do everything" }
  
}

console.log("You are "   input   " years old and "   result   "!"); 

CodePudding user response:

See it's work!

let input = prompt("Enter your age!");
let result = whatCanIDo(input);


function whatCanIDo(input) {

  if (input <= 15 ) {return "you cannot do anything" }
  if (input >= 16 && input <= 17 ) {return "you already can do things"} /* <-- Edited */
  if (input >= 18 ) {return "you can do everything" }
  
}

console.log("You are "   input   " years old and "   result   "!"); 

  • Related