Billy Chandler

Billy Chandler

1554267134

How to keep your JavaScript code simple and easy to read?

#javascript

What is GEEK

Buddha Community

There are many ways to solve the same problem, but some solutions are complex, and some are even ridiculous. In this article, I want to talk about bad and good solutions for the same problems.

Let’s start with the problem that requires us to remove duplicate values from an array.

Complex - Removing duplicates using forEach

First, we create a new empty array, then we use the forEach() method to execute a provided function once for each array element. Eventually, we check if the value doesn’t exist in the new array, and if not, we add it.

function removeDuplicates(arr) {  
   const uniqueVals = [];   
   arr.forEach((value,index) => {     
       if(uniqueVals.indexOf(value) === -1) {
           uniqueVals.push(value);
       }  
   });
  return uniqueVals;
}

Simple - Removing duplicates using filter

The filter method creates a new array with all elements that pass the test implemented by the provided function. Basically, we iterate over the array and, for each element, check if the first position of this element in the array is equal to the current position. Of course, these two positions are different for duplicate elements.

function removeDuplicates(arr) {
  return arr.filter((item, pos) => arr.indexOf(item) === pos)
}

Simple - Removing duplicates using Set

ES6 provides the Set object, which makes things a whole lot easier. Set allows only unique values, so when you pass in an array, it removes any duplicate values.

However, if you need an array with unique elements, why not use Set right from the beginning?

function removeDuplicates(arr) {
   return [...new Set(arr)];
}

Let’s move on and solve the second problem which requires us to write a function that takes an array of distinct non-negative integers, make them consecutive, and return the count of missing numbers.

For const arr = [4, 2, 6, 8], the output should be

countMissingNumbers(arr) = 3

As you can see 3, 5and 7 are missing

Complex - Solving by using sort and for loop

To obtain the smallest and largest numbers we need to sort them in ascending order, and for that purpose, we use sort method. Then we loop from the smallest number to the largest number. Each time, we check whether a sequential number exists in the array or not, and if not we increase the counter.

function countMissingNumbers(arr) {
    arr.sort((a,b) => a-b);    
    let count = 0;    
    const min = arr[0];    
    const max = arr[arr.length-1];
    for (i = min; i<max; i++) {
      if (arr.indexOf(i) === -1) {
          count++;         
      }      
    }        
    return count;
}

Simple - Solving by using Math.max and Math.min

This solution has a simple explanation: the [**Math.max()**]([https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max)") function returns the largest number in the array and the [**Math.min()**]([https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min) "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min)") returns the smallest number in the array.

First, we find how many numbers would be in the array if there weren’t missing numbers. For that, we use the following formula maxNumber - minNuber + 1, and the difference between the result of this and the array length will give us the count of missing numbers.

function countMissingNumbers(arr) {
      return Math.max(...arr) - Math.min(...arr) + 1 - arr.length;
}

The last problem I want to bring as an example is to check whether the string is a palindrome or not.

*A palindrome is a string that reads the same left-to-right and right-to-left.

Complex - Checking By using for loop

In this option, we loop over the string starting from the first character until half of the string length. The index of the last character in a string is string.length-1, the second to last character is string.length-2, and so on. So here we check whether the character at the specified index from the start is equal to the character at the specified index at the end. If they are not equal, we return false.

function checkPalindrome(inputString) { 
   let length = inputString.length
   for (let i =0; i<length / 2; i++) {
        if (inputString[i] !== inputString[length - 1 -i]) {
             return false        
        }
   }
  return true
}

Simple - Checking by using reverse and join

I think that this simple solution doesn’t require an explanation, as it speaks for itself. We simply create an array from the string using the spread operator, then reverse the array, then turn it into a string again using the join method and compare it with the original string.

function checkPalindrome(string) {
   return string === [...string].reverse().join('');
}

Keep it simple!

Why complicate when there are simpler ways? I hope you found this article interesting. Have a good day and try not to complicate simple things in life as well :)

Thanks for your claps 👏

Learn More

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript: Understanding the Weird Parts

An introduction to functional programming in JavaScript

Top 12 Javascript Tricks for Beginners

Introduction to JavaScript Scope

Top 10 JavaScript array methods you should know

4 Uses of JavaScript’s Array.map() You Should Know

