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

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.

The above statement is incorrect.
You can try this:
console.log(typeof ‘My cat is called {catName} and she is {catAge} years old. Ive just concatenated this string using variables of different data types.’);

The result is string because JavaScript will convert all the data to a string during execution.

let word = ‘Coffee’;

let number = 3;

console.log(‘I drink ’ + number + ’ cups of ’ + word + ’ a day’);

// Prints: I drink 3 cups of coffee a day.

To be able to use typeof when concatenating variables containing two different data types:

  1. Create the first variable (e.g. foo1)
  2. Set foo1 to a string value (e.g. "bar")
  3. Create the second variable (e.g. foo2)
  4. Set foo2 to a number value (e.g. 7)
  5. Store the concentration in a new variable (e.g. foo3)
  6. use typeof on the newly created variable (i.e. foo3)

As so

let name = "John"; // type = string
let age = 25; // type = number
let combined = name + age; 

console.log(typeof name); // => string
console.log(typeof age); // => number
console.log(typeof combined); // => string