TNS
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
✓
Angular
0%
✓
Astro
0%
✓
Svelte
0%
✓
Vue.js
0%
✓
Other
0%
✓
I only use React
0%
✓
I don't use JavaScript
0%

JavaScript

JavaScript is a high-level, interpreted programming language primarily used for web development. It allows developers to create dynamic and interactive content on websites, enhancing user experience by enabling client-side scripts to manipulate the browser’s Document Object Model (DOM) and communicate with servers asynchronously.

 
OVERVIEW

Introduction to JavaScript

Introduction to Javascript

Possibly the most popular programming language in the world, JavaScript underpins the web by enabling dynamic and interactive pages. But its flexibility and versatility is available on a wide range of platforms beyond the browser, from servers and smartphones to embedded systems, and it has emerged as a way of creating rich, engaging applications on all those devices. Annual updates to the language introduce new features and improvements to the functionality, readability, and performance of JavaScript, as well as increasing developer productivity; which ensures a language that’s fast to write and easy to get started with also stays relevant for increasingly challenging scenarios.

Brief History of JavaScript

The fact that the first version of JavaScript (originally called Mocha and then LiveScript), was written by Brendan Eich as a scripting language for the Netscape browser in just 10 days doesn’t mean the language is poorly designed. Intended to make webpages more dynamic and interactive, it drew on concepts and features from existing languages like Scheme and Java and has been extensively developed since. Although the language became an ECMAScript standard in 1997, updates stalled for a while after the release of ES5 in 2009, resulting in an unusually rich ecosystem of libraries and frameworks to help JavaScript keep up with the rapid evolution of web technologies. Since 2015, when ES6 came out with major revisions to the language, there have been annual updates to ECMAScript to harness the creativity of the JavaScript community and bring those new features in the language in a standardized way that’s available across platforms consistently.

Over the years, developers realized that JavaScript could be useful beyond the browser as a general-purpose language on a range of platforms and environments. The introduction of Node.js in 2009 as an open source cross-platform runtime using the V8 engine brought JavaScript to server-side programming. This expansion made JavaScript not just a tool for creating interactive web interfaces, but a way to handle complex backend tasks in the same fast, efficient language.

Current Relevance

Widely used and regularly updated, JavaScript remains a cornerstone of modern web development — which includes mobile devices and environments far beyond the browser. Its ubiquity is unparalleled; it delivers interactive elements in webpages, is essential for frontend frameworks like React, Angular, and Vue.js, powers desktop applications like Slack and VS Code through Electron and operates on servers, IoT devices and serverless platforms like Cloudflare Workers through runtimes like Node.js and Deno. JavaScript’s flexibility and adaptability have allowed it to remain at the forefront of web development trends, allowing developers to deliver ever-more sophisticated web applications.

Strong community support and the vast ecosystem of libraries and frameworks, along with supporting technologies like TypeScript WebAssembly that supplement JavaScript help JavaScript keep up with the range of what developers need to build. Whether it’s for creating simple websites or complex enterprise-level applications, JavaScript is indispensable in the current web development landscape — and beyond.

Digging into JavaScript

If you’re just getting started with JavaScript, we’ll take a look at the fundamentals of the language, from variables and data types to control structures and functions and touch on the advanced concepts that give JavaScript its power and versatility, including key frameworks and libraries, with some tips on best practices, ensuring that your JavaScript code is not only functional but also efficient, maintainable, and secure.

Perhaps more than any other language, JavaScript is driven by the community, so alongside resources and directions for tutorials that will help you deepen your understanding, we’ll touch on where to connect with other developers and stay on top of the latest developments.

Fundamentals of JavaScript

Fundamentals of JavaScript

JavaScript, developed as the scripting language of the web, offers a rich set of features that make webpages interactive and functional. New JavaScript developers should start by understanding basic syntax and data types.

Basic Concepts of the JavaScript Language: Variables, Data Types, Operators

  • Variables: In JavaScript, variables are used to store data values. JavaScript uses the keywords var, let, and const to declare and assign variables. While var has a function scope, let and const are only available in the block of code where they are declared, offering more predictable behavior in complex applications because you can reduce the change of unintended side effects.
  • Data Types: JavaScript is a dynamically typed language, which means the type of a variable is determined when the code runs rather than when it’s compiled. The eight primary data types are:
  • Primitive Types: String, Number, BigInt, Boolean, Undefined, Null, and Symbol.
  • Non-Primitive Types: The reference or derived data types are used to store collections of data: Object, Array, Function, Map, Set, WeakMap and WeakSet. Objects are key-value pairs, and arrays are ordered collections of values.
  • Operators: JavaScript includes various operators that you use with expressions and statements to perform calculations and logic. These include:
  • Arithmetic Operators: Perform basic mathematical operations with operators like +, -, *, % and /..
  • Comparison Operators: Compare two values with ==, ===, !=, >, <, >+ and so on.
    • Logical Operators: The three primary logical operators are && (and), || (or), and ! (not) : they return true or false by evaluating the variables and values in the expression.
  • String, Bitwise, Conditional and Type Operators.
  • Use regular expressions, text formatting and the emerging internationalization options to process strings and display text.

