Hugo JS

Hugo JS

1584500820

Why you should Stop using the ‘else’ keyword in JavaScript

If-else keyword built into nearly every programming language and simple conditional logic are easy for anyone to understand. If you are a programmer, you know else keyword. But if you are a good programmer, don’t use this keyword. One of the biggest mistakes I fell into when starting was overusing the else keyword when writing conditionals. Let me explain!

Why

Think about what else means, it means “if A then this, if not A then that;”. This isn’t a problem if A is binary — the problem space is only 2 cases. But if A is a combination of binary variables, or contains larger variables, your negative problem space can be unexpectedly large and difficult to understand, test and maintain. To avoid if/else if, to only use if statements, to spend the time to ensure the entry criteria for your group of if’s are mutually exclusive so that the answers don’t depend on the order of execution.

  • It promotes the main execution lane, with a few special cases.
  • It forces us to write all conditions, required to process the data, at the beginning of each function.
  • Use a switch — case statement.
  • Use polymorphism to handle complex conditional cases, making the code more clear like State Pattern.

Example

Our example is a traffic light (i.e. TrafficLight object) with 3 different states: Red, Yellow and Green, each with its own set of rules. The rules go like this:

  • Say the traffic light is Red. After a delay the Red state changes to the Green state.
  • Then, after another delay, the Green state changes to the Yellow state.
  • After a very brief delay the Yellow state is changed to Red.
  • And on and on.

Don’t use if-else keyword

const LightState = {
  GREEN: 0,
  YELLOW: 1,
  RED: 2
}

var TrafficLight = function () {

  var count = 0

  // default state = red
  var currentState = 0;

  this.change = function(state) {
    if (count++ >= 10 ) return
    currentState = state
    this.go(currentState)
  }
  this.go = function(state) {
    if (currentState == LightState.GREEN) {
      console.log("Green --> for 1 minute")
      this.change(LightState.YELLOW)
    } 
    else if (currentState == LightState.YELLOW) {
      console.log("Yellow --> for 10 seconds")
      this.change(LightState.RED)
    } else if (currentState == LightState.RED) {
      console.log("Red --> for 1 minute");
      this.change(LightState.GREEN)
    } else {
      throw Error("Invalid State")
    }
  }
  this.start = function() {
    this.change(LightState.GREEN)
  }
}

The simple way

We only remove else keywords and re-write all conditions.

this.go = function (state) {
    if (currentState == LightState.GREEN) {
      console.log("Green --> for 1 minute")
      this.change(LightState.YELLOW)
    }
    if (currentState == LightState.YELLOW) {
      console.log("Yellow --> for 10 seconds")
      this.change(LightState.RED)
    }
    if (currentState == LightState.RED) {
      console.log("Red --> for 1 minute");
      this.change(LightState.GREEN)
    }
    if (currentState != LightState.GREEN && currentState != LightState.RED && currentState != LightState.YELLOW) {
      throw Error("Invalid State")
    }
}

Or we can use a switch instead of if-else. A switch looks much cleaner when you have to combine cases. A if-else will quickly get out of control.

this.go = function (state) {
    switch (state) {
      case LightState.GREEN:
        console.log("Green --> for 1 minute")
        this.change(LightState.YELLOW)
        break
      case LightState.YELLOW:
        console.log("Yellow --> for 10 seconds")
        this.change(LightState.RED)
        break
      case LightState.RED:
        console.log("Red --> for 1 minute");
        this.change(LightState.GREEN)
        break
      default:
        throw Error("Invalid State")
    }
  }

We can use the State Pattern to remove all if-else keyword in these codes

Here, we introduce lots of if-else blocks/switch statements to guard the various conditions. The state pattern¹ fits in such a context. It allows your objects to behave differently based on the current state, and you can define state-specific behaviors. In this pattern, we start thinking in terms of possible states of our traffic light, and you segregate the code accordingly.

  • For a state-specific behavior, you have separate objects.
  • Operations defined in the traffic light are delegating the behavior to the current state’s object.
  • States are triggering state transitions themselves.

