How do I use the jQuery.css() Method?

jQuery

Angular logo - cssThe jQuery CSS method allows you to style one or more DOM elements

Let’s begin with the HTMLElement.style property, which provides the access you need to style any DOM element. As a front-end web developer, you should make it a point to be familiar with this low-level DOM API. But the HTMLElement.style property comes with challenges, the two biggest being:

  1. The syntax is verbose, which leads to repetitive, boilerplate code.
  2. You cannot overwrite the HTMLElement.style property, which means that you cannot arbitrarily assign an object to it.

Now while it may seem like a minor detail that you cannot overwrite the HTMLElement.style property, this limitation does negate the ability to assign a well-crafted object to an HTMLElement’s style property. It also severely minimizes code re-use.

But the jQuery CSS method provides a powerful way to sidestep the quirky limitations of the HTMLElement.style property. It offers the ability to style DOM elements in a way that is considerably more elegant and expressive.

For one thing, the syntax is based on method chaining; you chain the css() method to the result of any jQuery query. So whether your query returns one or many elements, the style property and value that you pass to the css() method will be applied to the element(s) returned by your query. And in addition to a more concise syntax, there is the potential for code reuse. And finally, something that is often overlooked about this method: you are styling the DOM element directly (as opposed to using an external style sheet). As a result, the styles you apply will enjoy a high specificity.

In its most basic form, the jQuery.css() method takes two arguments. Both arguments are strings. The first argument is the name of the CSS property that you want to change. The second property is the new value for that CSS property. When you execute the CSS method against one or more DOM elements, jQuery adds a style attribute to each DOM element. And then, jQuery uses the second argument you provided as the value for that CSS property.

Try it yourself !

In the above example, there are five paragraph elements. Click each paragraph. When you do, you’ll see that each clicked element turns red. Click the JavaScript tab. In the JavaScript code, you’ll see that there is a click-event handler set up for each paragraph element. As a result, when any paragraph is clicked, jQuery executes the CSS method against that paragraph. Two arguments are passed to the CSS method. The first argument is color, which is the CSS property that we want to change. The second argument is red, which is the new value for that CSS property.

So, the approach taken so far is a very simple implementation of the css() method. In this case, we are passing only two strings. These two strings act as key/value pairs for the specified style property. But it is also possible to pass an object to the css() method. Significantly, this approach allows you to style multiple properties of an HTMLElement. This, of course, is an advanced implementation of the css() method, which I’ll cover in another article; for now, it’s just good to be aware of it.

Summary

So once you’ve had a chance to work with the css() method a little, I think you’ll agree that it is arguably one of the most genius features of jQuery. It frees you from two limitations of the HTMLElement.style property, and in addition to the elegant syntax, this method provides a way to re-use well-crafted code, in order to style multiple DOM elements. And if you look into the advanced syntax, you’ll see that multiple styles can also be applied within one call to the css() method.

JavaScript Array.prototype.unshift()

Array.prototype

unshiftThe JavaScript unshift method adds the specified value to the beginning of the array and returns the new length of the array. It is the most efficient way to add an element to the beginning of a JavaScript array.

While some may be tempted to use the Array.prototype.splice() method to add an element to the beginning of a JavaScript array, you can trust me when I say, the Array.prototype.unshift() is the way to go. I will add though, just as an observation, I’ve always felt that the method name “unshift” is clunky and unintuitive. Nevertheless, it is the one that the ECMAScript specification has given us, so we’ll just have to hold our noses : – ) and dive right in.

So, the syntax for the Array.prototype.unshift() method is quite simple. You just chain unshift() onto your array variable name, and pass one argument to that method: the element that you want to add to the beginning of your array. For example: myArray.unshift(“hello”) would add the string “hello” to the beginning of the “myArray” array.

So you can pass any valid JavaScript value as the argument to the unshift() method. This could be a number, an object, another array or even an expression such as an executed function. But it’s important to keep in mind that the unshift() method returns the new length of the array.
So, if an array has five elements, calling the unshift() method will return “6”, because adding one element to that array has increased the length of the array to “6”.

Try it yourself !

In the above example, click the JavaScript tab. You’ll see that we have the foo array, which has three elements. Each time that we call the unshift method, the value that we pass as an argument is added to the beginning of the array. Notice that we show the return value of the unshift method in the console. This allows us to see that shift returns the new length of the array.

Click the Result tab. Notice how we call the unshift method a total of three times. Each time, we show the return of that call to unshift: “4”, “5”, and “6”. We also show that we use the console.dir method to inspect foo. This is so we can see the changes that are happening to the array with each call to unshift.

Video Example Code

If you want to download the example code, visit this page: bit.ly/kcv-array-unshift

Summary

So, big picture: the ECMAScript specification provides a number of methods on the Array.prototype object that are designed for handling mutations to the beginning and end of an array. The Array.prototype.unshift() method, for example, is specifically designed to efficiently add an element to the beginning of an array. The way it works is, the element that you pass as the sole argument is added to the beginning of the array, and the new length of the array is returned. Simple and efficient… that’s what we like, right?

JavaScript String.prototype.split()

String.prototype

XXXThe JavaScript split method turns a string into an array. You simply need to pass one or more characters as the separator.

Some may find it odd that all JavaScript strings have a prototype object. After all, isn’t a string a primitive type? Well, the answer is “yes”: a string is a primitive in JavaScript, but the string primitive has a prototype object “wrapper”. This wrapper prototype object actually wraps the primitive string temporarily, providing a number of properties and methods. Now one of the properties provided is the split() method, which allows you to turn the string into an array whose elements are specific parts of the string. And those parts are determined by the separator character (or characters) that you provide as the first argument.

When you need to convert a string into an array, you first need to decide how to split that string. In other words: what character in the string indicates a new array element? For example, if you determine that any single space is a separator, then every word in the string will become a new array element.

Now this is a fairly typical scenario (and perfectly valid). Another common case is when you have a string of words or phrases separated by commas, and you need to turn each word or phrase into an array element. In this case, the comma is your separator character, and you’ll need to pass it to the split() method. So keep two things in mind: 1) If you do not provide an argument to the split() method, it will return an array with one element: the original string (i.e. the split() method did not understand how to split the array!). 2) If you provide two quotes as the argument to the split() method, it will return an array and every single character in the original string will be an array element (this could potentially be a large array).

Try it yourself !

In above example click the JavaScript tab. There are a series of console.dir statements. We use console.dir because the JavaScript split method returns an array, so we want to inspect that array. We are using the string: “I want to be an array”  for each example.

