7 JavaScript language elements every developer needs

By Matthew Tyson

Research suggests there are seven JavaScript language elements developers lookup more than any other. While you might not be able to write a complete JavaScript program using only these features, you most certainly won't get far without them. Beginners need to learn them, but they're also great brain refreshers for JavaScript veterans. Let’s take a look at the JavaScript language features every developer needs.

The 'most searched' JavaScript language elements

array: Storing collections

Collections of values are an essential aspect of all programming languages. In JavaScript, we use arrays to store collections. JavaScript arrays are incredibly flexible, which is largely due to JavaScript’s dynamic typing system. You can declare an empty array or one that already holds values:

// make a new empty array:const myArray = [];//add a value:myArray.push("Happy New Year");console.log(myArray[0]); // outputs “Happy New Year”// make an array with values:const myOtherArray = [0, "test", true];

Like most languages, arrays in JavaScript are “base 0” meaning the first element has an index of 0 rather than 1. You can also see that myOtherArray can hold a diversity of types: numbers, strings, and booleans.

for: The classic loop

The for loop is a fundamental component of all programming languages but JavaScript's version has some peculiarities. The basic syntax of the for loop is:

for (let i = 0; i < 10; i++){ console.log("i is going up: "+ i);}

This code says: Give me a variable named i, and so long as it is less than 10, do what is indicated inside the braces. Every time you do, add 1 to i. This is a common loop variable, where "i" is short for "iterator."

This form of for in JavaScript is typical of many languages. It’s a declarative type of loop. This form is very flexible, as each part can have many variations:

// This will loop forever, unless something else changes i, because i is not modified by the loopfor (let i = 0; i < 10;){ console.log("i is going up: "+ i);}// you can declare multiple variables, tests and modifiers at oncefor (let i = 0, j = 10; i * j < 80 && i < 10; i++, j=j+5){ console.log(i * j); // outputs 0, 15, 40, 75 and breaks}

It can be helpful, especially when dealing with complex nested loops, to declare more descriptive iterators like userIterator or productCounter.

There’s also a for-in loop in JavaScript, useful for looping over JSON objects:

let myObject = { foo: "bar", test: 1000 }for (let x in myObject) { for (let x in myObject) { console.log(x + "=" + myObject[x]) } }// outputs: foo=bar test=1000

You can also use for-in on arrays:

let arr = [5, 10, 15, 20];for (let x in arr2) { console.log(x + "=" + arr2[x]);}// outputs: 0=5, 1=10, 2=15, 3=20

In objects, the iterator (x) becomes the name of the property. In the array, it becomes the index. This can then be used to access the object or array properties and elements.

forEach: The functional loop

Modern JavaScript embraces functional programming, and the forEach function is an excellent example of that. The forEach loop is a simple, functional way to iterate over collections: it keeps all the logic tight—no declaring extraneous iterator variables like you would with for.

Here, you can see the simplicity of forEach:

arr.forEach((x) => { console.log (x) })// outputs: 5, 10, 15, 20

We've passed in a function to forEach, defining an inline anonymous function using the arrow syntax. Doing this is very common. (We could also declare a named function and pass it in.)

You’ll notice that in forEach, the variable exposed, in our case x, is actually given the value of the element, not the index.

There's another simple way to get an iterator, which has the same behavior:

arr.forEach((x, i) => { console.log (i + "=" + x) })// outputs 0=5, 1=10, 2=15, 3=20

You’ll also see the simplified arrow syntax with forEach (which has the same behavior):

arr2.forEach(x => console.log(x))

This syntax automatically returns, but forEach doesn’t require a return value.

Many developers prefer forEach to the traditional for loop. In general, use whatever loop syntax makes your code most clear and easiest for you to understand. (That’ll make it easy for other developers to understand, too.)

map: The functional modifier

While forEach simply loops over each element, the map function allows you to loop on the array and perform actions on each element. The map function returns a new collection with the action applied to each element.

Let’s say we wanted to take our array and multiply each element by 10:

let modifiedArr = arr.map((x) => { return x * 10 } )// modifiedArray now holds: [50, 100, 150, 200]

You can also use the short form:

let modifiedArr = arr.map(x => x * 100 )// modifiedArray now holds: [500, 1000, 1500, 2000]

Using the long form, you can perform arbitrary logic inside the callback:

let modifiedArr = arr.map((x) => { let foo = 1000; // Do more stuff return x * foo; })

As the callback(s) become more elaborate, map's simplicity declines. That is to say: prefer simple callbacks whenever possible.

reduce: Turning collections into a single value

Alongside map, reduce is a functional part of JavaScript. It lets you take a collection and get back a single value. Anytime you need to perform an operation across an array that “reduces” it to a single value, you can use reduce:

const numbers = [1, 2, 3, 4];const sum = numbers.reduce((accumulator, number) => accumulator + number);console.log(sum); // Output: 10

The reduce takes a two-argument function, where the first argument is the accumulator—a variable that will live across all iterations, ultimately becoming the output of the reduce call. The second argument (number) is the value of the element for the iteration.

You can use reduce to specify a starting value by setting a second argument after the callback function:

// With initial value of 10const sum2 = numbers.reduce((accumulator, number) => accumulator + number, 10);console.log(sum2); // Output: 20 (10 + 1 + 2 + 3 + 4)

This is also helpful when the collection might be empty. In that case, the second argument acts as a default value.

substring

String.substring is a method on string objects that lets you get a portion of the string:

// Let’s get the substring of this Emerson quote:let myString = "Enthusiasm is the mother of effort, and without it nothing great was ever achieved."console.log(myString.substring(0,34));// outputs: 'Enthusiasm is the mother of effort'

switch

A switch is a common language feature that handles branching control flow. Developers use switch to handle branches in a more compact and understandable way than if/else when there are many options. Over the years, JavaScript’s switch statement has grown more powerful. The basic syntax of a switch is:

switch (word) { case "Enthusiasm": console.log("This word is about passion and excitement."); break; case "mother": console.log("This word is about the source or origin."); break; case "effort": console.log("This word is about hard work and dedication."); break; default: console.log("I don't have specific analysis for this word."); }

The switch keyword accepts a variable, which in this case is word. Each case statement corresponds to a possible value of the switch variable. Notice we have to use the break statement to end the case block. This is different from many constructs where braces are used to define scope. If a break statement is omitted, the code will “fall through” to the next case statement.

The default statement gives us the case that will execute if nothing else matches. This is optional.

Here’s how we could use this switch statement with our Emerson quote:

let myString = "Enthusiasm is the mother of effort, and without it nothing great was ever achieved." function analyzeWord(word) { switch (word) { case "Enthusiasm": console.log("This word is about passion and excitement."); break; case "mother": console.log("This word is about the source or origin."); break; case "effort": console.log("This word is about hard work and dedication."); break; default: console.log("I don't have specific analysis for this word."); }}myString.split(" ").forEach((word) => analyzeWord(word));

This example brings together several elements. We split the string into substrings with split(“ “), then iterate on each word using forEach, passing the word to our switch statement wrapped in a function. If you run this code, it’ll output a description for each known word and the default for the others.

Conclusion

We’ve toured some of the most useful and looked-up JavaScript fundamentals. Each of these is an essential part of your JavaScript toolkit.

© Info World