How to use `typeof` when concatenating two data types?

Same here, but when i tested it with a boolean variable and a number variable, it gives number as an answer!

var var5 = false
var var6 = 4
const var7 = var6 + var5
console.log(typeof var7) //it prints number
1 Like

JavaScript is loosely typed, which is what permits coercion. It does not make sense to add two booleans, but it does make sense to add two numbers. The role of coercion is to create a match between two types that has some semblance of common sense. false is the equivalent of 0, and true is the equivalent of 1 in a loose type match up.

false == 0
true
false === 0
false
true == 1
true
true === 1
false

Notice below how JS coerces a boolean to a string…

'42 ' + true
"42 true"

Above we concatenated two strings.

2 Likes

The initial value of the number variable was 50 (which is a number). However, you then added the string " years" to it which now makes the variable of type string

console.log(typeof number); // string

Can you please elaborate?

'use strict'

console.log(1 + true); // 2

It seems to me that even when our code has 'use strict' at the beginning, JavaScript permits coercion in arithmetic expression

1 Like

Well, it’s not the first time I’ve been mistaken. What makes me feel proud is when someone is diligent enough to track down the facts and correct the error in my ways. Will edit that post so it doesn’t mislead others. Thanks for pointing this out.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

3 Likes

Somehow I found that the typeof operator can be used in defining a variable:

//“create variables and manipulate values”

let numVariable = 10 - 7;

const concactVariable = ‘conCaTeNaTed’;

const interpVariable = ‘inTerPoLaTed’;

let str1Variable = ${concactVariable};

let str2Variable = ${interpVariable};

var booVariable = true;

let typeData = typeof numVariable + , + typeof str1Variable + , + typeof booVariable;

This is my understanding of the last question in the lesson, it’s a compilation of all the prior questions in this lesson, so we’re essentially building upon what we learned:

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

I used 3 of mine bc it made sense for what I wanted to display on the console:

console.log(

Look, here's +

numVariable + variables of different data types, + str1Variable + . + booVariable + ? + Their data types are: + typeData + , respectively);

Which gives me the following:

Look, here’s 3 variables of different data types, conCaTeNaTed. true? Their data types are: number, string, boolean, respectively

Well this was the result I aimed for, it took hours of playing around w/ all the code!! Overall this is a good lesson, the forums help a lot :+1:t3:

3 Likes

What happened to const interpVariable = ‘inTerPoLaTed’; & let str2Variable = ${interpVariable} ;

what do you mean what happened?

String interpolation in a template literal is more than just embedding variables, it’s about embedding whole expressions. Consider,

// helper function
const isAlpha = (x) => {
  y = x.charCodeAt(0)
  return y > 64 && y < 91 || y > 96 && y < 123
}
let n = 'AbCdEfGhIjKlMnOpQrStUvWxYz';

console.log(`${n}
${n.split('').map(x => isAlpha(x) ? x === x.toLowerCase() ? x.toUpperCase() : x.toLowerCase() : x).join('')}`)
AbCdEfGhIjKlMnOpQrStUvWxYz
aBcDeFgHiJkLmNoPqRsTuVwXyZ
1 Like

I mean teraace23395 spent the time to define seven variables but didn’t end up using 2 of those variables in the resulting example. I was wondering if there was some logic to including them in the definitions that eludes me as a newbie.

I’m pretty sure this is actually correct (basically the same):

let catName = 'Minnie';
let catAge = 5;

let sentence = 'My cat is called ' + catName + ' , and is ' + catAge + ' years old.';

console.log(typeof sentence);

You don’t need the interpolation in console.log

1 Like
let myStr = 'years';
let myNum = 5;

console.log(typeof myNum + myStr);

console.log(typeof (myNum + myStr));

Result:
numberyears
string

Putting myNum + myStr inside brackets make sure myNum + myStr gets concatenated into a string before typeof is used. Therefore, typeof will be used on the concatenated string of ‘5years’ and you will get the log of ‘string’. Hope that makes sense.

2 Likes

To clarify, the typeof operator has higher precedence than the + operator (concatenation) so that operation is performed first. As mentioned, by grouping we ensure that the plus operation takes place ahead of typeof.

1 Like

@mtf

Where can I find these precedence ranks? thanks :slight_smile:

Operator precedences - JavaScript - MDN

There is a table near the end of the page. Those operators higher up in the list have higher precedence.

typeof    =>  17

addition  =>  14
1 Like

Thank you so much <3 <3

1 Like
let number = 50;
let string = 'Words';
let boolean = true;

let multiType = string + number + boolean;

console.log(multiType); //logs Words50true
console.log(typeof multiType); //logs string

The way I read the question was that you just needed to use typeof to demonstrate that whenever you concatenate variables of different types they are are all converted and stored as a string variable.

Because your data is closed in backticks and in JavaScript strings are written in backticks.

Welcome to the forums!

Yes, backticks indicate that the object is a string. However, single or double quotes also indicate that objects are strings.

1 Like

Thanks!
String is Primitive data type. This means that it can’t have any properties or methods. It contains a simple data. When JavaScript execute the code it turns all the data into objects and assign some default properties and methods based on the data type.