In the first console.dir statement, we can see that passing no arguments to the split method returns an array where every character in the string is an element (including spaces). In the second console.dir statement we use a single space as the separator character (” “). This returns an array were every word in our string becomes an element. This is a very common approach, and quite useful. The third and fourth console.dir statements show other ways that you can provide a separator. The results are a bit odd, but the main point here is that it is really up to you: you can use any character(s) in that string in order to convert the string to an array.

Summary

So, to recap, every JavaScript string primitive has a temporary object wrapper that provides various properties and methods. That string primitive wrapper prototype includes a split() method, which allows you to convert that string into an array. So, you need to let the split() method know how to “split” the string into the array elements, and that is accomplished by the one or more characters you provide as the first argument.

JavaScript Array.prototype.splice()

Array.prototype

javascript spliceJavaScript’s Array.prototype.splice() method removes one or more elements from any position in the array and returns the removed elements in a new array. It also allows you to add one or more elements to the middle of an array.

JavaScript’s Array.prototype.shift() and Array.prototype.pop() methods allow you to remove elements from the beginning and end of a JavaScript array. These methods are simple to use and require no arguments because there is no potential for ambiguity: the concepts “first element” and “last element” require no further explanation. But when you want to remove one or more elements from the middle of a JavaScript array, there are details required. For example: where in the array do we want to start removing elements? Also, how many elements do we want to remove?

The Array.prototype.splice() method answers that question by removing one or more elements from any position in the array and returning the removed elements in a new array. Initially, this can throw you off because if you want to remove only one element, you would expect just that one element to be returned. But the Array.prototype.splice() method always returns an array. So, just keep in mind that if you plan to remove one element, you’ll need to access the first element in the array that is returned.

The syntax for this is simple: you just pass a minimum of two numbers to the splice() method: the position in the array at which you want to start removing elements, and the number of elements to remove. In this case, you are only removing elements from the array. But you do have the option of adding as many additional parameters as you like. So, beginning with the 3rd parameter, you specify one or more elements to ADD to the array, starting at the position specified with the first parameter. For example: myArray.splice(2, 3) would remove three elements from myArray, starting at index # 2. But, myArray.splice(2, 3, ‘a’, ‘b’, ‘c’) would also add the strings ‘a’, ‘b’, ‘c’ to the array starting at index # 2.

JavaScript’s Array.prototype.unshift() and Array.prototype.push() methods allow you to remove elements from the beginning and end of a JavaScript array. But if you want to remove elements from the middle of an array, the Array.prototype.splice() method is the correct tool. In this case, you provide a zero as the 2nd argument, which means that you are saying: “I do not want to remove any elements from the array”. If you provide any arguments after the 2nd argument, however, then those will be added to the array starting at the position specified in the 1st argument. For example: myArray.splice(2, 0, ‘HELLO’, ‘GOODBYE’). Here, you’d be adding the strings ‘HELLO‘, ‘GOODBYE‘ to the array starting at position # 2. But keep in mind that in this case, the Array.prototype.splice() method will return an empty array, because that method always returns an array. But if you do not remove any elements from the original array, then an empty array is returned.

Try it yourself !

In the above example, click the JavaScript tab. There we call the splice method on an array. In the first case, we take a very simple approach; the first argument is 0 and the second argument is 1: foo.splice(0, 1). This is similar to using the JavaScript shift() method, except that shift() returns the removed element, whereas the splice() method returns the removed element in an array.  This is a very simple example, but the main takeaway is: the first argument is the position to start at, and the second argument is the number of elements to remove.

Later in the examples, we pass no arguments to the splice method. In this case, no elements are removed from the original array and an empty array is removed.

Click the Result tab to see the output for all of the splice method examples.

Starting from the end of the array

In the last example, we provide a negative number for the first argument. A negative number tells the splice method that we want to “start at the end”.  For example:   foo.splice(-4, 3)  tells that splice method that we want to start at the fourth-to-last element in the array, and remove three elements.

Summary

Working with the beginning or the end of a JavaScript array is fairly straightforward, and to make matters even better, the Array.prototype’s push(), pop(), shift() and unshift() methods simplify the process. It’s when you want to remove or add elements to the middle of an array that things can get a bit more complex. Fortunately, though, the Array.prototype.splice() method provides a way to remove one or more elements from or add elements to the middle of a JavaScript array. But the key thing to remember is: this method always returns an array. So, if you are removing elements and you want to access any of the removed elements, you’ll need to iterate the returned array. But if you are adding elements only, then an empty array will be returned.

How do I fetch JSON data with jQuery?

jQuery

jquery-logo jQuery’s ajax method provides a way to make an HTTP request for JSON data and then handle the successful result.

Assuming that you have access to jQuery in your web page, fetching JSON data is very simple. The key to this is the jQuery.ajax method. This method takes an object as its first argument. In this object, you can, at minimum, specify url and success properties. The url property is the web address of the JSON data that you want to fetch. It should start with http:// or https://. If the resource is a relative path, then it could be virtually anything, for example: /data/json/customers. The success property is a method. That is, you assign a function to the success property. This function will receive the fetched JSON data as its first argument. Inside the function, you can process that data.

Try it yourself!

See the Pen jQuery AJAX – Basic Example by Kevin Chisholm (@kevinchisholm) on CodePen.

In the above example, we make a call to $.ajax. We pass an object to this method and that object has two properties. The url property has the web address of the JSON data that we want. Notice that this address ends with: ?sleep=2. This just means that for demonstration purposes, we can force the request to be delayed for two seconds. Go ahead and change that to ?sleep=5. You will see that the request then takes five seconds to complete. If you change it to ?sleep=0, then you will notice that the request completes very quickly. Either way, you can control this request and slow it down in order to see more clearly how things work.

The success property has an anonymous function assigned to it. This function will be executed once the $.ajax requests succeed. The function will take the fetched  data as its first argument. So, inside this function we use the JSONView jQuery plugin to inject the JSON data into the DOM.

Important note: we haven’t specified the HTTP verb that will be used for our request. For example, GET and POST are common HTTP verbs used for sending or receiving JSON data, but PUT and DELETE are fairly common as well. The jQuery.ajax method allows us to specify the HTTP verb that should be used for the request, and we specify this HTTP verb in the object that is passed to the jQuery.ajax method. Note that by default, the jQuery.ajax method will make a GET request, unless we specify a different verb, such as: type=”POST”, for example.

So, in the above example, we specified a success method.
It’s important to note, however, that we did not specify an error method. The reason for this was to make the example code easy to follow. However, it is highly recommended that you always provide an error handler when making any HTTP request. Keep in mind that while you may have full confidence in the requests you are making, HTTP transactions are fragile by nature, and in theory anything can happen. So, whatever you do, don’t overlook this small but important detail.