Control Flow and Error Handling

  • Loops: JavaScript supports several types of loops to repeat actions:
  • For loop: Iterates a set number of times or loops through the properties (For/In) or values (For/Of) an object.
  • While loop: Continues as long as the specified condition is true.
  • Do/While loop: Executes the code block once, and then repeats the loop as long as the specified condition is true.
  • Use break and continue statements to control the flow of code in loops.
  • Conditionals: These statements allow decision-making in code by executing different code blocks. The if/else statement executes a block of code if the specified condition is true, and another block if it is false; use else if to add a further statement to test. The switch statement is used for selecting one of many code blocks to be executed.
  • Error Handling: Handle errors and exceptions with try…catch statements. The try block contains code that may throw an error; the code to handle that error is in the catch block; use a final block for code that will execute whether or not an error occurs.

JavaScript Functions and Scope

  • Functions — sections of reusable code that perform a specific task — are the fundamental building blocks of JavaScript code, declared using the function keyword.
  • Expressions: any valid unit of code that resolves to a value — including variables, literals, operators and functions calls — is a JavaScript expression. If you assign a function to a variable, creating a function expression, you can leave out the function name.
  • Arrow Functions: Introduced in ES6, arrow functions allow you to write functions much more concisely: you don’t need the function keyword and if the functions consist of a single expression you don’t need the return keyword. They are particularly useful for short functions but can’t be used as methods or constructors.
  • Closures: A closure in JavaScript is a specific function that has access to a wider scope of variables: its own scope, the scope of the outer function and the global scope. Closures are powerful: you can use them to create modular, reusable code, to preserve state when you use asynchronous operations or to emulate private methods and variables; but they can also cause memory leaks and other unexpected behavior.

JavaScript in the Browser: DOM Manipulation, Events

Although the JavaScript language no longer only runs inside browsers, because it started as a web scripting language it has specific options for working with webpages:

  • DOM Manipulation: The Document Object Model (DOM) is the interface that allows JavaScript to change the content and structure of a webpage to make it dynamic and interactive: creating, removing, or modifying HTML elements and attributes and working with the layout tree.
  • Events: JavaScript can react to what the user does on a webpage — clicking on buttons, moving the cursor, pressing keys and entering text — to display navigation menus, pop-ups and other ways of interacting with the page. JavaScript lets developers track events like clicks, mouse movements, key presses or form submissions with event listeners (addEventListener) and define JavaScript functions (event handlers) to be executed when the events occur.

Advanced JavaScript Concepts

Advanced Javascript Concepts

Although you can make webpages interactive with fairly simple JavaScript, for complex applications you will want to turn to more sophisticated and powerful programming techniques.

Functional and Object-Oriented Programming

  • JavaScript supports both functional and Object-Oriented Programming (OOP). Functional programming treats data as immutable and functions as first-class objects that can be passed as arguments to other functions, returned by functions and assigned to variables. OOP in JavaScript uses the prototype mechanism by which JavaScript objects inherit features, so it works a little differently from classical object-oriented programming languages.
  • Classes and Objects: Built on top of prototypes, classes are a template for creating objects in JavaScript, rather than being objects themselves. An object is an instance of a class with properties and methods, so a Car class might have properties like brand and color or methods like start(). Use classes to encapsulate data with the code that will operate over that data.
  • Inheritance and Polymorphism: Creating new classes based on existing ones allows the child class to reuse the methods and variables of the patent class. Using the extends keyword, a class can be declared as a child of another class — and you can use polymorphism to override any methods in the parent class that aren’t useful in the child class to perform different operations. This is useful for creating a hierarchical structure in code, reducing redundancy, and enhancing reusability. For instance, a Electric Car class could extend a Car class, inheriting its properties and adding new features like battery capacity, but overriding the warning that the gas cap hasn’t been replaced after filling up with code to check if the car is still plugged in.
  • Modules and namespaces: There are other ways to organize and encapsulate code in JavaScript. Modules allow you to break your code up into separate files (useful for large codebases), or you can organize the functions of your code into local groups with namespace objects. If you want a more formal structured option for handline namespaces, TypeScript adds a namespace keyword.

Asynchronous Programming: Callbacks, Promises, Async/Await

