Number Is Power of Two

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore a JavaScript function that determines whether a given number is a power of 2. By using the bitwise binary AND operator and checking that the number is not falsy, we can accurately determine if a number is a power of 2. This lab will provide an opportunity to practice using bitwise operators and logical operators 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-28436{{"`Number Is Power of Two`"}} javascript/data_types -.-> lab-28436{{"`Number Is Power of Two`"}} javascript/arith_ops -.-> lab-28436{{"`Number Is Power of Two`"}} javascript/comp_ops -.-> lab-28436{{"`Number Is Power of Two`"}} end

Check If a Number Is a Power of Two

To check if a number is a power of two, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the bitwise binary AND operator (&) to determine if the number (n) is a power of 2.
  3. Additionally, check that n is not falsy.
  4. The following code functionally checks if n is a power of two:
const isPowerOfTwo = (n) => !!n && (n & (n - 1)) == 0;

Here are some examples of how to use the isPowerOfTwo function:

isPowerOfTwo(0); // false
isPowerOfTwo(1); // true
isPowerOfTwo(8); // true

Summary

Congratulations! You have completed the Number Is Power of Two lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like