JavaScript Array.prototype.shift()

Array.prototype

shiftThe JavaScript shift method removes the first element from the array and returns that element.

While it may be tempting to use the Array.prototype.splice() method to remove an element from the beginning of a JavaScript array, believe me, Array.prototype.shift() is the best way to do it. And just as a side note, I’ve always felt that the method name “shift” is a little odd, but that’s what the ECMAScript specification calls for, so we’ll just move along with the good stuff.

So, with the Array.prototype.shift() method, it’s the syntax that’s really important, and the beauty of it is, it’s quite simple. You just chain .shift() onto your array variable name, without passing any arguments. For example: myArray.shift() would remove the first element from the beginning of the “myArray” array. Just keep in mind that the .shift() method returns the element that was removed from the beginning of the array. So, for example, if an array has five elements and the first one is the string “ABC”, calling the .shift() method will return “ABC”, because it has removed that element from the beginning of the array.

Try it yourself !

In the above example, we have the foo array, which has six elements. Each time we call the shift method, the first element of that array is removed. Notice that we show the return value of the shift method in the console. So, we can see that shift returns the element that was returned.

Click the Result tab. Notice how we call the shift method a total of three times. Each time, we show the return of that call to shift: “a”, “b”, and “c”. We also show the length of the foo array each time as well. That length decreases each time we call shift, so the values are 5, 4, and 3. And finally, each time we call shift, we use the console.dir method to inspect foo, so that we can see the changes that are happening to the array with each call to shift.

Video Example Code

If you want to download the example code, visit this page: kcv-array-shift-fiddle

Summary

So, to recap, the ECMAScript specification provides a number of methods on the Array.prototype object that are designed for handling mutations to the beginning and end of an array. But the Array.prototype.shift() method specifically functions to efficiently remove the first element from the beginning of an array. This method takes no arguments and returns the element that was removed from the beginning of the array. Simplicity and efficiency at its best!

How to combine JavaScript arrays

JavaScript

JavaScript logo - concatThe concat method can be used to combine two arrays. This method returns a new array and the original arrays are not changed in any way.

If you’ve never had a need to combine two JavaScript arrays, you can pretty much count on having to, one day. And if you’ve ever entertained thoughts of rolling your own solution to this problem, I’d recommend against it. So now’s a good time to talk about the array.prototype.concat method, which provides a simple way to combine two JavaScript arrays. One thing that’s important to know about the concat method is that it does not change the original arrays. In other words, a new array is created and it will consist of the two specified arrays. But keep in mind that if either array contains one or more objects, those objects are passed by reference in JavaScript. So, even though the original arrays are not changed, if you make a change to any of the objects in the new array, that change will be reflected in the original (source) array.

Try it yourself !

In the above example, click the Result tab. The first call to the concat method is used to combine two arrays: [“a”, “b”, “c”] and [“d”, “e”, “f”]. The result is a new array: [“a”,”b”,”c”,”d”,”e”,”f”]. It is important to note that in both cases, the original array is not changed, which you can see from the second and third console.dir statements. Click the Result tab in order to see the results of each console.dir statement.

We can also pass a single value to the concat method in this way:  myArray1.concat("hello") . When we do that, a new array is returned with the single value we have provided as the last element. The effect is very similar to using the Array push() method. The main difference is that the push() method changes the original array and returns the new length of that array, whereas the concat method does not change the original array and returns a new array . In a similar manner, we can also pass multiple values to the concat method:  myArray1.concat("hello", "goodbye") . This returns a new array with the two values added to the end: [“a”,”b”,”c”,”hello”,”goodbye”].

Summary

So, here you’ve had a look at what a handy tool the array.prototype.concat method is. It not only allows you to combine two JavaScript arrays, it also allows you to add elements to the new array at the same time. But here are two helpful and important things to keep in mind: the original arrays are not changed, and any changes to objects that exist in the new array will be reflected in the original array that it came from.

How do I move DOM elements with jQuery ?

jQuery

jquery-logo - appendToThe jQuery.appendTo method makes it easy to move a DOM element. You won’t need to be concerned with creating or destroying elements and event handlers are preserved.

Moving DOM elements using vanilla JavaScript can be a bit tedious. It’s certainly possible, and it is a good idea to understand the steps, but it does require more code. jQuery provides powerful abstraction for this task, however, and the amount of code needed is minimal.

Whenever possible, I favor using vanilla JavaScript to solve a problem, because leaning on jQuery too much can weaken your overall JavaScript skills. In this case, however, I recommend letting jQuery do all of the work for you. The main issue with vanilla JavaScript when it comes to moving DOM elements is the need to understand the intricacies of the low-level hierarchical DOM API. For example, you’ll need to get ahold of the parent element of the DOM node, after which you’ll want to move your target element. Frankly, I commend anyone who wants to take on this challenge, but in many cases, it just makes sense to leverage jQuery.

Try it yourself !

See the Pen Moving DOM elements with jQuery by Front End Video (@frontendvideo) on CodePen.

In the above example, click the “HTML” tab. There are two DIVs with the IDs: “left-list” and “right-list“. DIV#left-list has an unordered list with the days of the week, and DIV#right-list is empty. Now click the “JS” tab. You’ll see that there is a click-event handler for $('#left-list li'). This means that when any of the list items are clicked, the anonymous function you see will be executed.

Go ahead and click each of the days of the week and you’ll see that it is moved to the DIV#right-list element. After each element is moved, if you click it, nothing happens.

In the anonymous function, we use the JavaScript this keyword to reference the element that was clicked. Actually, we wrap the JavaScript this keyword with jQuery: $(this). We then chain the .appendTo method, and pass it a target element: .appendTo( $('#right-list') ). Here we are telling jQuery: “Move this element to the #right-list element, and make it the last child“. So, we are appending it to DIV#right-list. We then chain this: .unbind('click');. The reason we do that is: the jQuery appendTo method retains any event bindings for elements that are moved. Most of the time, this is probably what you want. But in this case, we do not want the event bindings to travel with the element because once a list item is moved inside of the #right-list element, we no longer want it to have a click-event handler. But that is simply for this example.

Summary

Simply put, moving DOM elements with vanilla JavaScript can be messy business, but the jQuery.appendTo method provides abstraction that simplifies this process. Instead of having to dig into the low-level DOM API, you can simply specify the source and target HTML elements. In other words, you let jQuery know which element you want to move, and which element you want to append it to. In cases such as these, it’s often best to let jQuery do all of the work for you. It will certainly minimize the amount of boilerplate coding you’ll have to do, and will help to keep your JavaScript easier to manage.

