- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add a number and a string in JavaScript?
In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place.
In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a number(10). But in case of variable 'b' a string and a number ('5', 5) are added therefore, since a string is involved, we get the result as '55', which is a string. since strings are involved, Variables 'c' and 'd' also return a string as shown in the output.
Example
<html> <body> <script type="text/javascript"> var a = 5 + 5; var b = "5" + 5; var c = 5 + 5 + "5" + 5 var d = "Hello" + 5; document.write(a + "<br>" + b + "<br>" + c + "</br>" + d); document.write("</br>"); document.write(typeof(a)); document.write("</br>"); document.write(typeof(b)); document.write("</br>"); document.write(typeof(c)); document.write("</br>"); document.write(typeof(d)); </script> </body> </html>
Output
10 55 1055 Hello5 number string string string
Advertisements