Traffic Light: Green (1 minute) → Yellow (10 seconds)→ Red (1 minute)

var TrafficLight = function () {

    var count = 0

    // default state = green
    var currentState = new Green(this);

    this.change = function (state) {
        // limits number of changes
        if (count++ >= 10) return;
        currentState = state;
        currentState.go();
    }
    this.start = function () {
        currentState.go();
    }
}

var Red = function (light) {
    this.light = light

    this.go = function () {
        console.log(("Red --> for 1 minute"))
        light.change(new Green(light));
    }
}

var Yellow = function (light) {
    this.light = light;
 
    this.go = function () {
        console.log("Yellow --> for 10 seconds")
        light.change(new Red(light));
    }
};

var Green = function (light) {
    this.light = light;
 
    this.go = function () {
        console.log("Green --> for 1 minute");
        light.change(new Yellow(light));
    }
};

They are print the same output as following

Green → for 1 minute
Yellow → for 10 seconds
Red → for 1 minute
Green → for 1 minute
Yellow → for 10 seconds
Red → for 1 minute
Green → for 1 minute
Yellow → for 10 seconds
Red → for 1 minute
Green → for 1 minute
Yellow → for 10 seconds

It is these examples of bad codes and good codes. Finally, thanks for reading and hopefully I’ve covered everything.

#javascript #javascript tips #coding #programming

What is GEEK

Buddha Community

Why you should Stop using the ‘else’ keyword in JavaScript
Lowa Alice

Lowa Alice

1624402800

JavaScript if else (tutorial). DO NOT MISS!!!

JavaScript if else made simple.

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=IsG4Xd6LlsM&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=7
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #if else #javascript if else #javascript if else (tutorial)

CSS Boss

CSS Boss

1606912089

How to create a calculator using javascript - Pure JS tutorials |Web Tutorials

In this video I will tell you How to create a calculator using javascript very easily.

#how to build a simple calculator in javascript #how to create simple calculator using javascript #javascript calculator tutorial #javascript birthday calculator #calculator using javascript and html

Brandon  Adams

Brandon Adams

1625644560

Using the This Keyword in Java | What is the This Keyword?

In this video, we use the this keyword in Java to access an object’s instance variables, invoke an object’s instance methods, and return the current object. Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is Object Oriented Programming: https://youtu.be/gJLtvKMGjhU

Constructors:
https://youtu.be/8lr1ybCvtwU

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#keyword #java #using the this keyword in java #what is the this keyword

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Hugo JS

Hugo JS

1584500820

Why you should Stop using the ‘else’ keyword in JavaScript

If-else keyword built into nearly every programming language and simple conditional logic are easy for anyone to understand. If you are a programmer, you know else keyword. But if you are a good programmer, don’t use this keyword. One of the biggest mistakes I fell into when starting was overusing the else keyword when writing conditionals. Let me explain!

Why

Think about what else means, it means “if A then this, if not A then that;”. This isn’t a problem if A is binary — the problem space is only 2 cases. But if A is a combination of binary variables, or contains larger variables, your negative problem space can be unexpectedly large and difficult to understand, test and maintain. To avoid if/else if, to only use if statements, to spend the time to ensure the entry criteria for your group of if’s are mutually exclusive so that the answers don’t depend on the order of execution.

  • It promotes the main execution lane, with a few special cases.
  • It forces us to write all conditions, required to process the data, at the beginning of each function.
  • Use a switch — case statement.
  • Use polymorphism to handle complex conditional cases, making the code more clear like State Pattern.

Example

Our example is a traffic light (i.e. TrafficLight object) with 3 different states: Red, Yellow and Green, each with its own set of rules. The rules go like this:

  • Say the traffic light is Red. After a delay the Red state changes to the Green state.
  • Then, after another delay, the Green state changes to the Yellow state.
  • After a very brief delay the Yellow state is changed to Red.
  • And on and on.

