简体   繁体   中英

codecademy javascript explain “+”

I'm currently learning JS on codecademy.com and one of the things that struck me is this:

"Hi, I am" + " " + name

This is a simple return for a function that prints your name when you put it in ie

printName(name)

and it returns:

Hi, I am {name}

so, why don't they just simplify it to be

"Hi, I am " + name

Is there a reason for the "+" "?

sorry for the weird way this is typed out :/

Nope. No reason that couldn't just as easily been "Hi, I am " + name; . They produce equivalent results.

I'm guessing they wrote it that way so you get in the habit of adding spaces when concatenating strings (as variables usually don't have leading/trailing spaces included).

There is no reason. Perhaps they had originally intended you to input two variables for first and last name with a space between them, but then simplified the demo later and forgot to just move the space into the first string?

That's my guess, but no there is no reason not to do what you said. In fact, if you really want to get pedantic, their example is inefficient because string concatenation requires some overhead so their version would be slightly less performant. Though you wouldn't notice until you did the same operation over and over in a loop and then compared the two.

startTimer('with concat');
for (var count=0; count<99999; count++) {
  var someString = "Hi, I am" + " " + name;
}
stopTimer('with concat');

startTimer('without concat');
for (var count=0; count<99999; count++) {
  var someString = "Hi, I am " + name;
}
stopTimer('without concat');

Demo: http://codepen.io/Chevex/pen/gpWNeq?editors=001

The difference is negligible, but you can see there is one :D

I don't know what their reasoning is, however in EcmaScript + is overloaded for both addition and string concatonation.

Consider the following:

console.log("Hi: " + 12 + 13);
> "Hi: 1213"
console.log("Hi: " + "" + 12 + "" + 13);
> "Hi: 1213"
console.log("Hi: " + (12 + 13));
> "Hi: 25"

I don't know what their reasons were for the extra quotes, but prepending ""+ to a value will automatically perform type coercion, which may or may not be desirable.

The "+" in the code is used to add extra objects to make a string.

Yes, codecademy.com could've actually simplified "Hi, I am" + " " + name to "Hi, I am " + name but the website is only used to teach you the basics of a code - in this case JavaScript. You are able to simplify the code down to "Hi, I am " + name but that is not what the task wants (you could do this in your own codes outside of the website).

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