Number Is Primitive

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28438{{"`Number Is Primitive`"}} javascript/data_types -.-> lab-28438{{"`Number Is Primitive`"}} javascript/arith_ops -.-> lab-28438{{"`Number Is Primitive`"}} javascript/comp_ops -.-> lab-28438{{"`Number Is Primitive`"}} end

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:

  1. Create an object from the value you want to check using Object(val).
  2. Compare the created object with the original value using the strict inequality operator !==.
  3. 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.

Other JavaScript Tutorials you may like