Javascript

JS Basics: Functions and Syntax

A short intro to the core fundamentals of Javascript for front-end web development

Javascript (JS), oftentimes referred to as “Vanilla JS,” is used to added functionality to a web page (e.g. “do this when a user clicks this”). For many beginner web designers, JS can be daunting to learn. Many find JQuery to be much simpler and easier to use, learn, and implement. Knowing that JQuery is a JavaScript library that is based on JavaScript (that comes at the cost of adding it as a required dependency on page load), it makes sense to learn the source language first: JavaScript. Once you understand the basics of Vanilla JS, such as how to write a simple function, then the possibilities become endless. For example, if you can write a simple function that adds and removes a class on an HTML element (DOM manipulation) when a user clicks on something, then you can then manage the UX and control your UI via the HTML and CSS. This core front-end web development skill will enable you to do many, many, many things.

Alongside HTML and CSS, JavaScript is one of the three core technologies of World Wide Web content production.
Wikipedia

The Anatomy of a JS Function

The Syntax for a Function Definition:

function myFunctionName(optionalArguments) {
    var myVariableName = value;
    console.log(myVariableName); 
} 

The Syntax for a Function Call:

functionName();

Using JS to Manipulate the DOM

Using Vanilla Javascript, there are multiple ways to target elements via the DOM (Document Object Model). One of the simplest ways to target a single, unique element (class or id) is to use document.getElementById():

    document.getElementById('mydiv')

If you do not need to support older browsers, you can use querySelector or querySelectorAll, which will work with both id’s and classes:

    document.querySelector('#mydiv')
    document.querySelectorAll('.myclass')

Note: if there are multiple instances, such as multiple elements with the same class name, querySelector will only work on the first instance. If you need to target multiple instances of a class, then use querySelectorAll.

Linking to an external JS File

A recommended way to use JavaScript is to link to it in a separate file via a script tag. Just like HTML and CSS, JS has the same top-to-bottom running order, so when the browser encounters a block of JavaScript, it runs it in order, from top to bottom, all the way to the end, before it moves on. With that said, in most cases the html content is more important than the functionality (in other words, the functionality can come after the user sees the content), so for the reason, it is often times a best practice to place this JS code and linked script tags at the bottom of your html document, inside of your closing /body tag.

Inside your HTML file (at the bottom):
<script src="js/scripts.js"></script>
In a separate JS file (e.g. script.js):;
document.addEventListener('DOMContentLoaded', function() {
    const element = document.querySelector('#mydiv');
    element.addEventListener('click', function() {
      // do something
    });
    
})

If, for some reason, you can not load your JavaScript in the header, then you can either add a [defer] attribute to your script tag, or wrap your JavaScript code in a DOMContentLoaded event listener within your external .js file, or both. Don’t believe me? Chris Ferdinandi confirms pretty much the exact same thing here within one of his “Daily Tips” newsletter posts about web components.

JavaScript and the DOM (Document Object Model)

JS can store values (data), run operations on data (change data), listen to user actions (event listening), and make changes to elements within a html document directly in the browser immediately via DOM manipulation. The DOM API allows web developers to manipulate HTML and CSS, such as create, remove, and change HTML elements and dynamically apply new styles to elements on a web page. JS is natively supported by almost all browsers, which means that it is executed by the browser’s JavaScript Engine (no plugin, server, or database required).

Example: Add/Remove a Class on a Single Element (e.g. on click event)

To target a single, unique element (class or id) using vanilla JS, you can use document.querySelector():

<a href="#" class="mybutton">Unique Button</a>

You then need to add an event listener to handle a click event and a function to do something once an event is triggered.

    document.querySelector('.mybutton').addEventListener('click', function(e) {
      this.classList.toggle('red');
      e.preventDefault();
    });

Example: Add/Remove a Class on a Multiple Elements (e.g. on click event)

To target multiple elements (that share the same class) using vanilla JS, you can use document.querySelectorAll() and you’ll need to loop through an array of elements:

    <a href="#" class="button">Regular Button</a>
    <a href="#" class="button">Regular Button</a>
    const elements = document.querySelectorAll('.button');
    for ( let i = 0, len = elements.length; i < len; i++ ) {
        elements[i].addEventListener('click', function(e) {
          this.classList.toggle('red');
          e.preventDefault();
        });
    }

