fbpx

Best 5 Ways to Use Spread Operator In JavaScript

Understand Spread Operator In JavaScript with example . We are also going to find out How to Deep Copy objects In Modern JavaScript , We will also check How Spread Operator doesn’t deep copy the Properties and what should we do if we want to deep copy object properties in JavaScript .

Did you noticed {...} in any of your code ? This interesting dots in JavaScript  is known as spread operator . In this post we are going to demystify this special syntax in JavaScript world .

What is Spread Operator In JavaScript

Spread operator is one of the most interesting featured added in JavaScript in recent days. As the name Suggests Spread , so it basically spreads or expands the value of an iterable object in JavaScript.

Have a look at the definition of Spread Operator from Mozilla Doc .

There are multiple scenarios where spread operator comes to the rescue while doing development . We will be having a look at all those use cases here

Examples of Using Spread Operator With JavaScript

  1. Merging Objects .
  2. Merging or Copying Arrays .
  3. Converting String to Array .
  4. Deep Copy Using Spread Operator In JavaScript .

How To Merge Two Objects ?

We have two objects and we are going to using spread operator on both the object literals and construct a new merged object , with contents of both the objects .

let employee = { name:'Frugalis',lastname:'Minds'};
const salary = { grade: 'A', basic: '$2900' };
const summary = {...employee, ...salary};

Now Once you try running this , the result is a merged object literals here achieved in a pretty simple way using this amazing JavaScript feature

Here employee and salary objects are merged together and that produces a new object with merged key value pairs .

Now lets say we have some common key in both the objects , How would spread operator behave in that case .

let’s have a look

let employee = { name:'Frugalis',lastname:'Minds'};
 const salary = { name: 'A', basic: '$2900' };
 const summary = {…employee, …salary};
Spread Operator Javascript Merged Object

Note:- In all cases of merging objects wheather multiple or single . Always the last object will be replaced in all scenarios .

With the above scenario we can also use Object.assign{} to achieve the same result but with Spread operator its more easier and convenient .

Converting String to Array

Considering one of the very common use case and simple one to demonstrate an example of Spread operator in JavaScript world .

let data= "spring"
  // Without spread operator
 console.log(…data);

We have converted a plain simple string to an array using Spread operator .

Merging Or Copying Arrays Using Spread Operator

Now lets say we have a two different array of String or any other array . We can use spread operator on arrays to merge two arrays together like below

Have a look at the array below

let javaTech= ['spring', 'java'];
 console.log(javaTech); // Without spread operator
 console.log(…javaTech);

We are expanding this whole iterator of array into single piece of object . If you notice we do not get array anywhere in content. We actually get the items of the array in plain text format.

Now lets say we merge a two different set of arrays here . Lets See how Spread operator works in that case .

let techlist1= ['spring', 'java'];
 let techlist2= ['javascript', 'nodejs', 'mongo'];
 let fullstacklist= […techlist1, …techlist2];
 console.log(fullstacklist);

Here You have seen the Spread operator merges the two arrays techlist1 and techlist2 .

Resultant is a list of String which is retrieved out of the array and assigned into a new array using [] syntax .

In all of the above cases, we have seen the copying of array is done similar to what we used to do using object.assign{} .

All the above spread operator examples in JavaScript are doing a shallow copy , what if i need my spread operator to do a deep copy of nested objects .

Deep Copy Using Spread Operator In JavaScript

So I was providing some question’s answer on Stack Overflow, and found that Spread Operator doesn’t exactly do deep copy .

That led to me long debugging sessions for the Spread Operator and I will share my observations on Spread Operator and Deep Copy using spread operator in my JavaScript code.

Problem Statement – 

So problem was, I wanted to deep copy the JavaScript Object let’s say –

 let fruglise = {
 type : “Code”,
 code : 123
 }
 

So whenever we use a spread operator (written as …) for copying the object, I thought it does in a way of deep copy thing like – 

let copyObject = {...fruglise}
So whenever we change the properties of the “copyObject” ( copyObject.code = 36 ) it will not change the properties of the original object.

Spread operator deep copy example

Here you could see, in the above code snippet. We have changed the property of the “copyObject” but didn’t reflect on the original object.

But Let’s see different magic example ,

let randomExample = {a : 123, b: {c : 23}}
let copyRandomExample = {...randomExample}

What if we’ll do –

copyRandomExample.b.c = 1000

Guess What ? It will change the properties of the Original Object, Have look –

Well why so ?

