Header Ads

How do you find the sum of two numbers using JavaScript?

In this problem we have to take two number from the user as a input and get there sum. Here we will not be using HTML to get the inputs instead we will use node Js Module prompt-sync Using this module we can give inputs in the console without using HTML or Browser


Prerequisites to use prompt-sync Module :

=> Install Node Js in your System from it's official website 
=> After the completion of installation check if it properly installed by checking it's version
=> Open Command Prompt and run the following commands :
     node --version 
This will return your node Js version, if it say no external or internal command found then add node Js to environment variables.
Now check npm version using the command  npm --version 
If no error is shown then you are ready to use Node Js.
=> Run the following command to install prompt-sync
     npm install prompt-sync 
Now you are ready to use prompt sync, lets jump towards the code

Code :

// loading prompt-sync module
const prompt = require("prompt-sync")();

// declaring function to add to numbers
function addition(n1, n2){
    return parseInt(n1) + parseInt(n2);
}

// taking inputs and calling addition
let a = prompt("Enter First number : ","");
let b = prompt("Enter Second number : ","");

var add = addition(a, b);
console.log(add);

Output :

Enter First number : 8
Enter Second number : 6
14

Explanation :

Create a object and load prompt-sync Module in it using require method.
const prompt = require("prompt-sync")();
prompt is object here and () is prompt function
Now create function which will take 2 arguments i.e., n1 and n2 and return there sum
Note : prompt takes inputs as string, so parse n1 and n2 as integer using parseInt()
declare variables to take input
let a = prompt("Enter First number : ","");
let b = prompt("Enter Second number : ","");
prompt can take 2 argument, the text to be prompted and its default value
Call the function and store it's value in a variable and print the value using console.log

Post a Comment

0 Comments