JavaScript Array.prototype.join()

Array.prototype

javascript joinThe JavaScript join method converts an array into a string.

Converting an array to a string in JavaScript may seem like an unlikely scenario at first, since they are dissimilar types, but this is not as uncommon as one might think. I’ve found that when I want to build a complex string, organizing the various parts of that string into array elements can be a helpful approach. For example: I have to build many vanilla JavaScript applications that feature custom CSS. The CSS is completely managed by the JavaScript code, but I ultimately inject a new STYLE element into the page, with the custom CSS as the content of that element. In building these custom styles, I organize each CSS rule into a string that is an element of an array. Then, after all of the custom CSS rules are created, I use the join() method to combine all of those array elements into one long string, and make that string the content of the STYLE element that is injected into the page.

At first glance, it may seem a bit odd to use a space, hyphen or forward slash as the separator, but as a developer, you are likely to find yourself in many situations in which the business requirements require you to solve unexpected problems. Converting a number of array elements to a string and separating each element with an odd character will be a challenge you will run into, so be prepared; if it has not happened yet, it will! Fortunately, the Array.prototype.join() provides an elegant solution to this problem.

If you pass no arguments to the JavaScript join method, then there will be no space between the characters of the string. Or, you can pass an argument that determines how to join the elements of the array. Which character(s) you provide is up to you. The most common practice is to use the default, which is a comma (” , “ ), but again, the choice is completely yours.

Try it yourself !

Click the JavaScript tab in the above example. We have an array with six elements: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]. When we call the join method on that array in the first console.log statement, it returns the string: “a,b,c,d,e,f”. This is the default behavior. That is to say: when you do not provide a separator argument, the characters in the returned string are separated by a comma  (” , “ ). In the following examples we do provide a separator argument. In each case, you will see that the separator is used to create the returned string.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-javascript-array-join-fiddle

Summary

String manipulation in JavaScript can be tedious, as converting an array to a string is a problem that might tempt one to use a for-loop as a solution. But the Array.prototype.join() method was specifically designed to solve this problem, as it negates the need for any kind of for-loop or other iteration patterns. You can simply chain the join() method from your array reference and then pass a character as an argument, which tells the join() method how you want to separate the elements of the array when converting to a string. In the long run, it really is a smooth way to go.

Introduction to the JavaScript Array reduce() method

Array.prototype

JavaScript LogoJavaScript’s Array reduce() method can be a bit confusing. It doesn’t “reduce” any of the array elements, in fact they are not changed. This method “reduces” the array to one value.

An array is essentially a list, and in JavaScript, that list can contain any valid value. Most array-specific tasks involve “doing something” with the array, or you may need to “do something” with every array element. But what if you need to convert the array into one value? In other words, if the array contains a list of values, what one value could represent all of those values? In this article, I’ll explain how the JavaScript Array reduce() method provides a way to solve this problem.

An important concept to think about is how you can translate a list of values into one, that represents all of them. In some languages, all arrays must be “typed”. In other words, every array element must be of the same type. In JavaScript, you’re not limited in this way; a JavaScript array can contain any number of numbers, strings, arrays or any other valid JS value type.

It’s true that Typescript can limit this kind of freedom, but you’re not required to use Typescript and ultimately, Typescript compiles down to JavaScript. So, the reality of dynamic arrays in JavaScript has not changed. Therefore, if you want to reduce all of the values in your array to one, it’s important to consider the type of each element. If all of the elements in your array are of the same type, things are fairly simple. If the types vary, however, that can get complicated. Of course, that discussion is beyond the scope of this article, but I just wanted to point it out.

Using a while-loop – Example # 1

See the Pen Array.prototype.reduce() – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

A “while” loop is a valid way to iterate a JavaScript array and that approach has worked for us here. We effectively “reduced” all of the elements of our array to the one value of 79, and we did this by adding each array element to the “getTotal” variable.

When I said that this approach “…has worked for us”, you may notice that I didn’t say that it “…worked well”. This is because the approach we took solved a problem, but created a couple of issues, the main one being boilerplate code. Most of the code in our “while” loop will be repeated if / when we need to solve the same problem elsewhere in our code. In addition to that, we have created an “i” variable to keep track of our counting during our “while” loop. It may seem innocent, but the more variables we create, the more variables we need to manage. Fewer variables is better.

Using the JavaScript Array reduce() method – Example # 2

See the Pen Array.prototype.reduce() – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

The Array reduce() method has dramatically simplified things in Example # 2. Notice how, in the getTotal the variable is now an anonymous function. In this function, we add the accumulator and currentValue arguments. Now you may be wondering: “What are the accumulator and currentValue arguments?” Well, take a look at the last line of code: milesPerDay.reduce(getTotal). What’s happening here is, we’re executing the .reduce() method of our “milesPerDay“, passing it the getTotal as an argument. This is the anonymous function that we detailed a few sentences ago.

So, the reduce method iterates the array and provides access to not only the currently iterated value (i.e. the current array element), but also the value that was returned by the previous execution of this function. This allows you to “accumulate” values across the array.

The arguments passed to the JavaScript Array reduce() method –
Example # 3

See the Pen Array.prototype.reduce() – Solution – 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 3 does not provide any additional value with respect to solving the problem; the solution from Example # 2 is solid. The purpose of Example # 3 is to offer more detail about the arguments that are passed to the function provided to the Array reduce() method.

As demonstrated in the UI, the first argument is the accumulated value that’s being created as you iterate the array (i.e. the value returned by the last execution of this same function). The second argument, “currentValue”, is the value of the current array element. In the third, the index of the current array element is provided, and in the last, we see the array over which you are iterating.

I decided to show the value of the “array” argument to demonstrate that the Array reduce() method does not itself make any changes to the original. You can do that within the function passed to the Array reduce() method, but reduce() itself does not make any such changes. What you choose to do with these arguments is up to you, but just know that they’re helpful in building the logic you need to reduce your array to one final value.

Introduction to the JavaScript Array map() method

Array.prototype

JavaScript LogoJavaScript’s array map() method allows you to “do something” with each element of an array. This has always been possible, but the map() method’s syntax is simple and elegant.

When you have an array, you’ll eventually want to “do something” with it. You may, for example, want to do something with the entire array, such as showing all of its elements in the UI. But what about when you want to “do something” with each element in that array? This poses a bit more of a challenge.

First, you’ll need to iterate the array, which requires some kind of loop. Second, you’ll need to keep track of your iteration process, which requires a counter variable (which requires you to control that variable’s scope). This may seem like no big deal, but it’s work and each time you want to solve the same problem, you’re writing code that’s virtually identical, but not entirely the same, so you start to copy and paste.