Vuejs 2 Authentication Tutorial

*Originally published by Arthur Arakelyan at *https://medium.freecodecamp.org

Is easy, just do a “One” and “Simple” action inside every function, remember if you divide the task in an easy steps the code makes more easy to read and maintain.

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

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Giles  Goodwin

Giles Goodwin

1603857900

4 Ways You Can Get Rid of Dirty Side Effects for Cleaner Code in JavaScript

According to an analysis, a developer creates 70 bugs per 1000 lines of code on average. As a result, he spends 75% of his time on debugging. So sad!

Bugs are born in many ways. Creating side effects is one of them.

Some people say side effects are evil, some say they’re not.

I’m in the first group. Side effects should be considered evil. And we should aim for side effects free code.

Here are 4ways you can use to achieve the goal.

1. use strict;

Just add use strict; to the beginning of your files. This special string will turn your code validation on and prevent you from using variables without declaring them first.

#functional-programming #javascript-tips #clean-code #coding #javascript-development #javascript

JavaScript Snake Game Tutorial - Develop a Simple Snake Game

Work on real-time JavaScript Snake game project and become a pro

Snake game is an interesting JavaScript project for beginners. Snake game is a single-player game, which we’ve been playing for a very long time. The game mainly consists of two components – snake and fruit. And we just need to take our snake to the food so that it can eat and grow faster and as the number of fruits eaten increases, the length of snake increases which makes the game more interesting. While moving if the snake eats its own body, then the snake dies and the game ends. Now let’s see how we can create this.

JavaScript Project Prerequisites

To implement the snake game in JavaScript you should have basic knowledge of:

1. Basic concepts of JavaScript

2. HTML

3. CSS

Download Project Code

Before proceeding ahead please download source code of Snake Game: Snake Game in JavaScript

Steps to Build the Project – JavaScript Snake game

1. Create Html file

HTML builds the basic structure. This file contains some basic HTML tags like div, h1, title, etc. also we’ve used bootstrap (CDN is already included).

index.html:

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataFlair Snake game</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
    <div class="container">
        <div class ="Jumbotron">
        <h1>DataFlair Snake game using vanilla JavaScript</h1>

            <h2 class="btn btn-info"> 
                Score:   0 
            </h2>

            <div class="containerCanvas">
                <canvas id="canvas" width="500" height="500" class="canvasmain"> </canvas>
            </div>
        </div>
    </div>
    <script src="static/fruit.js"></script>
    <script src="static/snake.js"></script>
    <script src="static/draw.js"></script>
</body>
</html>

We have used simple HTML tags except tag. This new tag was introduced in HTML5, which is used to draw graphics, via JavaScript. It is nothing without JavaScript so we will use it in our JavaScript file to actually draw the board and the objects required. We’ll see its implementation in JS files.

#javascript tutorial #javascript project #javascript snake game #simple snake game #javascript

Santosh J

1622036598

JavaScript compound assignment operators

JavaScript is unarguablly one of the most common things you’ll learn when you start programming for the web. Here’s a small post on JavaScript compound assignment operators and how we use them.

The compound assignment operators consist of a binary operator and the simple assignment operator.

The binary operators, work with two operands. For example a+b where + is the operator and the a, b are operands. Simple assignment operator is used to assign values to a variable(s).

It’s quite common to modify values stored in variables. To make this process a little quicker, we use compound assignment operators.

They are:

  • +=
  • -+
  • *=
  • /=

You can also check my video tutorial compound assignment operators.

Let’s consider an example. Suppose price = 5 and we want to add ten more to it.

var price = 5;
price = price + 10;

We added ten to price. Look at the repetitive price variable. We could easily use a compound += to reduce this. We do this instead.

price += 5;

Awesome. Isn’t it? What’s the value of price now? Practice and comment below. If you don’t know how to practice check these lessons.

Lets bring down the price by 5 again and display it.
We use console.log command to display what is stored in the variable. It is very help for debugging.
Debugging let’s you find errors or bugs in your code. More on this later.

price -= 5;
console.log(price);

Lets multiply price and show it.

price *=5;
console.log(price);

and finally we will divide it.

price /=5;
console.log(price);

If you have any doubts, comment below.

#javascript #javascript compound assignment operators #javascript binary operators #javascript simple assignment operator #doers javascript