The JavaScript Code Snippet for Common Problems


Javascript Code Snippet | Long Javascript Code

Each programming language has its flaws and quirks. JavaScript language and even the Javascript code snippet used is not an exception. The script language has behaved strangely in recent years, but it is one of the most widely used languages this day. In most part is because it is the primary interactive language of internet browsers.

There are times, as programmers and coders, where we have repetitive, simple-task problems that we need simple code snippets. In this blog, I’m going to present some common problems that can be easily solved using ES6 scripting as part of some JavaScript code snippets.

Javascript Code Snippet Tip: Use ‘let’ Instead of ‘var’

let is like var but let has scope. let is only accessible in the block scope level it is declared and assigned a value. var is accessible at any level regarding the block scope it is defined. In the following example, variable ‘num1’ is defined inside an If statement and so it’s not accessible outside the function.

if (true) {
  let num1 = 40;
}

let num2 = 20;

console.log(num2, num1);
console.log(num1);

Output:
20
undefined
let a = 25;
let b = 50;

if (true) {
  let a = 100;
  var c = 5;
  console.log(a/c);
  console.log(b/c);
}

console.log(c);
console.log(a);

Output:
20
10
5
25

Use ‘const’ When a Variable Value Does Not Change

Javascript Code Snippet | Man Looking At Javascipt Codeconst assign a constant value to a variable that cannot be changed. Whenever a const variable is defined, JavaScript references the address of the value to the variable.

The Javascript Code Snippet’s Arrow Function, a New Syntax for Functions

The Javascript code snippets’ Functions in ES6 have changed to a simpler expression, ‘() => {}’.

// Old Syntax
function myHello() {
  console.log("Hello World..!");
}

// New Syntax
var myHello = () => {
  console.log("Hello World..!");
}

The new syntax may be a little confusing initially. There are two parts of the syntax.

var myHello = ()

The first part of the Javascript Code Snippet declares a variable and assigning the function () to it. It just says the variable is a function.

=> { //do something }

Javascript Code Snippet | Javascipt Code on Black BackgroundThe second part declares the body part of the function. The arrow part with the curly braces defines the body part.

 

 

 

Other examples but with parameters.

let withParameters = (a, b) => {
  console.log(a+b);
}

withParameters(10, 20);

Output:
30
let sumOfNum = (a, b = 10) => {
  return a + b;
}

console.log(sumOfNum(20);
console.log(sumOfNum(20,30);

Output:
30
50
Each programming language has its flaws and quirks. JavaScript language and even the Javascript code snippet used is not an exception. Click To Tweet

New’ for…of…’ Loop

for…of is very similar to for…in with slight modification. for…of iterates through a list of elements like an Array and returns the elements (not their index) one by one. Note that the variable ‘num’ outputs each element in the array, not the index.

let numbers = [5,6,7,8];

for (let num of numbers) {
  console.log(value);
}

Output:
5
6
7
8
let str = ‘Arturo’;

for (let char of str) {
  console.log(char);
}

Output:
A
r
t
u
r
o

Destructing Variable Assignment

Assigning variables from an array one-by-one is time-consuming and silly. Just use destructor assignment to accomplish this quicker and easier:

let profile = ['John', 32, 'engineer'];

let [name, age, job] = profile;

console.log(name);

Output:
John

Find a Specific Object in an Array of Objects

One of the most common tasks you would need to accomplish in JavaScript is iterating through an array of objects to find a specific one. The find method is a simple solution here. You simply plug in the selection criteria using an anonymous function as the argument, and you’re set:

let staff = [
  { id: 0, name: 'Nina' },
  { id: 1, name: 'Kevin' },
  { id: 2, name: 'John' }
]

let employee = staff.find(emp => emp.name === 'John');

console.log(client);

Output:
{ id: 2, name: 'John' }

Looping Over an Object Keys and Values

Javascript Code Snippet | Javascipt Code on White BackgroundOur data structure might be a complex object that contains various key/value pairs. Iterating each pair could be a little odd, but it’s straightforward once we get to use the function of Object.

After the Object’s keys are grabbed, we can loop through the keys and values at the same time. In the solution that follows, we access each pair using the key and value variables during the loop.

 

let myObject = { Peter: 15, John: 20, Anne: 35 };

Object.keys(myObject).forEach((key, value) => {
  //...do something
  console.log(key, value);
});

Output:
Peter 15
John 20
Anne 35

Filter an Array of Objects Based on a Condition

Sometimes we have a large array of data that we want to filter out items based on a specific condition. We can a filter function to accomplish this. The following solution has an array of file paths. Some files are in the directory ‘data1’ while others in the directory ‘data2’. Let’s think we want to filter for only a specific directory:

let location = [
  "files/data1/file",
  "files/data1/file2",
  "files/data2/file",
  "files/data2/file2"
];

let filter = location.filter(path => path.includes('data2'));

console.log(filter);

Output:
[ 'files/dir2/file', 'files/dir2/file2' ]

By specifying that the path string must include the string’ data2′ we filter out any paths that don’t contain ‘data2’ in them. Remember, whatever function you pass to filter must return true for the item to be included in the result.

Assign Keys to an Object with the Same Name

When you are assigning keys to an object if the key is the same name as the variable that holds the value you want to assign, you can omit the value assignment altogether. This prevents you from having to repeat yourself, something we all hate doing. Take a look at this example:

let name = 'John';
let age = 32;
let job = 'engineer';

// instead of this
let profile1 = { name: name, age: age, job: job };

// do this
let profile2 = { name, age, job };

console.log(profile2);

Output:
{ name: 'John', age: 32, job: 'engineer' }

Using the ES6 Spread Operator ‘…’

The spread operator allows you to quite literally “spread” out an array. This can be used to transform an array into a list of arguments or even combine two arrays. You could also use it to form a list of arguments to a function too.

In the first example, we show how the spread operator works on an array and turns each item into an individual element.

let numbers1 = [1,2,3,4,5];

console.log(...numbers1);

Output:
1 2 3 4 5

The second example combines the contents of two arrays by creating a new temporary array containing both contents.

let numbers2 = [6,7,8,9,10];

let combined = [...numbers1, ...numbers2];

console.log(...combined);

Output:
1 2 3 4 5 6 7 8 9 10

The last example illustrates how the spread operator can turn an array into a list of arguments to a function. The Math.max returns the highest number in a list of arguments passed to it. One of those arguments was 10, which is the highest.

let numbers1 = [1,2,3,4,5];

let numbers2 = [6,7,8,9,10];

let combined = [...numbers1, ...numbers2];

console.log(Math.max(...combined));

Output:
10

New Getters and Setters Functions

Getters and setters are one of the useful feature introduced in ES6. It comes in handy if we are using classes in JavaScript.

 

class PersonName {
  constructor(name) {
    this.name = name;
  }
  get Name() {
    return this.name;
  }
  set Name(name) {
    this.name = name;
  }
}

let person = new PersonName("Jon Snow");
console.log(person.Name); //(A)

person.Name = "Dany"; //(B)
console.log(person.Name);

Output:
Jon Snow
Dany

We can see there are two functions inside class PersonName with ‘get’ and ‘set’ properties. The ‘get’ property is used to get the value of the variable, and ‘set’ property is used to set the value to the variable. We can see, too, that the get Name function (A) is called without parenthesis, and set Name function (B) is called without parenthesis, and it’s just like assigning a value to the variable.

Listen to our CEO’s podcast “The Daily Drive” to stay driven and get great business insights from top business leaders. – Are you ready to scale your agency with a quality white label SEO, white label PPC, or white label social media provider?
If so schedule a meeting here –