This kind of repetitive boilerplate code is tedious, it must be managed, and as repeated code, it becomes a red flag. So, since this kind of coding presents unnecessary problems, what we’ll cover in this article, is how the JavaScript Array map() method solves these issues.

Using a for-loop – Example # 1

See the Pen Array.prototype.map – Challenge – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Our first pass at this solution employs a for-loop. As mentioned above, this introduces a few problems. We have the “i” variable, for instance, which in this example is a global. In a real-world situation, however, we would want to put this code in a function so that the “i” variable does not wind up in the global scope. Also, the code in our for-loop is tedious. We need to use the “i” variable to keep track of the currently iterated rawNumbers element. There’s definitely a better way to go about this.

Using the Array map() method – Example # 2

See the Pen JavaScript Array.prototype.find() – Solution 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 2, we use the JavaScript Array map() method to solve the problems discussed. We’ve passed an anonymous function to that method, and this anonymous function takes the currently iterated number as its first argument. Inside of our function, we have some simple code that rounds the currently iterated number.

The biggest benefit to using the JavaScript Array map() method is that we no longer have the “i” variable or the for-loop. This is already a major improvement, especially the reduction of code, since it means that it’s simpler and easier to read. These are not minor details, and if this is a task that occurs multiple times in your application, you’ll soon find that the benefit gained by reducing repetitive code will quickly become significant.

Passing a function to the Array map() method – Example # 3

See the Pen Array.prototype.map – Solution – 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

The approach in Example # 3 is similar, but there’s one big difference: instead of passing an anonymous function to the Array map() method, we pass to the Math.round method, which makes our code even easier to read. This is largely because we leave the implementation details to Math.round and eliminate even more code: our anonymous callback function. There are two reasons that we can do this: Math.round takes a number to round as its first argument, just like our anonymous function, and it returns the rounded number, just like our anonymous function. Simplified code is better code and in this case, we have Math.round to thank for that.

JavaScript Template Literals – Basics

JavaScript

JavaScript LogoTemplate Literals introduce a new syntax into JavaScript. The backtick character provides a way to have placeholders as well as multi-line text without special characters.

Working with strings is a daily activity for most JavaScript developers. One of the most common challenges is dealing with multi-line text. This is not an unsolvable problem, but it can certainly be painful. In this article, I’ll demonstrate how Template Literals can be used to make working with multi-line text much easier. Also, I’ll demonstrate how to use placeholders with Template Literals.

Double and single quotation marks are the way that we have always worked with strings in JavaScript. Either approach works fine; you just need to be mindful of some restrictions. For example, with valid JSON, all properties must be in double quotes. Also, backslashes must be used to escape double and single quotes, depending on which one is in use. But now we have Template Literals, which introduce a new character: the backtick. When using the backtick, you can include line breaks in your text and they will be respected when your text is rendered. You can also use the newline character: “\n”. When using the newline character, you can “programmatically” insert a new line in your text without literally doing so.

Using HTML to create new lines – Example # 1

See the Pen YeYmNb by Kevin Chisholm (@kevinchisholm) on CodePen.

For Example # 1, we’ve taken the “old school” approach: we have created text using single quotes, and used the BR HTML element to create new lines in our text. When you look at the UI for Example # 1, you see that the new lines were created just as expected. We also use string concatenation to combine the “firstPart“, “endpart” and “author” variables. This is all fine, and I can say I’ve employed this approach thousands of times. The drawback with this, however, is the need to use the BR HTML element to create new lines in our text. It works as long as we actually render the HTML in our browser, but what about a situation in which the text will be rendered in a non-browser context?

Using Template Literals – Example # 2

See the Pen JavaScript Template literals – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

Well, you’ll notice a dramatic difference in how we do things in Example # 2. Here, we’ve used Template Literals — specifically, the backtick character, to create our string. In doing so, we were able to include line breaks simply by literally using new lines in our text. You may have noticed that I’ve used a textarea HTML element to display the text, because, if I were to use a paragraph element, you wouldn’t see the line breaks. And this is because the paragraph element would simply render all of the text inside of itself. But by using a textarea HTML element, we can see that the line breaks have been preserved.

Now in Example # 2 you’ll see that there’s another new concept in play: the placeholder. On Line # 21, we create the “allText” variable, which contains the combined text contained in the “firstPart“, “endpart” and “author” variables. But instead of using string concatenation (as we did in the previous example), we use placeholders. The placeholder syntax is simple: you use a dollar sign and curly braces. Inside the curly braces, you can insert any valid JavaScript expression, which will be evaluated. In our example, we use this placeholder syntax to combine the “firstPart“, “endpart” and “author” variables.

Using the New Line Character – Example # 3

See the Pen JavaScript Template literals – Solution 2 by Kevin Chisholm (@kevinchisholm) on CodePen.

Example # 3 is identical to the previous one, with one exception: we use the newline character instead of literal new lines. The output here is exactly the same, but the method for creating the string is different. This is not necessarily a “better” or “more correct” way of doing things; it’s simply an alternative way to create new lines in your string literal. The advantage here, of course, is that the new lines are created programmatically. For example, if you had a function that generated this string, based on some dynamic logic, you might want to include a single line break or double line break, depending on the logic. The newline character makes this kind of task much easier.

JavaScript Object Literal Shorthand Syntax Basics

JavaScript

JavaScript object literal shorthand syntaxJavaScript Object Literal Shorthand Syntax is a feature that provides a path to cleanerJavaScript. Not only does it provide a way to reduce the size of your code, but it will be easier to read and understand.

Many ECMAScript 2015 features provide improved ways to solve problems. Object literal shorthand syntax is a bit unique in that it’s not so much a shiny new tool, but an improved syntax. Now it might be tempting to dismiss this kind of feature as less-than-stellar, but it’s worth working into your routine for a number of reasons. For example, an improved syntax can lead to less code, and not only that, the code you write can be easier to understand. And believe me, those who inherit your code will thank you for this. So, in this article, I’ll explain how to use object literal shorthand syntax when defining properties and methods.

Typical Object Literal Syntax – Example # 1

See the Pen JavaScript Object Literal Shorthand Syntax – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

Let’s start with the way we’re used to working with object literals. In Example # 1 we have a getGoods() method that returns an object. The value argument is used on execution to set the value property, and the lowerValue() and raiseValue() methods lower and raise that value property. So this is all fine and everything works exactly as expected. In fact, if you look at the UI, the text that you see shows that our methods set and value property accordingly. Unlike many of the examples in this blog, there is nothing to “fix” here. Our code works fine and follows a typical syntax pattern because, as stated, I mainly wanted to establish that this is the way we normally work with object literals.

