Javascript Basic Input / Output

Posted by

In JavaScript, you can use the console.log() function to output data to the console. 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!');

[/dm_code_snippet]

This will print the string 'Hello, world!' to the console.

You can also use console.log() to output the value of a variable, like this:

[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 message = 'Hello, world!';
console.log(message);

[/dm_code_snippet]

To get input from the user, you can 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]

This code will display a dialog box with the message 'What is your name?', and when the user enters their name and clicks OK, the value will be stored in the name variable and printed to the console.

You can also use the confirm() function to display a dialog box with a message and a OK/Cancel button. 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]