Aspire Media

a web development and technology blog

Pascal’s Triangle in JavaScript

| 0 comments

Pascal's Triangle

Recently I came across a JavaScript challenge on the internet. The challenge was to generate Pascal’s Triangle using JavaScript. If you don’t know what Pascal’s Triangle is, in short, it is a mathematical concept of a triangular array of the binomial coefficients (not original to Pascal). For more details see this on Wikipedia. I decided to give it a whirl. The first challenge was conceptualizing and creating a triangular array. Since arrays are typically rectangular, this took some mental maneuvers. Upon some reflection, I realized that there was no way to recreate the triangle. What was needed was some way to make everything except the actual triangle fade to white, in other words, to ‘null’ away.

I ended up using a two-dimensional array, null-ing out irrelevant outliers¬†and calculating subsequent rows and columns based on previous and next columns using each previous row. I decided to take multiple passes (loops) at massaging the data in each cell in order to make the logic a bit more straightforward. Here’s what I ended up with:

See the Pen Pascal’s Triangle by Arthur Khachatryan (@ArtBlue) on CodePen.

I decided to add some parameters to make things interesting and to display the triangle on the page instead of logging to console to make it look better. I wouldn’t be surprised to find a better and more efficient way of doing this – that is the very nature of programming.