JavaScript: Variables and concatenation
Earlier, we already joined strings directly using concatenation. Now we'll do the same thing, but with variables. The good news: the syntax stays the same. The values of the variables are simply substituted in.
Joining two strings directly
const what = 'Kings' + 'road';
console.log(what); // => KingsroadEverything is simple here: two strings are joined into one. This is how concatenation works: the + operator adds strings together, creating a new string.
Joining a string and a variable
If the variable first holds the string 'Kings', we can safely join it with another string:
const first = 'Kings';
const what = first + 'road';
console.log(what); // => KingsroadJavaScript substitutes the value of the variable, performs the operation, and creates the resulting string.
Joining two variables
In the same way, you can combine the values of two variables, if both contain strings:
const first = 'Kings';
const last = 'road';
const what = first + last;
console.log(what); // => KingsroadYou can also add spaces:
const full = first + ' ' + last;
console.log(full); // => Kings roadfirst = 'Kings'
last = 'road'
first + ' ' + last
└─┬──┘ └─┬┘
'Kings' + ' ' + 'road'
└────────┬─────────┘
'Kings road'What if the variable contains a number?
In JavaScript, the + operator behaves in a special way when there's a string on one side and a number on the other. In this case, the number is automatically converted to a string, and concatenation happens:
const age = 42;
console.log('Age: ' + age); // => Age: 42The same applies to variables holding the results of computations:
const price = 50 * 1.25 * 6.91; // => 431.875
console.log('Price in yuans: ' + price); // => Price in yuans: 431.875There's also an explicit way to convert a number to a string using String() — we'll cover it in the lesson about type coercion.
Instructions
Write a program that builds and prints a greeting letter. Use only two console.log() calls.
Define the variables:
firstName='Anna'greeting='Hello'intro='Thank you for your order.'info='Expected delivery date — 3 business days.'
Expected output:
Hello, Anna!
Thank you for your order.
Expected delivery date — 3 business days.Tips
Think about which string and in what order you need to join the variables with to get this two-line body of the letter.
Remember that you can create a string that contains only the escape sequence
\n.
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.
It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.
In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.
It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.
By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.
Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в обратной связи нашего сообщества
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('hello world', async () => {
const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe(
'Hello, Anna!\nThank you for your order.\nExpected delivery date — 3 business days.',
);
});Teacher's solution will be available in:
20:00
