DEV Community

JEGADESHWARAN B
JEGADESHWARAN B

Posted on

Operators in JavaScript

  1. What are Operators in JavaScript?

Operators are symbols used to perform operations on values (called operands).
Example:

let result = 10 + 5;
Enter fullscreen mode Exit fullscreen mode

Here:

  • 10 and 5 → operands
  • + → operator

  1. Types of Operators (Basic Idea)

Some common operators:

  • Arithmetic → +, -, *, /
  • Assignment → =, +=
  • Comparison → ==, ===
  • Logical → &&, ||

Now we focus on Arithmetic operators (+ and -)


  1. Addition (+) Operator

How it works:

  1. If both values are numbers → addition
  2. If any one is string → convert to string
  3. Then join (concatenate)

Examples

Number + Number

javascript
console.log(10 + 5); // 15

String + String

console.log("Hello" + " JS"); // "Hello JS"
Enter fullscreen mode Exit fullscreen mode

String + Number

console.log("10" + 5); // "105"
Enter fullscreen mode Exit fullscreen mode

Number + String

console.log(10 + "5"); // "105"
Enter fullscreen mode Exit fullscreen mode

  1. Subtraction (-) Operator

How it works:

  1. Convert both values to numbers
  2. Perform subtraction
  3. If not possible → NaN

Examples

Number - Number

console.log(10 - 5); // 5
Enter fullscreen mode Exit fullscreen mode

⚠️ String - Number

console.log("10" - 5); // 5
Enter fullscreen mode Exit fullscreen mode

Number - String

console.log(10 - "5"); // 5
Enter fullscreen mode Exit fullscreen mode

String - String

console.log("10" - "5"); // 5
Enter fullscreen mode Exit fullscreen mode

Invalid String

console.log("Hello" - 5); // NaN
Enter fullscreen mode Exit fullscreen mode

  1. Final Difference
Operator Behavior
+ Can add OR join strings
- Always numeric subtraction

  1. Easy Memory Trick
console.log("5" + 5); // "55"
console.log("5" - 5); // 0
Enter fullscreen mode Exit fullscreen mode

+ → string joins
- → number math only

Top comments (0)