First Steps in JavaScript and Building a Calculator
Introduction:
JavaScript is a versatile and widely-used programming language that plays a central role in web development. With its ability to add interactivity and functionality to web pages, JavaScript is a must-learn language for anyone interested in front-end or full-stack web development.
For those with a particular interest in JavaScript security and protecting web applications from cyber threats, this language becomes even more critical. Understanding how to secure web applications and guard against web-based attacks like XSS is essential in today’s digital landscape.
In this article, we’ll introduce JavaScript by building a simple calculator. By the end of this tutorial, you’ll have a basic understanding of JavaScript syntax and how to use it to create interactive web applications. Whether you’re focusing on front-end development, full-stack engineering, or security, JavaScript is a valuable skill that opens doors to a wide range of opportunities.
What Is JavaScript ?
JavaScript is a high-level, dynamically typed scripting language primarily known for its use in web development. It allows developers to add dynamic behavior to websites, making them more interactive and responsive. JavaScript can manipulate HTML and CSS, handle user input, and communicate with web servers to fetch and update data.
Setting Up Your Environment
To get started with JavaScript, you don’t need any special development environment. All you need is a web browser and a text editor.
For this tutorial, we’ll use a simple HTML page to demonstrate JavaScript’s capabilities.
Here’s a basic HTML structure for our calculator:
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<! - Calculator content goes here →
</body>
</html>
Writing JavaScript : Adding two numbers
Now, let’s start adding JavaScript to our HTML page. JavaScript code can be placed within the HTML document between <script> tags. We’ll create functions to handle user input and perform calculations. Here’s a simple example of a JavaScript function that adds two numbers:
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
</head>
<body>
<input type="text" id="num1" placeholder="Enter first number">
<input type="text" id="num2" placeholder="Enter second number">
<button onclick="addNumbers()">Add</button>
<div id="result">Result will be displayed here</div>
<script>
function addNumbers() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var result = num1 + num2;
document.getElementById("result").innerText = "Result: " + result;
}
// Define similar functions for subtraction, multiplication, and division
</script>
</body>
</html>
In this code, we define a function called addNumbers that prompts the user for two numbers, adds them together, and then displays the result in the same page.
Building a Simple JavaScript Calculator
We are now adding functions for subtraction, multiplication, and division to our program, as well as comments that are very useful for code comprehension and maintenance.
This code creates a simple calculator with input fields for two numbers and buttons to perform addition, subtraction, multiplication, and division.
<!DOCTYPE html>
<html>
<head>
<title>Simple JavaScript Calculator</title>
</head>
<body>
<!-- Input fields for entering numbers -->
<input type="text" id="num1" placeholder="Enter first number">
<input type="text" id "num2" placeholder="Enter second number">
<!-- Buttons to perform operations -->
<button onclick="addNumbers()">Add</button>
<button onclick="subtractNumbers()">Subtract</button>
<button onclick="multiplyNumbers()">Multiply</button>
<button onclick="divideNumbers()">Divide</button>
<!-- Display the result here -->
<div id="result">Result will be displayed here</div>
<script>
// Function to add two numbers
function addNumbers() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var result = num1 + num2;
document.getElementById("result").innerText = "Result: " + result;
}
// Function to subtract two numbers
function subtractNumbers() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var result = num1 - num2;
document.getElementById("result").innerText = "Result: " + result;
}
// Function to multiply two numbers
function multiplyNumbers() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var result = num1 * num2;
document.getElementById("result").innerText = "Result: " + result;
}
// Function to divide two numbers
function divideNumbers() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
if (num2 === 0) {
document.getElementById("result").innerText = "Result: Division by zero is not allowed";
} else {
var result = num1 / num2;
document.getElementById("result").innerText = "Result: " + result;
}
}
// Title: Simple JavaScript Calculator
// Author: Larbi OUIYZME
// Version: 1.0
</script>
</body>
</html>
Building Another JavaScript Calculator
Now, let’s expand our JavaScript code to build a JavaScript calculator.
<!DOCTYPE html>
<html>
<head>
<title>Javascript Calculator - Version 1.0</title>
<style>
#calculator {
width: 300px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
text-align: center;
}
#calculator button {
width: 60px;
height: 60px;
font-size: 18px;
margin: 5px;
cursor: pointer;
}
#display {
width: 80%;
height: 40px;
font-size: 24px; /* Ajustez la taille de la police selon vos préférences */
margin: 10px auto;
}
</style>
</head>
<body>
<h1>Javascript Calculator</h1>
<p>Auteur: Larbi OUIYZME</p>
<p>Version: 1.0</p>
<div id="calculator">
<input type="text" id="display" disabled>
<br>
<button onclick="addToDisplay('7')">7</button>
<button onclick="addToDisplay('8')">8</button>
<button onclick="addToDisplay('9')">9</button>
<button onclick="addToDisplay('+')">+</button>
<br>
<button onclick="addToDisplay('4')">4</button>
<button onclick="addToDisplay('5')">5</button>
<button onclick="addToDisplay('6')">6</button>
<button onclick="addToDisplay('-')">-</button>
<br>
<button onclick="addToDisplay('1')">1</button>
<button onclick="addToDisplay('2')">2</button>
<button onclick="addToDisplay('3')">3</button>
<button onclick="addToDisplay('*')">*</button>
<br>
<button onclick="addToDisplay('0')">0</button>
<button onclick="clearDisplay()">C</button>
<button onclick="calculateResult()">=</button>
<button onclick="addToDisplay('/')">/</button>
</div>
<script>
// This function is used to add the specified 'value' to the display.
function addToDisplay(value) {
document.getElementById('display').value += value;
}
// This function clears the display by setting its value to an empty string.
function clearDisplay() {
document.getElementById('display').value = '';
}
// This function calculates the result of the expression in the display using the 'eval' function.
// It handles errors and displays 'Error' if the expression is invalid.
function calculateResult() {
try {
// Evaluate the expression in the display and update the display with the result.
document.getElementById('display').value = eval(document.getElementById('display').value);
} catch (error) {
// If an error occurs during evaluation, display 'Error' on the display.
document.getElementById('display').value = 'Error';
}
}
</script>
</body>
</html>
In the provided JavaScript code, arithmetic operations are handled by the calculateResult() function. Here’s how it works:
- The user enters a mathematical expression in the user interface, for example, “2 + 3” or “10 * 5.”
- When the user presses the button to calculate the result, the calculateResult() function is called.
- Inside the calculateResult() function, there is a try…catch block to handle potential errors. The eval() function is used to evaluate the expression contained in the display element.
- If the expression is valid, eval() will return the result of the arithmetic operation, and this result will then be displayed in the display element using document.getElementById(‘display’).value = eval(…). For example, if the expression was “2 + 3,” the display would show “5” after evaluation.
- If an error occurs during evaluation (for example, if the user enters an invalid expression like “2 / 0”), the code inside the catch block will be executed, and the display element will show “Error.”
In summary, arithmetic operations are performed using the JavaScript eval() function, which evaluates a string containing a mathematical expression and returns its result. However,
it’s important to note that using eval() can be risky due to security issues related to code injection, so it’s essential to validate and secure user inputs if they are used with eval().
Links to Javascript project :
Resources for Mastering JavaScript : From Basics to Beyond
Here are some popular online resources for learning web development, including JavaScript. They offer tutorials, examples, and interactive coding exercises. Many beginners find them useful due to their straightforward and practical approach to learning web technologies.
- W3Schools JavaScript Tutorial
- MDN JavaScript Guide
- freeCodeCamp
- Codecademy
- JavaScript.com
- Eloquent JavaScript
- JavaScript30
- LeetCode
- And many more in YouTube
Conclusion
JavaScript is a powerful language that can be used to create interactive web applications. In this introductory article, we built a simple calculator to demonstrate the basics of JavaScript. As you continue to learn and practice JavaScript, you’ll discover its vast potential for creating dynamic and engaging web experiences.
In future articles, we’ll explore more advanced JavaScript topics and show you how to build more complex web applications. Stay tuned for more exciting JavaScript tutorials!