Detect last iteration in FOR OF loop in ES6 javascript

One approach is using Array.prototype.entries(): for (const [i, value] of arr.entries()) { if (i === arr.length – 1) { // do your thing } } Another way is keeping a count outside the loop like Shidersz suggested. I don’t think you want to check indexOf(item) though because that poses a problem if the last item … Read more

Is it possible to have a comment inside a es6 Template-String?

Option 1: Interpolation We can create interpolation blocks that return an empty string, and embed the comments inside them. const fields = ` id,${ /* post id */” } message,${ /* post status/message */” } created_time, permalink_url, type `; console.log(fields); Option 2: Tagged Templates Using tagged templates we can clear the comments and reconstruct the … Read more

generic throw giving Expected an object to be thrown lint error

throw Object.assign( new Error(myMessage), { code: 402 } ); Throw a regular error and extend it with custom fields. You could also write a reusable error class for that: class CodeError extends Error { constructor(message, code) { super(message); this.code = code; } } throw new CodeError(myMessage, 404); That way, you can distinguish the errors easily … Read more

How do you check the difference between an ECMAScript 6 class and function?

I think the simplest way to check if the function is ES6 class is to check the result of .toString() method. According to the es2015 spec: The string representation must have the syntax of a FunctionDeclaration FunctionExpression, GeneratorDeclaration, GeneratorExpression, ClassDeclaration, ClassExpression, ArrowFunction, MethodDefinition, or GeneratorMethod depending upon the actual characteristics of the object So the … Read more