Because it (Spread Operator) does till the first level, whenever it finds the nested level, it doesn’t do the Deep Copy. It does the Shallow Copy of the Object from next level onwards .

In summary Spread Operator (written as …) does the Shallow Copy(for first level it does but for others it doesn’t). 

How to Deep Copy Objects in JavaScript – 
Well if you want to the Deep Copy of the Object you could Use JSON.parse(JSON.stringify(object).But it will not work for the non-Json object just like if the Object values are function().

spread operator deep copy

If one needs full proof of Deep Copy then one could use lodash’s clone Copy.

Points to Remember for interview :-

  1. Spread operator in JavaScript does not Perform Deep Copy Of Objects
  2. You Can use Spread operators as an arguments in iterator objects in javascript .

Building and Publishing NPM TypeScript Package

Building and Publishing NPM TypeScript Package : A Guide from Scratch

In this guide we will build NPM Package from scratch using TypeScript and publish it to the central repository as NPM Package. We will use TypeScript to write the package and Jest to test our code functionality.

What are We going to Build :-

This is what we are going to build , We are going to build a small soap web client package and publish in npm.

https://www.npmjs.com/package/soap-web-client

What is NPM :-

NPM is a package manager and world’s largest library for the node packages from where you could use open-source package and publish your package there. .

Let me tell you npm is a node based package manager . Its is used to manage your projects packages from online registry of packages public and private both . For developers npm is a command line tool , used to manage or pull packages often referred as project dependencies . If you are from a Java programming background , you can think of npm similar to maven .

Here is the official documentation of npm .

Why TypeScript ?

Typescript is a static typed language and helps you write error free code. Typescript is a superset of JavaScript which provides a richer environment for spotting common errors while you write the code.

Let’s KickOff :

Make sure to have latest version of the node, at least >= 7.6 because we have used async/await in our package which was introduced in the nodejs 7.6


Pick a Unique Name :
Since there are a number of packages available in npm, it will be hard for you to name your package but you’ll have to choose one. In this guide we have chosen the name “soap-web-client” since we are going to make a package for the soap web services.

Basic Setup :

Make a Git Repository with the name you have chosen in https://github.com

Clone the created repository :- 

git clone <repository_name.git> && cd soap-web-client

Init your Package :

Let’s create the package.json file first. Enter the below command in command line.

npm init 

Or 

yarn init

Awesome we have done the basics. Package.json will look like something, not exactly. But for sure this package.json provides a metadata about our package that we are going to publish in npm .

 Building and Publishing NPM TypeScript Package : A Guide from Scratch
publishing your npm typescript package in npm

npm install --save-dev typescript

Or 
yarn add -D typescript
Good now you’ll see the node_modules folder.
In order to compile typescript we also needed the tsconfig.json file. So let’s add the same in the root.

{
   "compilerOptions": {
       "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
       "module": "commonjs",
       "allowJs": true, /* Allow javascript files to be compiled. */
       "strict": true, /* Enable all strict type-checking options. */
       "outDir": "./lib", /* Redirect output structure to the directory. */
       "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
   },
   "include": ["src"],
   "exclude": ["node_modules"]
}

Wooh, we have done lots of thing here, let’s understand , tsconfig file indicates the project as typescript project and it includes options on how the typescript files to be compiled

Browsers can’t execute TypeScript directly. Typescript must be “transpiled” into JavaScript using the tsc compiler, which requires some configuration. Typically, you add a TypeScript configuration file called tsconfig.json to your project to guide the compiler as it generates JavaScript files.

target – we want to compile down to “es5” whatever we are writing in the typescript file. There are other target options available.

module – Use commonjs for compatibility.

allowJs – allow javascript files to be compiled.

strict – enable all strict type checking options.

outDir – Redirect target to what directory.

include – which folder should we include for the typescript to be compile.

exclude – which folder should we exclude for the transpile.

Your first step to publish your own npm package :
You are very close to publishing your first npm package. Let’s create the “src” folder and inside this let’s create “index.ts”.

Write any function inside the index.ts file and export that method.

const demoMethod = () => {
return “I’m Duffer”;
}
module.exports = demoMethod;

We have created soap-web-client service hence we have coded like that –



Okay now it is good to go, Next step is to add build scripts in the package.json under scripts.

build” : “tsc”

Now run the build command in the terminal/console.

yarn build

Or 

npm run build

And Magic… You’ll see the lib folder in the root directory.

We have Created the our method which will be exported, let’s write a test case for the same using Jest.

Setup Testing with Jest :


Jest, an awesome package by Facebook.

Since we will be writing tests against our typescript source-files, we also need to add ts-jest and @types/jest. The test suite is only used during development so let’s add them as devDependencies.

npm install --save-dev jest ts-jest @types/jest

Or

yarn add -D jest ts-jest @types/jest

We have added the jest dependency now, let’s put the configuration for the test environment, you could put it into package.json or you could create some configuration file which will provide the configuration to test environment and same we will indicate in the package.json

Let’s create the new file  “jestconfig.json”.

and remove the old test script present in the package.json with

   "test": "jest --config=jestconfig.json",

We will add two more scripts inside the package.json for future use, one is to get code coverage and another is just to clean node_modules.

“coverage” :  “jest --config=jestconfig.json --coverage”,

“clean” : “sudo rm -rf node_modules/”
Now at the end package.json will look like this, you could add dependency on package.json what you need for the first package, but let’s make it simple.

We have done a test setup, let’s create __tests__ folder in the root directory to write the test case in one place.

Write a basic test case :

Let’s write a basic test case for the method we have written in the index.test.ts file.

const testDemoMethod = require(“../src/index”);
test(‘DemoTestCase’ , ()=>{
	expect(testDemoMethod()).toBe(`I’m Duffer`);
});

Save it, now try to run


npm test

Or

yarn test

You’ll see a screen like this, in-case some test are failing, resolve first.

Now we are ready to publish the first package – 

Commit your code to git :

git add .

git commit -m “my first package”

git push origin master

If you don’t have an account at npm, first create the account at https://www.npmjs.com/signupIf you have command then let’s login first in our terminal.

npm login

Or 

yarn login

Provide your username and email id of registered npmjs account, you’ll not have to put your password here.

Last step towards magic :

Let’s publish it, now run publish and provide credentials of npmjs account.

npm publish

Or 

yarn publish

View your package – 
Now you could browse your package at npm. The url of the package will be https://npmjs.com/pacakge/<your-package-name>, in my case it is https://www.npmjs.com/package/soap-web-client

Nice we have got a new package …

Bumping a new version :

If you have made changes and want to push it again after the latest changes then let’s add patch version.

npm version patch

Or 

yarn version --patch

And then again Publish it using the publish command.

Happy coding and publishing ….

Connect with us at LinkedIn –





How to Setup Puppeteer In CentOS 7

How to Setup Puppeteer in CentOS 7

Setup Puppeteer In CentOS 7 is easy but gets tricky in Linux distributions. Few weeks back we have Completed a project using puppeteer . Now the Question was Where Should we deploy ?

Our code is written in Windows and we wanted to move code to Production . Now we have CentOS 7 in prod . We were struggling to run Puppeteer on Prod machine .

Have a look at Environment details we have used to deploy a puppeteer .

Environment Details:

Have a look at Steps we Have Followed to Deploy A puppeteer backed application in CentOS 7

Step 1:- Install Node JS In CentOS 7


curl -sL https://rpm.nodesource.com/setup_10.x | sudo -E bash -

yum install nodejs


Step 2 :- Install Puppeteer In CentOS 7

npm i pupeteer

Step 3 :- Install Chromium In CentOS 7


yum install pango.x86_64 libXcomposite.x86_64 libXcursor.x86_64 libXdamage.x86_64 libXext.x86_64 libXi.x86_64 libXtst.x86_64 cups-libs.x86_64 libXScrnSaver.x86_64 libXrandr.x86_64 GConf2.x86_64 alsa-lib.x86_64 atk.x86_64 gtk3.x86_64 ipa-gothic-fonts xorg-x11-fonts-100dpi xorg-x11-fonts-75dpi xorg-x11-utils xorg-x11-fonts-cyrillic xorg-x11-fonts-Type1 xorg-x11-fonts-misc

Step 4 :- Install puppeteer in CentOs7

npm install --save puppeteer

Now Let’s Write a Sample Code to run Puppeteer in headless mode and name that file as test.js

'use strict';
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
  console.info("Starting browser");
  let browser;
  try {
    browser = await puppeteer.launch({});
  } catch (e) {
    console.info("Unable to launch browser mode in sandbox mode. Lauching Chrome without sandbox.");
    browser = await puppeteer.launch({args:['--no-sandbox']});
  }
  console.info("Browser successfully started");
  console.info("Closing browser");
  await browser.close();
  console.info("Done");
})();

