How to Use Basic Input and Output in JavaScript

Posted by

  1. To output data to the console, use the console.log() function. You can pass a string or a variable as an argument to console.log(). For example:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

console.log('Hello, world!');

let message = 'Hello, world!';
console.log(message);

[/dm_code_snippet]

  1. To get input from the user, use the prompt() function. This function will display a dialog box with a message and a text field, and it will return the value entered by the user as a string. For example:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let name = prompt('What is your name?');
console.log(`Hello, ${name}!`);

[/dm_code_snippet]

  1. To display a dialog box with a message and a OK/Cancel button, use the confirm() function. This function will return true if the user clicks OK, and false if the user clicks Cancel. For example:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let result = confirm('Do you want to continue?');
if (result) {
console.log('User clicked OK');
} else {
console.log('User clicked Cancel');
}

[/dm_code_snippet]