To check if a variable is a string in JavaScript, you can use the typeof
operator. This operator returns the data type of the operand, which you can then compare to the string "string"
.
Here is an example:
function isString(val) {
return typeof val === "string";
}
Code language: JavaScript (javascript)
In this example, the isString()
function takes in a single argument val
and uses the typeof
operator to check if its data type is a string. If it is, the function returns true
, otherwise it returns false
.
You can use this function to check if a variable is a string like this:
let str = "hello";
if (isString(str)) {
// str is a string
console.log(str);
}
Code language: JavaScript (javascript)
In this example, the isString()
function is called with the str
variable as an argument. Since str
is a string, the function returns true
and the code inside the if
block is executed.
Leave a Reply