Step 5 :- Run the Code , you will see the following output

Setup Puppeteer In CentOS 7
running puppeteer centos7 without sandbox mode

Real problem starts here , We are not able to launch browser without --no-sandbox flag.

I Challenge most of you will face this problem while you setup puppeteer in Centos 7. SO Follow down this simple hack to solve this . I struggled a lot , I think you may or may not . But if you have reached this section of article then i firmly believe you have faced this as well.

For running Puppeteer in sandbox mode we need to do few changes as of now .

If you navigate to node_modules/puppeteer/.local-chromium/linux-549031, you notice that for puppeteer there is a file named chrome_sandbox (with an underscore).

Renaming this file to chrome-sandbox and perform following steps below


sudo mv chrome_sandbox chrome-sandbox
sudo chown root chrome-sandbox
sudo chmod 4755 chrome-sandbox

So what are we doing here ,

We are renaming the chrome_sandbox folder to chrome-sandbox as standard chromium searches for file with chrome-sandbox. Now run the test file again.


$ node test.js

Starting browser
Browser successfully started
Closing browser
Done

Conclusion :-

While running puppeteer we were facing issues Unable to connect to chrome . While searching on internet about the problem i got this solution . Hence sharing this with you all . Let me know if this helps .

References :-

https://github.com/puppeteer/puppeteer/issues/560

