Play with User Input and Constants in JavaScript ๐

How to Accept JavaScript User Input ๐ฌ
1. Easy Way: Using window.prompt() ๐ ๏ธ
Description: Quickly accept user input via a simple pop-up dialog box.
let username = window.prompt("What's your username?"); console.log(username);Explanation:
window.prompt(): Opens a dialog box that prompts the user for input, which is stored in the variableusername. ๐ชconsole.log(username): Outputs the value ofusernameto the console for debugging purposes. ๐
2. Professional Way: Using an HTML Text Box ๐
Description: Collect user input via an HTML text box and a submit button.
let username; document.getElementById("mySubmit").onclick = function() { username = document.getElementById("myText").value; document.getElementById("myH1").textContent = `Hello ${username}`; };Explanation:
HTML Structure:
Text Box (
<input id="myText">): Allows the user to input text. ๐ฅSubmit Button (
<button id="mySubmit">Submit</button>): Triggers the function to capture and process the input. ๐ฑ๏ธHeading (
<h1 id="myH1">Welcome</h1>): Displays a greeting that updates with the user's input. ๐
JavaScript Logic:
document.getElementById("mySubmit").onclick: Adds an event listener to the submit button, triggering a function when clicked. ๐ฏusername = document.getElementById("myText").value: Retrieves the value entered in the text box and assigns it to theusernamevariable. โ๏ธdocument.getElementById("myH1").textContent: Updates the headingโs text content to greet the user by name. ๐
JavaScript Type Conversion ๐ฑ
1. What is Type Conversion? ๐ง
Description: Type conversion is the process of changing the data type of a value to another type, such as converting strings to numbers, or numbers to booleans.
Why is it Important?
- User inputs are typically received as strings. To perform mathematical operations or logical checks, it's often necessary to convert these strings into numbers or booleans. ๐งฎ
2. Converting User Input from String to Number ๐ข
Example:
let age = window.prompt("How old are you?"); age = Number(age); // Converts the string input to a number age += 1; // Increments age by 1 console.log(age, typeof age);Explanation:
window.prompt(): Captures user input as a string. ๐Number(): Converts the string input to a number. If the input is not a valid number, it returnsNaN(Not-a-Number). ๐ซage += 1: Adds 1 to the numerical value ofage. โconsole.log(age, typeof age): Displays the new value ofageand its data type, confirming the conversion. ๐
3. Converting Various Data Types ๐
Example:
let x = "pizza"; let y = "pizza"; let z = "pizza"; x = Number(x); // Attempts to convert "pizza" to a number y = String(y); // Keeps "pizza" as a string z = Boolean(z); // Converts "pizza" to a boolean console.log(x, typeof x); // Outputs: NaN 'number' console.log(y, typeof y); // Outputs: 'pizza' 'string' console.log(z, typeof z); // Outputs: true 'boolean'Explanation:
Converting Non-numeric Strings to Numbers: Attempting to convert a non-numeric string like "pizza" to a number results in
NaN, but its type changes tonumber. ๐งฉString Conversion: Converting a string to a string has no effect; the value and type remain unchanged. โ๏ธ
Boolean Conversion:
Non-empty strings convert to
true. โEmpty strings (
"") convert tofalse. โThe number
0converts tofalse, while any other number converts totrue. ๐ขundefinedconverts tofalse. โ
4. Practical Use-Cases for Type Conversion ๐ ๏ธ
Validating User Input:
Empty Input Check:
let userInput = ""; let isInputProvided = Boolean(userInput); // Converts to false โNumeric Input Validation:
let userAge = window.prompt("Enter your age:"); userAge = Number(userAge); if (isNaN(userAge)) { console.log("Please enter a valid number for age."); } else { console.log(`Your age is ${userAge}.`); }Explanation:
isNaN(): Checks if the value isNaN. Useful for validating numerical inputs. ๐Boolean Checks: Converting user input to a boolean helps in checking if any input was provided. ๐ฅ
JavaScript Constants ๐ซ
1. What is a Constant (const)? ๐
Description: A constant (
const) is a variable whose value cannot be changed once it is assigned.Example:
const PI = 3.14159;Explanation:
Immutability: Once a value is assigned to a constant, any attempts to reassign it will result in an error. ๐
Best Practice: Use constants for values that should remain the same throughout your program, like
PI. โ๏ธ
2. Why Use const? ๐
Example:
let radius; let circumference; const PI = 3.14159; document.getElementById("mySubmit").onclick = function(){ radius = document.getElementById("myText").value; radius = Number(radius); // Converts the input to a number circumference = 2 * PI * radius; document.getElementById("myH3").textContent = circumference + "cm"; };Explanation:
Security: By declaring
PIas a constant, its value cannot be modified, which prevents incorrect calculations. ๐ก๏ธBest Practice: It's common to use uppercase letters for constant names (e.g.,
PI) to signify that the value is unchangeable. โ๏ธ
3. Attempting to Change a Constant โ
Example:
const PI = 3.14159; PI = 420.69; // This will throw an error ๐ซExplanation:
- Error Handling: If you try to reassign a value to a constant, JavaScript will throw an error (
TypeError: Assignment to constant variable), preventing the program from running with an incorrect value. โ ๏ธ
- Error Handling: If you try to reassign a value to a constant, JavaScript will throw an error (
4. Practical Implementation Using const ๐ ๏ธ
Example:
const PI = 3.14159; let radius; let circumference; document.getElementById("mySubmit").onclick = function(){ radius = document.getElementById("myText").value; radius = Number(radius); circumference = 2 * PI * radius; document.getElementById("myH3").textContent = circumference + "cm"; };Explanation:
- This program calculates the circumference of a circle based on the user's input for the radius. The constant
PIensures consistent and correct calculations. โ๏ธ
- This program calculates the circumference of a circle based on the user's input for the radius. The constant
5. Extra Tips ๐ฎ
Note on Naming Conventions:
It's a good practice to capitalize constant names (e.g.,
PI) to signify they are unchangeable values. ๐Use
constfor primitive data types like numbers, strings, or booleans. ๐



