Chapter variables lesson 10/10

Here’s the lesson: https://www.codecademy.com/courses/introduction-to-javascript/lessons/variables/exercises/review-variables

The last “challenge” says the following:

  • Use typeof to find the data type of the resulting value when you concatenate variables containing two different data types.

My code is the following, but focus on the last line where I concatenate the variables:

let GreetingsSpain = 'Hola';
let GreetingsHawaii = 'Aloha';
console.log(GreetingsSpain);
GreetingsSpain = 1;
console.log(GreetingsSpain);
console.log(GreetingsSpain + ' ' + GreetingsHawaii);
const colorOfPen = 'blue';
const numberOfPen = 50;
console.log(`My pen is ${colorOfPen}. Not only that but I also have ${numberOfPen}.`);

console.log(typeof GreetingsSpain)
console.log(typeof(GreetingsSpain + ' ' + GreetingsHawaii))

Basically I don’t understand why when doing console.log it shows string and not number. Why does it shows that data type and not the other? Is there a preference for displaying between different data types? Thanks in advance.

What you are doing is called string concatenation. Even though one of the items being concatenated is a number, it needs to be in string format to store both variables as one. Think about it this way too, if you say this variable is a number, we all agree the variable would not contain a word. However if you said this variable is a string, then the variable could be variable1 = '1 banana', we’d all agree this is still a string. Therefore it always becomes the most general type, in this case a string.

Try concatenating a boolean and a number, and see what happens there, as well as a boolean and a string.

2 Likes

For future viewers this is the solution to the mini-challenge above: image

Thank you for the reply, I’ve done what you’ve told me. Now I do have a question, is there a possiblity where I can display a boolean or a number in a string concatenation?

For string concatenation specifically no, as in order for it to be string concatenation, a string needs to be involved, therefore it will always be a string. If you sum two booleans or two numbers or any mix of these, you will always get a number, as it is doing a regular sum, as opposed to string concatenation.

1 Like