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.

1 Like