Example: Change a Data Attribute Value (e.g. “state”)

When dealing with situations that require simple state management (e.g. whether a menu is “open” or “closed”), instead of adding/removing a class (toggling), another solution is to change the value of the element’s data attribute. To do this, you will need to add an event listener to handle a click event and then a function to do something once an event is triggered.

<button class="menu-button">Toggle Menu</button>
const mymenubutton = document.querySelector('.menu-button');
const mymenu = document.querySelector('.menu-drawer');
mymenubutton.addEventListener('click', function() {
    if (mymenu.getAttribute('data-menustate') === 'open') {
        mymenu.setAttribute('data-menustate', 'closed');
     } else {
        mymenu.setAttribute('data-menustate', 'open');
    }
});
Notes:
  • document.querySelector(‘.classname’) gets the first matching element
  • document.querySelectorAll(‘.classname’) returns a node list (“array”) of all matching elements.
  • These will only work on IE 9+. If you require support for older browsers, you can use a polyfill or use different methods, such as:

JS Terminology

A Brief Primer

Variables

Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it:

var myvariable;
myvariable = "Chris";
console.log(myVariable);

Using modern JS, you can use const and let instead of var.

  • Use const for any variables with values that will never change (e.g. a DOM element that you want to target)
  • Use let for variables with values that will change (e.g. a counter variable for a for loop).
const myvariable;
myvariable = "Chris";
console.log(myVariable);
for ( let counter = 0, totalnumberofitems = 4; counter < totalnumberofitems; counter++ ) {
     console.log(counter);
 }

Data Types

  • String
  • Number
  • Boolean
  • Array
  • Object

Arrays and Objects

An array is a collection of values are comma-separated values

An object is a collection of both properties and values that are represented as key/value pairs, where each pair is separated by a comma.

Methods

Methods provide the ability to extend the power of an object by setting the value of a property to a function (e.g. the latter in an object’s key/value pair).

Operators

An operator is a symbol that produces a result based on two values or variables.

1 + 1 //here the + operator is used to add two numerical values
"Hello" + "Chris" //here the + operator is used to combine (concatenate) two values, or in this case: two strings.

Conditionals

if (something === true) {
    // do something
} else {
    // do something else
}

Loops

Loops are used to repeat code multiple times, often used when you need to apply the same set of instructions to multiple elements on a web page. The basic anatomy of a loop is 1) a starting value (e.g. 1), and exit condition (e.g. when you get to the total number of instances of an element or class on a web page), and 3) an increment (+1 every time you go through the loop).

Here’s an example of the syntax of a “for” loop:

for (var i = 1 ; i < totalnumberofitems ; i++) {
    // do something
    console.log(i)
}

Dot Notation vs. Bracket Notation

object.property;
object[property_name]

Functions

A function is a sequence of instructions. You can think of them as “blocks” of code.

Function Definition and Call

A function is defined using the “function” keyword followed by a custom name and a set of parentheses (for any function arguments, if needed), then the “body” of the function is situated between two curly braces and can contain an unlimited number of statements, each of which must end with a semicolon.

Events

To add interactivity to a website using JS, you can use events. Events essentially “listen” for things to happen in the browser so that code can be triggered, or run, in response. A common example is the click event, that is executed (“fired” when a user clicks on something (or “touches” it via their device).

There are several different ways to attach an event to an element.

document.querySelector('.myButton').onclick = function() {};
const myButton = document.querySelector('.myButton');
myButton.onclick = function() {};
const myButton = document.querySelector('.myButton');
myButton.addEventListener('click', function() {
}

Conclusion

Javascript is fun and powerful. External JS files should be linked via script in the bottom of the html document to avoid browser render-blocking. Happy Scripting!

Related Resources and Reading

Go Further

Author Notes

This was written specifically to help aspiring web designers as they aim to:

  • Learn the basic syntax and common uses of Javascript for front-end web development.