Skip to main content

Command Palette

Search for a command to run...

Play with User Input and Constants in JavaScript ๐Ÿš€

Published
โ€ข5 min readโ€ขView as Markdown
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 variable username. ๐Ÿšช

    • console.log(username): Outputs the value of username to 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 the username variable. โœ๏ธ

  • 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 returns NaN (Not-a-Number). ๐Ÿšซ

    • age += 1: Adds 1 to the numerical value of age. โž•

    • console.log(age, typeof age): Displays the new value of age and 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 to number. ๐Ÿงฉ

    • 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 to false. โŒ

      • The number 0 converts to false, while any other number converts to true. ๐Ÿ”ข

      • undefined converts to false. โ“

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 is NaN. 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 PI as 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. โš ๏ธ

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 PI ensures consistent and correct calculations. โš™๏ธ

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 const for primitive data types like numbers, strings, or booleans. ๐Ÿ”’


More from this blog

Learning In Public

7 posts