w3resource

JavaScript: Check whether given value types are same or not

JavaScript validation: Exercise-10 with Solution

Write a JavaScript function to check whether the given values are the same or not.

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to check whether given value types are same or not.</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function is_sameType(value1, value2) {
        if(is_nan(value1) || is_nan(value2)) {
         return is_nan(value1) === is_nan(value2);
        }
        return toString.call(value1) === toString.call(value2);
    }

function is_nan(val)
        {
        return val !== val;
       }

console.log(is_sameType('12', 100));
console.log(is_sameType('12', '100'));
console.log(is_sameType(12, 100));

Sample Output:

false
true
true

Flowchart:

Flowchart: JavaScript - Check whether given value types are same or not.

Live Demo:

See the Pen javascript-validation-exercise-10 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to validate whether a given value type is char or not
Next: JavaScript Searching and Sorting Algorithm Exercises

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.