简体   繁体   中英

adding variables and console.log the result

I'm taking a basic javascript tutorial and cannot figure this out as I've been searching and searching.

Code is as follows:

const a = 1
const b = 1

console.log("a" + "b");

This should return 2, but something is wrong. Fix the code.

I've tried many different options including removing the quotes and changing const to var or let with no luck. Can anyone help me?

You are printing 'a' and 'b' as strings by using the double quotes, which is why your code doesn't work as intended. You also did not add a semicolon between your variable declarations. You should do console.log(a + b) , without the quotes:

const a = 1; 
const b = 1;

console.log(a + b); // 2

Please refer to this article on medium, which explains the differences between let , const and var .

you don't add the double quotes. That will print a string.

You want to print a sum of numbers so a+b would suffice.

console.log(a+b);

In JavaScript you cannot add two variables with quotes. Your console.log("a" + "b") would print 'ab' as it's treated as a string. Also, you need to add a semicolon (;) after you declare a const.

 const a=1, b=1; //add a ';' console.log(a+b); //will output 2 as it has no quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM