All posts by webammer_anand

Debugging JavaScript in Google Chrome and Visual Studio Code

By James Quick

Learning to debug is an essential skill for taking the next step as a developer. It’s important to understand and leverage the vast array of tools that exist for a given languge. Unfortunately, debugging might not seem as obvious when working with JavaScript outside of a full-fledged IDE. At least not initially. Let’s take a look at getting started debugging JavaScript in the Google Chrome Dev Tools as well as my favorite text editor for Web Development, Visual Studio Code.

Watch on YouTube

https://youtu.be/AX7uybwukkk

TLDR – Debugging JavaScript in Chrome?

  • Open the ‘Sources’ tab
  • Inspect code
  • Set breakpoints, inspect variables, etc.

TLDR – Debugging JavaScript in Visual Studio Code?

  • Download the Debugger for Chrome extension
  • Create Debug configuration
  • Launch Debug configuration
  • Set breakpoints, inspect variables, etc.

Setup

For this article, I’m giong to be debugging an application called ‘Quick Chat’.

While it is not required for you to run the same application, you can easily follow this video series to build the application yourself or clone the source code if you choose.

Whatever project you decide to run, you’ll need to start it up. You can serve your applicatin from Node, like I’m doing, or from the Live Server extension for a simple static site. If you’re new to the Live Server extension, check out this getting started video.

With my project, I’ve added a tiny bug that fails to register who the user is after they’ve logged in. Technically speaking, I’m incorrectly grabbing the user’s username by referencing usernameInput.text instead of usernameInput.value. If I made this mistake in real life, my first instinct is to use console.log() to print out the DOM element reference (bad James….BAD JAMES), which isn’t all that help as you can see. If this is you’re first instinct also, don’t worry, that’s why you’re here!!

Debugging Basics

Let’s start with the basics. The idea of debugging is being able to (conditionally) trigger what are called breakpoints to pause the execution of your code. This provides you, the developer, the opportunity to look at the state of your application by inspecting variables for example. You can even take it a step further and ‘watch’ variables of your choosing, so that whenever your application gets paused, you can inspect them specifically. After triggering a breakpoint, you will typically have the following options.

  • continue execution of your program
  • step through your code line by line
  • step out of the current function that you are in
  • step into the next function call.

You’ll additionally have access to view the call stack. In other words, as functions call other functions in your program, you can inspect the history of those function calls.

Debugging in Google Chrome

To get started with debugging in Chrome, add a debugger statement to the application as I have below in the loginBtn click event handler.

When this statement is reached, your application will be paused and the debug tools will automatically be activated. Noticed how the application is greyed out to signify that it has been stopped. Notice also how the Sources tab in the Chrom Dev Tools has popped up open proudly.

Let’s breakdown what we’re seeing.

Source Code

The first thing you might notice is what appears to be a copy of your code. This is the code that the browser has loaded and is running as your application. You can also see that the debugger line is higlighted a blue color to let us know that this is where our application has been paused.

Chrome gives you the ability to view this code for a reason. With the code in front of you, you can now set breakpoints. A breakpoint is intentional stopping or pausing place in a program. The debugger statement we used above functions as a breakpoint, but isn’t necessarily picked up by Chrome as one.

Breakpoint – intentional stopping or pausing place in a program

To add a breakpoint, click in the gutter, or empty space, to the left of the line numbers. As your do, notice that Chrome now adds this breakpoint to the list of breakpoints further down.

Scope

In the scope tab, you have the ability to inspect variables in your application. You’ll notice there is a local section (local scope to the function where the breakpoint is), a global section (the global scope), and a scripts section. In the scripts section, you can view variables within the scope of the current script.

This is where a significant amount of your debugging time will be spent. This is a much more efficient replacement for writing out many console.log() statements.

Watch

As I mentioned earlier, in addition to viewing variables in the scope tab, you can also define variables that you want to look into specifically. By adding a variable to the watch tab, each time you hit a breakpoint, you can quickly find the value of that variable (which may be undefined depending on where you are in the code). Hit the add icon and enter the name of the variable you want to watch to track, in this case, usernameInput.

Step Functions, Call Stack, and Breakpoints List

The last section, located in the bottom left of the Sources tab in my configuration, will allow you to view the list of breakpoints, call stack, etc.

In the call stack above, there is one function listed which is the event handler for my login button. This function is listed because it is the only function that has been called so far. As functions call more functions, that chain will be updated appropriately.

Notice also the arrow buttons at the top of this screenshot. These correspond to the functions referenced above for continuing execution of your code or stepping through it line by line or by function. I would recommend testing these buttons for a bit to get used to how you navigate the execution of your code.

Lastly, there are different kinds of breakpoints that can be set. Let’s take a look at creating a conditional breakpoint, one that will only get triggered if a certain condition is met. For example, let’s say we want to break on the login button callback only when the user attempted to login without entering a username. We can do this, by right-clicking in the gutter and choosing conditional breakpoint with the following condition, usernameInput.text === ''.

In the case of debugging Quick Chat, if you press the login button without entering a username, this breakpoint will be triggered. Otherwise code will continue to execute as normal.

Note that there are even more breakpoint options available that are not covered here.

Debugging in VS Code

The Chrome Developer Tools are some of the best in the business. As you’ve seen so far, they offer a great experience to debug your application with lots of functionality. However, Visual Studio Code has worked really hard to match that debugging functionality in a more seamless way. In my mind, I absolutely love VS Code and want to spend as much time there, and not in other tools, as possible. This includes debugging.

I absolutely love VS Code and want to spend as much time there, and not in other tools, as possible. This includes debugging.

To get started debugging in VS Code, you will need to install the Debugger for Chrome extension.

Let’s take a quick look at the Debug tab in the sidebar (on the left side of your editor by default). Open the debug tab by clicking on the icon that… well looks like a bug. With this pane open, you should recognize very similar tools to what we saw in Chrome… variables, watch, call stack, and breakpoints.

The majority of the functionality that you get in Chrome Dev Tools is available right here inside of VS Code.

Now that we’ve seen the Debug tab, we need to create a launch configuration that tells VS Code how to debug your application. VS Code stores debug configurations in a file called launch.json inside of a folder .vscode. To have VS Code create this file for us, click on the ‘No Configurations’ dropdown and choose ‘Add Configuration’.

VS Code stores debug configurations in a file called launch.json inside of a folder .vscode.

Then choose ‘Chrome’ in this case.

Then, choose the ‘Chrome: Launch’ configuration from the popup dropdown list.

The specific configuration that we created will automatically attach to the application at the defined port. We need to make one small change to this configuration to correctly point to the source code for the app. The source code is located in the public directory, which is why I have updated the ‘webRoot’ property.

**Keep in mind that your application must already be running locally at a certain port for this to work.

With the configuration defined, you can now start your debug session by clicking the green play button. Your application should pop up in a Chrome window as shown. Also, notice the debug menu bar that popped up in the background inside of VS Code. With this debug toolbar, you can pause, restart, continue, and use step functions to navigate your code and interact with the debugger.

With this debug toolbar, you can pause, restart, continue, and use step functions to navigate your code and interact with the debugger.

With debugging connected, you can set a breakpoint in the code, just like we did in Chrome. Click in the ‘gutter’ next to the line number. I’m keeping my breakpoint in the same location as before, just inside the login event callback.

Now, when trying to login without entering a username, the breakpoint should trigger swiching the contect back to VS Code for further investigation.

From here, the functionality that we discussed in Chrome maps over directly to VS Code. If you want to add a conditional breakpoint, right-click in the gutter and choose ‘conditional breakpoint’ with some condition. If you want to watch a variable, click to add a new one, and type the name of the variable to watch. If you want to explore variables, go to the variables tab and explore away!

Recap

As I said ealier, to take that next step as a developer means more than just writing better code. It means taking advantage of the ecosystem of tools that your language lives in. Debugging is one of those topics that takes some time and effort to get started with, but ultimately, the benefit will vastly outweigh the cost.

My recommendation is to spend some time debugging with both Chrome and VS Code, and see what you like best. If you have any questions or comments, find me on twitter, @jamesqquick.

Source:: scotch.io

Weekly Node.js Update - #24 - 06.15, 2018

By Tamas Kadlecsik

Weekly Node.js Update - #24 - 06.15, 2018

Below you can find RisingStack‘s collection of the most important Node.js news, updates, projects & tutorials from this week:

Node.js Updates from June 12

Google Cloud announces support for Node.js in App Engine

Google announced that App Engine is gaining support for the wildly popular Node.js JavaScript run-time.
One of the primary focuses for App Engine’s Node.js support is making the experience comfortable and familiar for developers.

Deploying Node.js on App Engine standard environment

In this video you will learn how you can quickly and easily deploy a Node.js application on App Engine standard environment.

AWS SDK for Node.js Best Practices

Most code examples covering the AWS SDK for Node.js initialize various AWS service clients. Save precious loading times and memory — especially helpful in compute resource constrained environments like an IoT device or inside an AWS Lambda function.

How To Interact With Database Using Async Module In Node.js

The asynchronous feature of Node.js makes the processes more efficient, but we cannot prefer this asynchronous nature in all scenarios. When should we select the synchronous method over the asynchronous?

The Dangers of Malicious Modules

According to a recent security survey by npm, 77% of respondents were concerned with the security of OSS/third-party code. This post will be covering security vulnerabilities introduced into an application by way of code written by a third party.

Building A Pub/Sub Service In-House Using Node.js And Redis

As the size of data for each message in our system differs from a few bytes to up to 100MB, we needed a scalable solution that could support a multitude of scenarios. In this article, Dhimil Gosalia explains why you should consider building an in-house Pub/Sub service, too.

From Node.js to Go: There, and back again

Read TheNativeWeb’s story about chosing GO over Node.js to write a wolkenkit CLI, then rewrite everything from scratch, this time using Node.js again. What did they learn from this journey?

Why Is Node.js Becoming Popular Among Online Retailers?

This smart technology makes the app ten times faster than other technologies, by decreasing the load time to a large extent.

Previous Node.js Updates:

In the previous Weekly Node.js Update, we collected great articles, like

  • 10 Things I Regret About Node.js – Ryan Dahl;
  • How we built a nationwide live video streaming service using Node.js Microservices powered by Redis;
  • Building RESTful Web APIs with Node.js, Express, MongoDB, and TypeScript — Part 5;
  • The Node.js Event Loop: Not So Single Threaded;

& more…

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

The Next Scotch v8: How We're Getting to 1s Load Times

By Chris Sevilleja

You might be wondering, “are they redesigning again?!” Whenever I’m asked that, my answer is always a resounding “OF COURSE!”

Sure the Scotch site is currently good enough, but there’s always ways to improve. This next version is what v7 was supposed to become.

Some of the main features

  • Fully cached pages (JAM stack-ish)
  • Better discoverability (real-time search everywhere)
  • Clearer site sections (Guides/Courses/Posts always confused people)
  • More video content
  • More community involvement

In this post, I’ll dive into some of the main technical changes and reasons why.

Launch is impending ™ (copyright).

The Problems with Scotch v7

Before we can design something new, we need to know where we come from. We have to identify problems and iterate on them (or blow them up). Otherwise, we’d end up with the same problems as the previous design. History repeats itself as they say.

Scotch is Slow Globally

In the states, Scotch responds quickly. We’re hosted over at Digital Ocean in New York.

Our site audience is pretty global though. And those speeds are not as impressive.

Load time doubles when moving across the world to Mumbai. Unacceptable!

Also, first byte time for both of those are slower than Google’s recommended 200ms.

New Site Numbers

Here’s some early numbers on the new design (from Mumbai):

  • Load time: 1.36s (down from 16.52s)
  • First byte: 0.27s (down from 0.92s)
  • First interactive: 1.06s (down from 8.19s)

Solid numbers! Really excited about that first interactive improvement.

Still early numbers and I still think we can improve. We’ll talk about how we got to these numbers later in this post.

Finding Content is Hard (and confusing)

Our current site header:

We lost so many sections of the site. Bet you didn’t know these existed:

  • Guides
  • Author’s Section (Post Ideas)
  • Newsletter
  • Shop
  • Forums
  • Tag Pages (Angular, React, Vue, Laravel)

New idea for site header:

Ever since v7 launched, our pages/visit went down from ~3 to 1.3. Big loss there and we think this will fix it.

We’ll have a lot more updates on finding new content when we get closer to launch.

Content Discovery Improvements

Here’s a tease of what we’re cooking up with real-time Algolia:

We’ll be talking much more on design in the next site updates.

The State of Blogs: Era of JAM Stack

The JAM stack is a great way to build blogs these days.

  • JavaScript: Get the data
  • APIs: Provide the data
  • Markup: Prebuilt sites from a site generator

Ultimately, what JAM stack meant to us was:

  • Separate API w/ JWT authentication (easy enough)
  • Separate frontend that hits API (not sure how to implement. keep current or move everything)
  • Serve sites statically for crazy uber duper fast load times (not sure how to implement. keep current or move everything)

Blogs these days are becoming more and more static. Many blogs (including Smashing Magazine) have moved towards static-sites.

A few tools for static sites:

I asked myself:

If we built a blog starting today, with the tools available, what would it look like?

I knew that we had go fully static. The question is how to do that?

  • Do we move our entire infrastructure?
  • Can we use what we currently have and create a static site?
  • Two parts. Do we move the API? Do we move our frontend markup?

We decided that having a static site brought lots of benefits that we needed.

Going JAM and Caching Everything

This can’t be underestimated at how much speed this brings, especially globally. If you never have to spin up a server, you can serve pure HTML for a request and speed things up greatly. No wonder so many are doing it.

We’ve seen this with traditional server-side setups by using Varnish and NGINX Caching. I tried that with the Scotch setup, but never found configuration easy enough. I don’t consider myself a backend devops type person (hats off to those who can), so I wanted an easier setup.

The big problem with going to a fully static site is removing any server-side session usage. Our entire auth setup!

We had to remove any auth things in the view and handle that client-side with JWTs. Thinks less of this from Laravel:

@if (Auth::user())
  I am logged in!
@endif

And more of client-side JavaScript JWT auth.

if (localStorage.getItem('user')) {
  // render some stuff in that div over there
}

This leads us to the next point. Moving to a JWT setup means we got to separate backend API and frontend concerns.

Our Options Moving Forward

Here’s our current setup:

As you can tell, we’re big fans of Laravel. Going JAM meant we had to make API JWT authenticated and frontend views had to be API driven. Options were:

1. Total Loss of Control

Move our blog to a 3rd party. Medium, Ghost, WordPress, etc. Not for us.

2. Move the API + Frontend to JavaScript

This is the traditional JAM stack setup.

  1. Move our content and API over to Contentful
  2. Move the frontend to Angular, React, or Vue
  3. Use a static site generator like Gatsby to generate our site
  4. Host the statically generated site through Firebase or Netlify

Big architecture changes to go fully JavaScript. While tempting, there wasn’t a compelling reason. The goal was to get to static sites. Totally achievable without changing everything.

We invested a lot of time into our setup and have some custom stuff. It would probably take a decent amount of time to move the API to Contentful or prismic. Also, that’s another expense we’d have to take on monthly.

We’re still a small team (Scotch is a side project for us) and want to stay as lean as possible. As few monthly expenses as possible so this option would’ve brought on two new costs (Contentful and Netlify).

3. Update Current API + Frontend goes JavaScript

We could keep our current API and have JWT auth. Really easy to switch thanks to Laravel. Then we build out the frontend in JavaScript, generate static sites, and then host statically.

This was something we really looked at. Ultimately, we wanted to see if there was something easier than moving the entire frontend.

Scotch Solution

With all these awesome new tools out there, what would be the best solution that got us a better site and got it fast?

The problem we faced is that we already have a solid backend built fully custom on Laravel with lots of custom features.

We decided to keep our current Laravel backend and API. We also decided that we’d use Laravel to serve our HTML but also add React on top for the auth things.

No need to go fully JavaScript frontend. Laravel for sites + JS auth vs JS static generated site + JS auth. Pretty similar in the end result.

Getting Static Sites

So how would we get a static site? Drumroll… we would let our good friends at Cloudflare handle that!

  1. Update the current Laravel API
  2. Update our views to have React dropped on top for only the authenticated parts (user nav, bookmark/like buttons)
  3. Use Cloudflare to statically cache and serve the site

Easy Cheese!

Sometimes the best solution is the easiest. I know this solution came out of left field. It’s essentially change as little as possible. I like to call what we’ve done “JAM Stack-ish”.

It takes 5 seconds to switch Scotch to fully cached static pages delivered globally:

Cloudflare is amazing (not paid to say this). We even have a case study.

With Cloudflare handling the static site generation and us using our already existing API, we were able to switch to static pretty easily. The architecture change of switching from session auth to JWT auth was the biggest amount of work.

Since we had to redo all the auth, might as well redesign the site and fix our problems!

Recap and Up Next

So to recap, we went with minimal architecture changes. This only touched the surface on the new site. Here’s what we’ll be talking about next:

  • How we improved content discovery?
  • Making a better writing platform for coding authors (Dashboard updates)
  • Improving tech blogs. Tech blogs have been the same. Let’s make them better

This was a long journey learning about the current state of blogs and are happy with the choices we’ve made. This isn’t to say that these choices will be right for your setup, but definitely weigh all the options. It may be tempting to move to the latest and greatest, but ask if that’s really the best way forward.

Let me know what you think of our changes moving forward!

Source:: scotch.io

Code Challenge #11: JavaScript Functional Programming

By William Imoh

Previously on the code challenge #10, we delved into lazy loading images for performance, you can check out the challenge post and solution.

This week on the code challenge, we’ll be re-visiting the basics of JavaScript with Arrays. Arrays are like containers which hold various data types.

While these containers are useful for holding various data types it is important to understand the manipulation of arrays to analyze and utilize withheld data. This is done with the use of specific functions which are actionable on Arrays called Methods.

The Challenge

This challenge is quite unique such that we will be using some really useful built-in array methods to manipulate the provided arrays. Three arrays are provided and each comes with 3 problem parts to be solved.
In the first array:

  • Part 1 – Find all users older than 24
  • Part 2 – Find the total age of all users
  • Part 3 – List all female coders

In the second array:

  • Part 1 – List all users in the US in ascending order
  • Part 2 – Sort all users by age
  • Part 3 – List all female coders

In the third array:

  • Part 1 – Find the total age of male coders under 25
  • Part 2 – List all male coders over 30
  • Part 3 – Find the total age of everyone in texasss, newieyork and vegzas combined.

Complete these problems using any array method in the best way possible. Useful methods include:

  • .map()
  • .filter()
  • .find()
  • .replace()
  • .reduce()
  • forEach()

Note that you can write your results to the DOM or even log to console, whichever is fine by you.

Requirement

This challenge can be completed by using any technique or method. However, try to completely solve each part in as little lines as possible using functions.

Goals for this Challenge

On completion of this challenge you should be able to:

  • Learn basic functional programming concepts and immutability
  • Utilize built-in array methods to sort, filter and traverse arrays.
  • Choose the right methods and alternatives to analyzing data in an array.

Bonus

In a bid to make this more fun and challenging, a bonus will be to complete this the challenge parts without the aid of built-in methods and functions.

Resources

To get started quickly, a base codepen containing required arrays is provided. These arrays to be utilized contain objects with data in key-value pairs.

Fork this base codepen to get started

This previous Scotch post could be useful to you in solving this challenge.

Community

On completion of the challenge, if you wish to showcase your work and receive reviews, kindly,

  • Post it on Twitter using the hashtag #scotchchallenge and be sure to tag us to see it!
  • Build your writing skills by writing about how you solved it and we’ll be glad to feature it in our community posts!
  • Post it in the comment section under this post.
  • Post it on the #codechallenge Slack channel in the Scotch Slack.
  • Join the chatter on Spectrum and showcase your solution.

Solution

The solution to this challenge will be released on Saturday. Happy coding!.

Source:: scotch.io