JavaScript Operators and Type Conversion (Day 2)
What are JavaScript Operators?
In JavaScript, Operators are special symbols used to perform operations on values (called operands). For example, the +
symbol is used to add two numbers. Let's explore them in detail.
1. Arithmetic Operators
These operators are used for basic mathematical calculations.
let a = 10;
let b = 4;
console.log("a + b =", a + b); // Addition: 14
console.log("a - b =", a - b); // Subtraction: 6
console.log("a * b =", a * b); // Multiplication: 40
console.log("a / b =", a / b); // Division: 2.5
console.log("a % b =", a % b); // Modulus (Remainder): 2
2. Comparison Operators
These operators compare two values and return a boolean result: true
or false
.
let x = 5;
let y = "5";
// == (Loose Equality): Checks only the value, not the type.
console.log("x == y:", x == y); // true
// === (Strict Equality): Checks both value and type. (Recommended)
console.log("x === y:", x === y); // false (because x is a number and y is a string)
// != (Not Equal)
console.log("x != y:", x != y); // false
// !== (Strict Not Equal)
console.log("x !== y:", x !== y); // true
Important: Always use strict equality ===
to avoid unexpected bugs from type coercion.
What is Type Conversion?
Type Conversion means changing the data type of a value to another. This can happen in two ways: Implicit (automatically) and Explicit (manually).
Implicit Conversion (Coercion)
This happens when JavaScript automatically converts a data type.
let result;
// When adding a string and a number, the number becomes a string.
result = "Hello " + 123;
console.log(result); // "Hello 123"
// When subtracting a string and a number, the string becomes a number.
result = "10" - 5;
console.log(result); // 5
Explicit Conversion
This is when we manually convert a data type.
let value = "99";
// String to Number
let numValue = Number(value);
console.log(typeof numValue); // "number"
// Number to String
let strValue = String(numValue);
console.log(typeof strValue); // "string"
// To Boolean
let boolValue = Boolean("hello"); // Non-empty string is true
console.log(boolValue); // true
Today's Project: Simple Age Checker
Let's use today's concepts to build a small program that checks if a user is eligible to vote.
// prompt() takes user input and returns it as a string.
let ageString = prompt("What is your age?");
// Explicitly convert the string to a number.
let age = Number(ageString);
// Check if the conversion was successful and age is a valid number.
if (!isNaN(age)) {
// Use a comparison operator to check eligibility.
if (age >= 18) {
alert("Great! You are eligible to vote.");
} else {
alert("Sorry, you are not yet eligible to vote.");
}
} else {
alert("Invalid input. Please enter a valid age.");
}
Comments
Post a Comment