In JavaScript, the + operator serves two purposes: addition and string concatenation. Whether it acts as addition or concatenation depends on the operands involved. Here are the general rules:
String Concatenation:
If either operand is a string, JavaScript will treat the + operator as string concatenation. This means it will convert the other operand to a string (if it's not already a string) and then concatenate the two strings.
Example:
let result = "Hello" + " " + "World"; // "Hello World"
let result2 = "Age: " + 25; // "Age: 25"
Numeric Addition:
If both operands are numbers (or can be coerced to numbers), JavaScript will treat the + operator as numeric addition.
Example:
let result = 5 + 10; // 15
let result2 = "5" + 10; // "510" (string concatenation, since one operand is a string)
Type Coercion:
If one operand is a string and the other is a number, the number is automatically converted to a string, and the + operator performs string concatenation instead of numeric addition.
Example:
let result = 5 + " apples"; // "5 apples"
Summary:
- + is used for addition when both operands are numbers (or can be coerced to numbers).
- + is used for concatenation when one or both operands are strings.
No comments:
Post a Comment