Because JavaScript is single-threaded but also frequently runs in the browser, it needs a way to run code without blocking the main thread and slowing down the rendering of the webpage you’re looking at. Long-running tasks are delegated to the browser’s background processes and when they finish, a callback function is triggered to handle the results.

  • Callbacks: A callback is a function passed into another function as an argument and executed at a later time. Callbacks enable asynchronous programming in JavaScript but are difficult to write and debug.
  • Promises: Introduced in ES2015 to handle the complexities of callbacks, a Promise is an object representing the eventual outcome — completion or failure — of an asynchronous operation. JavaScript Promises are a wrapper function around a callback function and they are easier to write and manage, with three states: pending, fulfilled, or rejected. Methods like .then() and .catch() are used to resolve the promise or handle errors.
  • Generators: generators are functions that can be stopped and started, allowing developers to write functions that wait for a promise to be resolved.
  • Async/Await: The async/await syntax was added in ES2017 to make it easier to work with promises and generators and write asynchronous code that looks more like synchronous code. Put the async keyword before a function to mark it as asynchronous and use the await keyword inside the function to pause the execution of the function code until the promise is resolved, and then resume the code.

JavaScript Frameworks and Libraries

JavaScript Frameworks and Libraries

While you can create interactive webpages and apps from scratch in JavaScript, frameworks and libraries make life easier, giving you built-in functions for common tasks (which improves the consistency and reliability of your code), supplementing missing features in the language, improving cross-platform compatibility so apps work across a wider range of devices, optimizing performance and giving you access to support from what’s usually an active community of developers. It may take a little more work to learn them, but frameworks and libraries provide structures, patterns and extra tools. Some of the most popular JavaScript frameworks handle frontend development; we’ll come back to the server-side JavaScript frameworks used for backend development later on.

Overview of Popular JavaScript Frameworks: Angular, Ember.js,Vue.js, Babylon.js

  • Angular: Maintained by Google, Angular is a widely used framework for building single-page apps (SPAs). It has a component-based architecture for modularity, uses templates to make creating UI views simple and has rich features like two-way data binding, modularization, AJAX handling and dependency injection. Angular has a steep learning curve but there are a lot of courses and tutorials and it’s well-suited for building large-scale, high-performance applications. Don’t confuse it with the older Angular.js which is no longer developed or supported by Google.
  • Ember.js: Another component-based framework for creating SPAs, Ember uses templates, provides default behaviors that make it quick to get started, is strongly opinionated (to the point that all apps have the same structure) and has its own built-in router, state management and development environment with an Inspector and Ember CLI, that some other libraries like Glimmer.js have adopted.
  • Vue.js: A simpler progressive framework for building user interfaces, SPAs and smaller projects, Vue.js is designed to be easy to get started with — and too add to existing projects. The core library focuses on the view layer only and handles data binding, CSS transitions and animations, but you can add a router, scheduling and CLI for project scaffolding and bring in more libraries if you want to build more powerful SPAs.
  • Babylon.js: A powerful 3D engine based on WebGLA and JavaScript, you can use Babylon.js as a library for displaying 3D models and scenes or a framework with built-in components that can help you build complex interactive applications.

Highlights of the JavaScript Library Ecosystem: React, jQuery, Lodash, Moment.js, D3.js

  • React: Developed by Facebook, React is a declarative, efficient, and flexible JavaScript library for building user interfaces and reusable components for dynamic applications that’s so powerful it’s usually treated as a framework. Its virtual DOM, which optimizes updates to the actual DOM for enhanced performance, allows developers to create large web applications that can change data without reloading the page. You will need to learn its JSX markup syntax and it doesn’t handle any server-side logic, but again, there is a strong community with many resources for learning.
  • jQuery: Once the most popular JavaScript library, with the improvements in the language since ES2015 many of the tasks jQuery handles can now be done directly in JavaScript. You may still need it for legacy projects that rely on it for simplifying HTML document manipulations, event handling, animation and AJAX interactions but it’s not likely to be your first choice for new projects.
  • Lodash: A utility library that makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings and so on, Lodash has modular methods that are great for iterating arrays, objects, and strings; manipulating and testing values; and creating composite functions.
  • Moment.js: Until the long-awaited Temporal object is added to the ECMAScript standard, you’ll want to use the Moment.js library to work efficiently with time and date, especially handling time zones and different languages.
  • D3.js: D3.js (Data-Driven Documents) is a library for producing dynamic, interactive data visualizations using SVG, HTML and CSS rather than a proprietary framework.

Choosing the Right JavaScript Framework/Library: Factors to Consider

When there are multiple options for which library or framework you’re going to use, choose between them the way you would pick any other development tool:

  • Project Requirements: Assess the specific needs of your project. For complex, enterprise-level applications, a comprehensive framework like Angular might be suitable. For dynamic interfaces with reusable components, React is a great choice. For smaller projects or particular functionalities like data visualization, a library like D3.js might be all you need.
  • Learning Curve: Consider the time and effort required to learn the framework or library. React has a steeper learning curve than Vue.js but offers more flexibility in large applications.