Don’t use if-else keyword

const LightState = {
  GREEN: 0,
  YELLOW: 1,
  RED: 2
}

var TrafficLight = function () {

  var count = 0

  // default state = red
  var currentState = 0;

  this.change = function(state) {
    if (count++ >= 10 ) return
    currentState = state
    this.go(currentState)
  }
  this.go = function(state) {
    if (currentState == LightState.GREEN) {
      console.log("Green --> for 1 minute")
      this.change(LightState.YELLOW)
    } 
    else if (currentState == LightState.YELLOW) {
      console.log("Yellow --> for 10 seconds")
      this.change(LightState.RED)
    } else if (currentState == LightState.RED) {
      console.log("Red --> for 1 minute");
      this.change(LightState.GREEN)
    } else {
      throw Error("Invalid State")
    }
  }
  this.start = function() {
    this.change(LightState.GREEN)
  }
}

The simple way

We only remove else keywords and re-write all conditions.

this.go = function (state) {
    if (currentState == LightState.GREEN) {
      console.log("Green --> for 1 minute")
      this.change(LightState.YELLOW)
    }
    if (currentState == LightState.YELLOW) {
      console.log("Yellow --> for 10 seconds")
      this.change(LightState.RED)
    }
    if (currentState == LightState.RED) {
      console.log("Red --> for 1 minute");
      this.change(LightState.GREEN)
    }
    if (currentState != LightState.GREEN && currentState != LightState.RED && currentState != LightState.YELLOW) {
      throw Error("Invalid State")
    }
}

Or we can use a switch instead of if-else. A switch looks much cleaner when you have to combine cases. A if-else will quickly get out of control.

this.go = function (state) {
    switch (state) {
      case LightState.GREEN:
        console.log("Green --> for 1 minute")
        this.change(LightState.YELLOW)
        break
      case LightState.YELLOW:
        console.log("Yellow --> for 10 seconds")
        this.change(LightState.RED)
        break
      case LightState.RED:
        console.log("Red --> for 1 minute");
        this.change(LightState.GREEN)
        break
      default:
        throw Error("Invalid State")
    }
  }

We can use the State Pattern to remove all if-else keyword in these codes

Here, we introduce lots of if-else blocks/switch statements to guard the various conditions. The state pattern¹ fits in such a context. It allows your objects to behave differently based on the current state, and you can define state-specific behaviors. In this pattern, we start thinking in terms of possible states of our traffic light, and you segregate the code accordingly.

  • For a state-specific behavior, you have separate objects.
  • Operations defined in the traffic light are delegating the behavior to the current state’s object.
  • States are triggering state transitions themselves.

Traffic Light: Green (1 minute) → Yellow (10 seconds)→ Red (1 minute)

var TrafficLight = function () {

    var count = 0

    // default state = green
    var currentState = new Green(this);

    this.change = function (state) {
        // limits number of changes
        if (count++ >= 10) return;
        currentState = state;
        currentState.go();
    }
    this.start = function () {
        currentState.go();
    }
}

var Red = function (light) {
    this.light = light

    this.go = function () {
        console.log(("Red --> for 1 minute"))
        light.change(new Green(light));
    }
}

var Yellow = function (light) {
    this.light = light;
 
    this.go = function () {
        console.log("Yellow --> for 10 seconds")
        light.change(new Red(light));
    }
};

var Green = function (light) {
    this.light = light;
 
    this.go = function () {
        console.log("Green --> for 1 minute");
        light.change(new Yellow(light));
    }
};

They are print the same output as following

Green → for 1 minute
Yellow → for 10 seconds
Red → for 1 minute
Green → for 1 minute
Yellow → for 10 seconds
Red → for 1 minute
Green → for 1 minute
Yellow → for 10 seconds
Red → for 1 minute
Green → for 1 minute
Yellow → for 10 seconds

It is these examples of bad codes and good codes. Finally, thanks for reading and hopefully I’ve covered everything.

#javascript #javascript tips #coding #programming