In JavaScript, you can add both strings and numbers, but the results differ based on the types involved. This guide will explain how adding strings and numbers works in JavaScript, along with examples.
Adding Numbers
When you add two numbers in JavaScript using the + operator, JavaScript performs addition:
let num2 = 3;
let sum = num1 + num2;
console.log(sum); // Outputs: 8
Here, num1 and num2 are both numeric values, so adding them gives the expected sum of 8.
Adding Strings
When you add two strings or a string and another value (like a number), JavaScript concatenates them into a new string:
let str2 = ' World';
let greeting = str1 + str2;
console.log(greeting); // Outputs: Hello World
In this example, str1 and str2 are concatenated using the + operator to form the string 'Hello World'.
Mixing Numbers and Strings
JavaScript allows you to mix numbers and strings in an addition operation. When you do this, JavaScript converts the numbers to strings and concatenates them with the other string(s):
let string = ' apples';
let result = number + string;
console.log(result); // Outputs: '5 apples'
Here, the number 5 is converted to the string '5', and then it is concatenated with the string ' apples', resulting in '5 apples'.
Automatic Type Conversion (Type Coercion)
JavaScript is a weakly typed language, which means it can automatically convert one data type to another as needed. This is known as type coercion. When you use the + operator with different types, JavaScript converts one of the operands to match the other:
Number to String Conversion
let bananas = ' bananas';
let result = apples + bananas;
console.log(result); // Outputs: '5 bananas'
In this example, the number 5 is converted to the string '5' and then concatenated with the string ' bananas', resulting in '5 bananas'.
String to Number Conversion
let sum = 5 + num;
console.log(sum); // Outputs: 15 (the string '10' is converted to the number 10)
In this example, the string '10' is converted to the number 10, and then added to 5, resulting in 15.
Examples of Adding Strings and Numbers
Example 1: Adding Numbers
let num2 = 5;
let sum = num1 + num2;
console.log(sum); // Outputs: 15
Example 2: Adding Strings
let str2 = ' World';
let greeting = str1 + str2;
console.log(greeting); // Outputs: Hello World
Example 3: Mixing Numbers and Strings
let oranges = ' oranges';
let result = 'I have ' + apples + oranges;
console.log(result); // Outputs: I have 5 oranges
In this example, the number 5 is converted to the string '5' and concatenated with 'I have ' and ' oranges'.
Practice Excercise Practice now