https://github.com/puppeteer/puppeteer/issues/497

https://github.com/puppeteer/puppeteer/issues/2857

Redefining JavaScript loops – filter map and reduce

Redefining JavaScript loops – filter map and reduce

In JavaScript we have been writing loops , like we do in any programming language . Today we are going to check JavaScript  filter , map and reduce . These are a part of JavaScript Functional Programming .

We are not going to deep dive into the concepts of functional programming in java script . Lets get started and have  a look at these concepts.

Have a look what MDN Says about these JavaScript filter map and reduce :-

  1. Filter In Javascript  :- As the name suggests, it returns an array with filtered  items from the original array
  2. Map In Javascript :- Used to create a new array by iterating existing array
  3. Reduce  In Javascript  :- Returns a single object .

We are going to take following example where we have an array of employees and we are going to do some operations on this array to demonstrate JavaScript filter map and reduce.




How to use Filter In JavaScript  :-

How Would you Find Out Employees Whose age is less than 50 here in above employee array ?

In a Normal JavaScript we would do something below as shown ,

let seniorCitizen = [];
for(let i = 0; i < employee.length; i++) {
  if(employee[i].age <= 50) {
    seniorCitizen.push(employee[i]);
  }
}

Now We have a different Way of Doing this using Javascript Filter .

const seniorCitizen= employee.filter(function(emp,index) {
    console.log(index);
      if(emp.age <= 50) {
        return true;
      }
    });

JavaScript Filter we can pass two arguments inside a callback function , actual object and index .

We can also Write same thing using ES6 syntax as below .

const seniorCitizen= employee.filter((emp,index) => {emp.age <= 50});

Output:-

How to use JavaScript Map  :-

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

const usernames = employee.map(function(emp) {
  return emp.name;
});

const test1 = employee.map(function(emp) {
  return `${emp.name} [${emp.age} - ${emp.salary}]`;
});

const testMap = employee.map(emp => `${emp.name} [${emp.age} - ${emp.salary}]`);

const ageMap = employee
  .map(emp => emp.age * 2)
  .map(age => age+2).filter(age=>age<88);

console.log(ageMap);
console.log(test1);
console.log(testMap);

Output :-

 Array(1) [48]
 Array(3) ["Sanjay [23 - 34545]", "John [43 - 3444]", "Sean [53 - 344445]"]
 Array(3) ["Sanjay [23 - 34545]", "John [43 - 3444]", "Sean [53 - 344445]"]

How to Use JavaScript Reduce :- reduce()  works on an array and returns a single object .We are going to write a code works on an array and reduce to compute the total value of age of users  array .

Lets See How We can achieve this :-

const ageSum = employee.reduce(function(total, emp) {
  return total + emp.age;
}, 0);

In the above example we are passing two parameters to the callback function , total is known as accumulator. The Job of accumulator is it accumulates the callback’s values . It is the accumulated value previously returned . In this case we have initialized our accumulator with zero value .

So once the first element of array is traversed accumulator total will have 0+age of First employee. Now this value is passed to the next callback function for second array item and so on.

Now We Can simplify the above JavaScript reduce() code using ES6 syntax as :

const totalYears = employee.reduce((total, emp) => total + (emp.age), 0);

 

Please Comment if You Want some More examples or You are stuck at any place .We will be happy to help you ! Thanks !