Introduction
In this lab, we will explore the concept of primitive values in JavaScript. We will learn how to differentiate between primitive and non-primitive values using the isPrimitive() function, which compares the passed value with an object created from it. Through a series of exercises, we will gain a deeper understanding of this fundamental concept in JavaScript.
Checking for Primitive Values
To practice coding, open the Terminal or SSH and type node. Once you've done that, you can check whether a value is primitive or not by following these steps:
- Create an object from the value you want to check using
Object(val). - Compare the created object with the original value using the strict inequality operator
!==. - If the two values are not equal, the original value is primitive.
Here's the code for the isPrimitive function:
const isPrimitive = (val) => Object(val) !== val;
You can test this function with the following values:
isPrimitive(null); // true
isPrimitive(undefined); // true
isPrimitive(50); // true
isPrimitive("Hello!"); // true
isPrimitive(false); // true
isPrimitive(Symbol()); // true
isPrimitive([]); // false
isPrimitive({}); // false
If the value you want to check is primitive, the function will return true. Otherwise, it will return false.
Summary
Congratulations! You have completed the Number Is Primitive lab. You can practice more labs in LabEx to improve your skills.