Object Literal Shorthand Syntax -Example # 2

See the Pen JavaScript Object Literal Shorthand Syntax – Solution by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, in Example # 2 we do things quite differently. To start, look at Line # 3. When we set the value property, there is no colon; we simply assign the value of the “value” argument that was provided when the function was executed. This syntax is concise, thereby requiring you to write less code. Now it may seem like a very small savings here, but when you have an application with many thousands of lines of code, the savings quickly add up.

Okay, so next, look at where we define the lowerValue() and raiseValue() methods. Here, notice two things are missing: there is no colon, and we don’t need the function keyword. We simply provide the parentheses and the curly braces (as well as the code inside the curly braces). Here, too, the savings may seem small on a per-line basis, but in a large application, the difference will be dramatic. And the additional benefit, especially when defining methods, is that the code is a bit easier to read.

Introduction to JavaScript Default Parameters

JavaScript

JavaScript default parametersJavaScript functions can take arguments, but they are optional by nature. Default parameter syntax makes it easy to determine if one or more arguments have been provided and if not, initialize them.

While something like Typescript can make it easier to enforce certain practices, use is voluntary. Ultimately, you can’t force a consumer to provide one or more arguments to your function. There are ways to work around this problem, but solutions are not simple. As is often the case, for example, solutions sometimes introduce new problems. There’s good news on this front, though, and in this article, I will demonstrate the JavaScript default parameter syntax and how it solves the above-mentioned problem.

The JavaScript default parameter syntax is surprisingly simple; instead of specifying an argument in the parentheses, you initialize it. This may look a bit deceiving, and, in fact, some may think that by doing this you are absolutely setting that value. But quite the contrary: what you are saying is: “If argument X is not provided, then initialize it and set it equal to this value.” So, you’re providing a “default” value for that argument, and if that argument is provided when the function is executed, then the provided value is used.

Example # 1

See the Pen JavaScript Default Parameters – Challenge by Kevin Chisholm (@kevinchisholm) on CodePen.

In Example # 1, the addBonus() function takes one argument: “bonus.” In that function, we had to write code that checks to see if the “bonus” argument was provided. If it was, then we use the provided value. Now, this code works just fine, but there’s a problem. If we accept this solution, that means that we’ll write code that is virtually identical to it any place else in our application where the same problem needs to be solved. So, of course, it’s worth remembering here that any time we have repeated code, we know that there’s a better way to solve a problem.

Example # 2

See the Pen JavaScript Default Parameters – Solution 1 by Kevin Chisholm (@kevinchisholm) on CodePen.

Now, when you take a look at the approach in Example # 2, you’ll see an immediate improvement. We’ve leveraged default parameter syntax so that the “bonus” argument is now optional, thereby creating the biggest advantage of this approach, which is that there is no longer any repeated code. By simply initializing the “bonus” argument, we ensure that if not provided, that variable will have a value.

Understanding the difference between scope and context in a JavaScript method

JavaScript

scope and contextSometimes the concepts of scope and context are misunderstood in JavaScript. It is important to understand that they are not the same thing. This is particularly important inside of a method.

In JavaScript, the concept of scope refers to the visibility of variables. On the other hand, the concept of context is used to mean: “the object to which a method belongs”. That may sound like an odd statement, but it is accurate. The only time we care about context is inside a function. Period. Inside a function, the “this” keyword is very important. It refers to the object to which that function belongs. In other words, every function is a property of some object. In client-side JavaScript (i.e. in a browser), if you declare a function at the top of your code, then that function is a property of the window object. So, inside of that function, the “this” keyword refers to the window object. If you create a new object (let’s call it: “myObject”) and add a method (i.e. a property that happens to be a function), then inside of that function, the “this” keyword refers to the object (i.e. “myObject”).

So the main issue is that inside of a method, object properties and variables can sometimes be confused. In short; when the JavaScript “var” keyword is used, that is a variable. A variable will not be a property of an object (except in the global scope, which is for another discussion). But inside a method, any variable created using the JavaScript “var” keyword will be private to that method. So this means that it is not possible to access that variable from outside the method. But inside of a method, you have access to all of the properties of the object to which that method belongs. And you access these properties using the JavaScript “this” keyword. So, for example; if myObject.greeting = “Hello” and myObject.greet is a method, then inside myObject.greet, if I reference this.greeting, I should get the string: “Hello”. And if I have declared a variable named “speed” inside of myObject.greet, I would access it simply by referring to “speed” (i.e. I would not use the JavaScript “this” keyword). Also, a big difference between variables and properties in a method is that properties are always public. That is to say: all object properties can be seen and in most cases modified. But a private variable inside of a method is completely hidden from the outside world. And only our code inside of the method has access to that variable.

Try it yourself !

In above example, we start out by creating a property on the window object named: “foo”. This “foo” object is the result of an immediately invoked function expression (aka: “IIFE“). The reason that we take this approach is so that we can have a private variable: count. Our getCount method as access to that private count variable.

There is also a count property on the “foo” object. This property is available publicly. That is to say: we are able to make changes to the count property, whereas the count variable is not available outside of the IIFE. Our getCount method has access to the count variable, but that is the only way we can reach it.

When we call foo.getCount() without passing any arguments, then it increments the count property and returns it. This is CONTEXT. By using the JavaScript “this” keyword inside of the getCount method, we are leveraging the concept of context. Conversely, when we call foo.getCount(“scope”), then the count variable is incremented and returned. This is SCOPE. It is very important to understand the difference between scope and context in JavaScript.

JavaScript Spread Syntax – Basics

JavaScript

JavaScript Logo - spread syntaxJavaScript spread syntax provides a way to convert an array into a comma-separated list.

In this article, I will cover the basics of JavaScript spread syntax. But first, let’s start by taking a step back and thinking about how functions work in JavaScript. A function expects a comma-separated list of arguments, so, when we call a function, we need to provide zero, one or more arguments, separated by a comma. But what happens when we don’t know exactly what all of these arguments are? Now it may be tempting to simply pass an array, but then this array would be seen by the called argument as simply the first argument. In other words, argument[0] in the function would be an array. But this is not what we want; we want to pass an array to a function and for that array to be interpreted by the function as a comma-separated list of arguments.

Why is JavaScript Spread Syntax So Helpful?

So here’s where the spread syntax comes in: it allows us to put the arguments in an array, and then pass that array to the function we are calling. And, actually, this is only one example of how the JavaScript spread syntax can be helpful, but it certainly is a great way to start the conversation.

Inspect Arguments in a Function – Example # 1 A

The Output from the inspectArguments function – Example # 1 B

Inside every JavaScript function, the “arguments” keyword provides a reference to all arguments that were passed into this execution of the function. The “arguments” keyword is not an array, but an array-like object with a “length” property. Fortunately, however, this “length” property allows us to iterate the “arguments” object as if it were an array. The “inspectArguments” function from Example # 1 A contains a for-loop, which iterates over all the arguments it receives. Inside of that for-loop, we output the value of each argument.

Nothing too special there.

On the last line of Example # 1 A, we call the “inspectArguments” function, passing it: “…letters”. What’s happening here is that instead of passing the letters array, we pass “…letters”, which spreads the letters array out into a comma-separated list. Example # 1 B contains the output from Example # 1 A, and as expected, we see the contents of the letters array.

Spreading Out the Arguments – Example # 2 A

The Output Has Changed – Example # 2 B

Example # 2 A is similar to Example # 1 A, except in the way that we call the “inspectArguments” function. In other words, instead of passing just “…letters”, we pass “x, y, …letters”. This allows us to specify that the first two arguments that the “inspectArguments” function receives are “x” and “y” and the rest of the arguments is the content of the letters array. The point here is that we can mix the use of literals and the spread syntax. So as expected, Example # 2 B shows the output, which is similar to Example # 1 B, except that “x” and “y” are the first two console.log statements.

Using Spread Syntax for Both Arguments – Example # 3 A

The Output – Example # 3 B

Now, in Example # 3 A, we take things a little further. We use the spread syntax twice, which calls the “inspectArguments” function, passing the contents of both the days and letters arrays, spread out into one comma-separated list. Consequently, the output that you see in Example # 3 B is exactly as expected: the contents of the days and letters arrays.

JavaScript – For-In vs For-Of

JavaScript

JavaScript Logofor-in and for-of both provide a way to iterate over an object or array. The difference between them is: for-in provides access to the object keys ,
whereas the for-of operator provides access to the values of those keys.

Iterating over an object or array is a pretty routine task with JavaScript, in fact, it’s hard to imagine a day when you don’t’ need to perform this action. When Iterating over an array, things are a bit easier because you can leverage the array’s “length” property to set up your iteration. But when you need to iterate over the properties of an object, things get a little sticky.

Why For-In vs For-Of

In his article, I will demonstrate the difference between the for-in and for-of JavaScript operators. Now, while these two methods may seem to provide the same functionality, actually, they do not. In fact, you might say that they are polar opposites. The for-in operator returns the keys of an object of array, whereas the for-of operator provides access to the values of these keys.

For a better understanding, let’s take a look at some examples.

for-in – Example # 1

In Example # 1, we use a for-in loop to iterate over the elements of the days array. Now, since we are creating the variable: “day in days”, on each iteration of the loop, we have access to a day variable, which represents the element over which we are currently iterating. The output for this example can be seen in line #s 8-15, and the purpose of this example is to demonstrate that the for-in operator provides the keys of an object, not the values of those keys. It is possible to get ahold of these values, which we will see in a moment, but, for now, I just wanted to point out that for-in provides direct access to the keys of the object over which we are iterating.

Using Bracket Notation – Example # 2

Example # 2 is virtually identical to Example # 1, in that we leverage almost the exact same code to iterate over the days array. The difference here is that we manage to get ahold of the key values by using bracket-notation. So, instead of outputting console.log(day), we output console.log(days[day]). In a pseudocode kind of way, we are saying: “give me the value of the days property that had this key”. The output for this example can be seen in line #s 10-14, and it is exactly what we wanted: we see the value for each key. This does feel a little hackey though, so let’s see if we can do better than this.

for-of – Example # 3

In Example # 3, we’re able to achieve our goal by leveraging the for-of operator. Simply by using for-of (instead of for-in), we’re able to access the value of each key. So, not only is this a non-hackey way to approach this problem, it is also cleaner and easier to read.

JavaScript Rest Parameter – Basics

JavaScript

JavaScript LogoThe Rest Parameter allows you to do two things: (1) break out the first X arguments passed-into the function, and (2) put “the rest” of the arguments into an array.

Passing arguments to a JavaScript function is quite common. If a function expects one or more arguments, then it follows that inside of that function you’ll want to examine the incoming arguments. But things can get problematic when you’re not entirely sure exactly what the incoming arguments will be at design time. Now it’s true that inside of any function you have a local variable named “arguments” that is an array-like object, but there are two problems with this array-like “arguments” object.

First of all, it’s not an array, and while you can leverage the Array.prototype object in order to treat the “arguments” object as if it is a true array, that approach feels like a hack. Secondly, if you want to act upon the incoming arguments differently, based on their position, things can get messy. Now this is where the JavaScript Rest Parameter comes in – it’s a powerful tool that can help solve these problems.

Why Should I Care About the JavaScript Rest Parameter?

In this article, I will cover the basics of the JavaScript rest parameter. I’ll walk through the ways in which it can be used to collect the incoming arguments of a function and convert them into a true JavaScript array. I’ll also demonstrate how you can use the JavaScript rest parameter to break out the incoming arguments so that one or more of the initial arguments can be left as is, and then “the rest” of them can be put into an array.

Using the Rest Parameter – Example # 1 A

inspectArgs Output – Example # 1 B

Above we’ve created a function named “inspectArgs”, which we’ll use in the rest of the code examples for this article. In Example # 1 A, we use the JavaScript rest parameter to collect all of the arguments that are passed into the function, we and put them into an array. So, on line # 2, since theArgs translates to an array, we can use the forEach method of the “theArgs” variable to iterate that array. Inside of the anonymous callback function that we pass to the forEach method, we have access to each array element, as well as the index of that element. Now using this information, we output the value of each argument, and the index of that argument.

So, the key point here is that by placing “…theArgs” where the incoming arguments would normally go, we are saying: “take all of the arguments that are passed-into this function, put them into an array, and create a local variable for this function named theArgs”. And in Example # 1 B, you can see the output of Example # 1 A, which is exactly what we expect: the value of each argument that was passed to the inspectArgs function.

When you actually want “the rest” of the arguments – Example # 2 A

We See the First Argument, and “the rest” of them- Example # 2 B

Now, in Example # 2A, we made one small change, in order to really demonstrate the power of the JavaScript rest parameter. We changed “…theArgs” to “x, …theArgs” where the incoming arguments would normally go. So, what we are saying to the JavaScript engine here is: “let the first argument be what it is, but then take the rest of the incoming arguments and put them into an array”. So, before we use the “theArgs.forEach” method to iterate the “theArgs” variable, we take a look at the very first argument: “X” and output it.

Now if we take a look at Example # 2 B, we see the output of Example # 2 A. As expected, we see “x -> a” first, because we examined the first argument. Then we see the “rest” of the arguments, because we used the rest parameter to iterate the “rest of” the arguments that were passed into the function.

Skipping Arguments – Example # 3 A

The Second Argument Has Been Skipped – Example # 3 B


In Example # 3 A, we take an approach that’s very similar to that of Example # 2 A, by examining the first argument and outputting it to the console. But when you look at Example # 3 B, the output of this call to inspectArgs skips the second argument: “b”. This is because we specify: “x, y, …theArgs” where the incoming arguments would normally go. So now what we are saying to the JavaScript engine here is: “let the first and second arguments be what they are, but then take the rest of the incoming arguments and put them into an array”. As a result, we wind up with three local variables in this function: “a” “b” and “theArgs”. We output the value of “a” and “theArgs”, but we ignored “b”. The main point here is that we have changed the value of “theArgs” simply by specifying a “b” argument. So, as you can see, Example # 3 A truly demonstrates the power of the JavaScript Rest Parameter.

mapbox-gl Uncaught ReferenceError: t is not defined

Mapbox

JavaScript LogoMy Mapbox integration was working fine locally. But then when did a Webpack build and pushed the assets to my web server, there was a JavaScript console error

I was implementing Mapbox in an Angular 4 application and everything was going fine. I was working locally, but after getting some UI issues worked out, things seemed to be going very smoothly. But when I ran my build and then viewed the static assets remotely, I had this lovely little JavaScript error in my console: “Uncaught ReferenceError: t is not defined“.

Hmmmm. everything seemed just fine to me. I did some troubleshooting and the issue looked like it was being caused by Mapbox. How could this be? It was not a problem locally.

I found the answer here: Build fails when using mapbox-gl webpack 2 and UglifyJSPlugin #4359.

Credit really goes to zezhipeng  – whose answer was spot-on. Seems that when Webpack parses the mapbox-gl module, things do not go too well. So I just needed to add this line to my Webpack config:

(the “” is just whatever else you have in your module.exports.module object.)

And that was it, working again. Thanks zezhipeng!

What is the difference between LET and CONST in JavaScript?

JavaScript

JavaScript LogoThe JavaScript let and const keywords provide block-level scope, but there is a slight difference in how they behave. With const, you can not re-assign a value to the variable. With let,
you can.

Over time, JavaScript applications have grown in complexity. As a result of the increased code complexity programmers have been faced with a challenging dilemma: build applications that satisfy ever-evolving business requirements, yet continue to work with the same tools. It only makes sense that JavaScript would be in need of improvements, since for much of its history, functions were the only tools available to achieve scope. But, for several years, block-level scope was a feature that was sorely lacking. Then along came the ECMAScript-2015 specification that finally met that need with the let and const keywords.

The JavaScript let and const keywords are quite similar, in that they create block-level scope. However, they do differ a bit in the way that they behave. For example, the JavaScript let keyword is similar to the var keyword in that assignments can be changed. On the other hand, the JavaScript const keyword differs in that assignments can not be changed. So, once you declare a variable using the const keyword, you cannot re-assign a value to that variable. This does not mean that the variable is immutable. If you assign an object to a variable using the const keyword, you can mutate that object. You just can’t re-assign that variable with a new value. Let’s take a look at some examples.

Example # 1 A

Example # 1 B

In Example # 1 A, we have two different versions of the “i” variable. I say “two different versions” because the same variable name exists in two difference scopes, the global scope and a block scope. The block scope exists between the two curly braces: “{ }”. Then inside of the two curly braces, I used the JavaScript let keyword to declare a second “i” variable. Because we used the let keyword, that particular “i” variable is scoped to the block in which it was declared. And because of this, the console.log() statement on line # 6 outputs  50. I’ll just note here that it may seem a little odd at first to declare a variable anywhere other than at the top of the function, but this actually is the correct syntax; if we want a block-level scope variable, we use the let keyword inside of a set of curly braces.

Take a look at Example # 1 B. Notice how, in the second console.log() statement, the output is 100. This is because that second console.log() statement is in the global scope, and in that scope the “i” variable is equal to 100. So, there we have it: two different scopes without even having used a function.

Example # 2 A

Example # 2 B

Now, in Example # 2 A, there are two “j” variables.
The first “j” variable is a global, equal to 100, and the second is defined inside of the for loop. And because it’s defined inside of a block, it has block-level scope. Now look at example # 2 B. Because “i” is global, the “i” variable increments, just as we would expect. But notice that the “j” variable is always 50 in each console.log() statement, even though there is a global “j” variable. This is because on each iteration of the for loop, a block-level “j” variable is declared using the let keyword, and it is incremented (just to demonstrate that with let, we can re-assign a variable value). So in this case, with each iteration of the for loop we have a block-scoped “j” variable and it is always 51. Note that the global “j” variable is ignored on line # 12.

Example # 3 A

Example # 3 B

In Examples # 3 A and # 3 B you’ll see a similarity to Examples # 1 A and # 1 B, the only difference being the use of the use of the const keyword instead of let when declaring our block-level version of the “i” variable.

Example # 4 A

Example # 4 B

Now here in Example # 4 A, we’ve run into a problem. We tried to take the same approach as Example # 2 A, that is, we tried to increment the “j” variable declared on line # 6. The problem, though, is that when you use the JavaScript const keyword, you cannot re-assign a new value to a variable. So when you look at Example # 4 B, you’ll see that we never see the full output of the for loop that we expected, because line # 9 of Example # 4A throws a TypeError. This is because when we try to change the value of “j”, we find that this is not possible because it was created using the const keyword. In other words: it’s a constant.

Example # 5 A

Example # 5 B

Now Example # 5 A is virtually identical to Example # 4 A, except that we have not tried to increment the “j” variable. And when you look at Example # 5 B, you’ll see that we no longer have an error. In the console, the value of “j” is 50 every time.

Summary

So to recap, we now know that the JavaScript let and const keywords allow you to create block-level scope for variables, which, in turn, negates the need to always use functions to create scope. With block-level scope, all you need are the curly braces “{ }”, and within that block, any variable created using let or const is private (or local) to that block. This is particularly helpful with for-loops. And a very important thing to keep in mind: with const, you cannot re-assign values to a variable. In other words, any variable created with the const keyword is a constant and the assignment cannot be changed.

A lot to take in here, but I think it’s worth keeping on your radar, given this very functional block-level scope now increasingly available in browsers.