Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow do you Make an If Statement in JavaScript that Checks if...

How do you Make an If Statement in JavaScript that Checks if a Variable is Equal to a Certain Word ?

In this article, we will discuss How You Make An If Statement In JavaScript That Checks If A Variable is Equal To A Certain Word. In JavaScript, an if statement is a basic control structure that allows you to conditionally execute code based on specified conditions. A common use case is to check if the value of the variable is equal to a specific word or string.

There are several approaches that can be used to Check If A Variable is Equal To A Certain Word, which are listed below:

  • Using the Equality Operator (===)
  • Using the includes() Method

We will explore all the above approaches along with their basic implementation with the help of examples.

Approach 1: Using the Equality Operator (===)

Using the strict equality operator (===), it checks if the variable is exactly equal to the specified word, including the type.

Syntax:

if(variable === 'word') {
// Code to be executed
//if the variable is equal to 'word'.
}

Example: In this example, we are using Strict Equality Operator (===) to check our variable is equal to specified word.

Javascript




let data = 'neveropen';
  
if (data === 'neveropen') {
    console.log('The variable is equal to "neveropen"');
} else {
    console.log('The variable is Not equal to "neveropen"');
};


Output

The variable is equal to "neveropen"

Approach 2: Using includes() method

In this approach, the includes() method checks if the string word contains the substring “gfg”.

Syntax:

word.includes(targetWord)

Example: In this example, we are using the above-explained approach.

Javascript




const word = "neveropen";
const targetWord = "gfg";
  
if (word.includes(targetWord)) {
    console.log("The variable contains the word 'gfg'.");
} else {
    console.log("The variable does not contain the word 'gfg'.");
};


Output

The variable does not contain the word 'gfg'.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments