Welcome to our comprehensive JavaScript (JS) Arithmetic tutorial! This lesson is designed for beginners and intermediate learners, and we'll explore various arithmetic operations in JavaScript, along with real-world examples and practical applications.
JavaScript is a versatile programming language that is essential for web development. Arithmetic operations are fundamental in JavaScript, allowing us to perform calculations on numbers. Let's get started by understanding the different arithmetic operators in JavaScript.
Here are the basic arithmetic operators in JavaScript:
+ (addition)- (subtraction)* (multiplication)/ (division)% (modulus)++ (increment)-- (decrement)Let's dive into basic arithmetic operations using examples.
// Basic addition
let a = 5;
let b = 3;
let sum = a + b;
console.log(sum); // Output: 8// Basic subtraction
let a = 10;
let b = 3;
let difference = a - b;
console.log(difference); // Output: 7// Basic multiplication
let a = 5;
let b = 3;
let product = a * b;
console.log(product); // Output: 15// Basic division
let a = 10;
let b = 3;
let quotient = a / b;
console.log(quotient); // Output: 3.3333333333333335The modulus operator % returns the remainder of a division operation.
// Modulus example
let a = 17;
let b = 4;
let remainder = a % b;
console.log(remainder); // Output: 3Increment (++) and decrement (--) operators are used to increase or decrease the value of a variable by 1.
// Increment example
let counter = 0;
counter++; // Increment counter by 1
console.log(counter); // Output: 1
// Decrement example
let counter = 3;
counter--; // Decrement counter by 1
console.log(counter); // Output: 2Now, let's test your understanding with a quick quiz!
What is the result of `3 + 4` in JavaScript?
In real-world applications, arithmetic operations in JavaScript are essential for various tasks such as calculations, form validations, and data manipulations. To demonstrate, let's create a simple loan calculator.
// Loan calculator example
let principal = 10000; // Loan amount
let annualInterestRate = 0.05; // Annual interest rate in decimal
let years = 30; // Loan term in years
// Calculate monthly interest rate
let monthlyInterestRate = annualInterestRate / 12;
// Calculate monthly payment
let monthlyPayment = (principal * monthlyInterestRate) / (1 - Math.pow(1 + monthlyInterestRate, -years * 12));
// Output the monthly payment
console.log("The monthly payment is: $" + monthlyPayment.toFixed(2));In this example, we've created a simple loan calculator that calculates the monthly payment for a given loan amount, annual interest rate, and loan term. The Math.pow() function is used to calculate the total number of monthly payments.
That's it for our JS Arithmetic tutorial! We hope you found it helpful and engaging. Stay tuned for more JavaScript lessons on CodeYourCraft! 💡