Let’s see what’s so special about JavaScript, what we can achieve with it, and what other technologies play well with it.
What is JavaScript?
JavaScript was initially created to “make web pages alive”.
The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.
Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.
In this aspect, JavaScript is very different from another language called Java.
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that time, so it was decided that positioning a new language as a “younger brother” of Java would help.
But as it evolved, JavaScript became a fully independent language with its own specification called ECMAScript, and now it has no relation to Java at all.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine.
The browser has an embedded engine sometimes called a “JavaScript virtual machine”.
Different engines have different “codenames”. For example:
- V8 – in Chrome, Opera and Edge.
- SpiderMonkey – in Firefox.
- …There are other codenames like “Chakra” for IE, “JavaScriptCore”, “Nitro” and “SquirrelFish” for Safari, etc.
The terms above are good to remember because they are used in developer articles on the internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it probably works in Chrome, Opera and Edge.
Engines are complicated. But the basics are easy.
- The engine (embedded if it’s a browser) reads (“parses”) the script.
- Then it converts (“compiles”) the script to machine code.
- And then the machine code runs, pretty fast.
The engine applies optimizations at each step of the process. It even watches the compiled script as it runs, analyzes the data that flows through it, and further optimizes the machine code based on that knowledge.
What can in-browser JavaScript do?
Modern JavaScript is a “safe” programming language. It does not provide low-level access to memory or the CPU, because it was initially created for browsers which do not require it.
JavaScript’s capabilities greatly depend on the environment it’s running in. For instance, Node.js supports functions that allow JavaScript to read/write arbitrary files, perform network requests, etc.
In-browser JavaScript can do everything related to webpage manipulation, interaction with the user, and the webserver.
For instance, in-browser JavaScript is able to:
- Add new HTML to the page, change the existing content, modify styles.
- React to user actions, run on mouse clicks, pointer movements, key presses.
- Send requests over the network to remote servers, download and upload files (so-called AJAX and COMET technologies).
- Get and set cookies, ask questions to the visitor, show messages.
- Remember the data on the client-side (“local storage”).
What CAN’T in-browser JavaScript do?
JavaScript’s abilities in the browser are limited to protect the user’s safety. The aim is to prevent an evil webpage from accessing private information or harming the user’s data.
Examples of such restrictions include:
JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy them or execute programs. It has no direct access to OS functions.
Modern browsers allow it to work with files, but the access is limited and only provided if the user does certain actions, like “dropping” a file into a browser window or selecting it via an
<input>
tag.There are ways to interact with the camera/microphone and other devices, but they require a user’s explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the NSA.
Different tabs/windows generally do not know about each other. Sometimes they do, for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other page if they come from different sites (from a different domain, protocol or port).
This is called the “Same Origin Policy”. To work around that, both pages must agree for data exchange and must contain special JavaScript code that handles it. We’ll cover that in the tutorial.
This limitation is, again, for the user’s safety. A page from
http://anysite.com
which a user has opened must not be able to access another browser tab with the URLhttp://gmail.com
, for example, and steal information from there.JavaScript can easily communicate over the net to the server where the current page came from. But its ability to receive data from other sites/domains is crippled. Though possible, it requires explicit agreement (expressed in HTTP headers) from the remote side. Once again, that’s a safety limitation.Such limitations do not exist if JavaScript is used outside of the browser, for example on a server. Modern browsers also allow plugins/extensions which may ask for extended permissions.
What makes JavaScript unique?
There are at least three great things about JavaScript:
- Full integration with HTML/CSS.
- Simple things are done simply.
- Supported by all major browsers and enabled by default.
JavaScript is the only browser technology that combines these three things.
That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating browser interfaces.
That said, JavaScript can be used to create servers, mobile applications, etc.
Languages “over” JavaScript
The syntax of JavaScript does not suit everyone’s needs. Different people want different features.
That’s to be expected, because projects and requirements are different for everyone.
So, recently a plethora of new languages appeared, which are transpiled (converted) to JavaScript before they run in the browser.
Modern tools make the transpilation very fast and transparent, actually allowing developers to code in another language and auto-converting it “under the hood”.
Examples of such languages:
- CoffeeScript is “syntactic sugar” for JavaScript. It introduces shorter syntax, allowing us to write clearer and more precise code. Usually, Ruby devs like it.
- TypeScript is concentrated on adding “strict data typing” to simplify the development and support of complex systems. It is developed by Microsoft.
- Flow also adds data typing, but in a different way. Developed by Facebook.
- Dart is a standalone language that has its own engine that runs in non-browser environments (like mobile apps), but also can be transpiled to JavaScript. Developed by Google.
- Brython is a Python transpiler to JavaScript that enables the writing of applications in pure Python without JavaScript.
- Kotlin is a modern, concise and safe programming language that can target the browser or Node.
There are more. Of course, even if we use one of these transpiled languages, we should also know JavaScript to really understand what we’re doing.
Here's an in-depth look at various aspects of JavaScript:
Syntax: JavaScript syntax is similar to C programming language. It uses semicolons
;
to terminate statements, curly braces{}
to denote blocks of code, and uses//
for single-line comments and/* */
for multi-line comments.Data Types: JavaScript has several data types including:
- Primitive Data Types: such as numbers, strings, booleans, null, undefined, and symbols (added in ECMAScript 6).
- Composite Data Types: such as arrays and objects.
Variables: In JavaScript, variables are declared using the
var
,let
, orconst
keywords.var
has function scope,let
has block scope, andconst
is used for constants.Operators: JavaScript supports various operators such as arithmetic, assignment, comparison, logical, bitwise, and more.
Functions: Functions in JavaScript can be declared using the
function
keyword or through arrow functions introduced in ECMAScript 6. Functions are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.Control Flow: JavaScript provides control flow statements such as
if...else
,switch
,for
loops,while
loops,do...while
loops, etc.Objects and Prototypes: JavaScript is based on prototypes rather than classes. Objects can be created using object literals or constructor functions. Prototypal inheritance allows objects to inherit properties and methods from other objects.
Arrays: Arrays in JavaScript are dynamic and can hold elements of different data types. They have built-in methods for manipulation such as
push()
,pop()
,splice()
,slice()
, and more.DOM Manipulation: JavaScript is widely used to manipulate the Document Object Model (DOM) of web pages. It allows developers to dynamically change HTML and CSS, handle events, create animations, and more.
Asynchronous Programming: JavaScript supports asynchronous programming through features like callbacks, promises, and async/await. This allows non-blocking execution, making it suitable for handling tasks such as AJAX requests, timeouts, and event handling.
Error Handling: JavaScript provides mechanisms for error handling such as
try...catch
blocks to gracefully handle exceptions.Modules: ECMAScript 6 introduced native support for modules, allowing developers to organize code into reusable and maintainable modules. This improves code encapsulation and reusability.
JavaScript is continuously evolving with new features and improvements being added regularly through updates to the ECMAScript specification. It's used not only for web development but also for server-side development (Node.js), mobile app development (React Native, Ionic), desktop app development (Electron), game development (Phaser, Three.js), and more. Its versatility and ubiquity make it one of the most important programming languages in modern software development.
Functions:
- Functions in JavaScript can be defined using the
function
keyword followed by the function name and parameters enclosed in parentheses. For example:javascriptfunction greet(name) { console.log("Hello, " + name + "!"); }
- Functions can also be defined anonymously and assigned to variables, or passed directly as arguments to other functions. These are called "function expressions".
- JavaScript supports nested functions, where a function is defined within another function. Inner functions have access to the variables and parameters of their outer function, a concept known as "closure".
- Arrow functions, introduced in ECMAScript 6, provide a more concise syntax for defining functions. They have a shorter syntax and lexically bind
this
, making them especially useful for callback functions and concise one-liners. For example:javascriptconst add = (a, b) => a + b;
- Functions in JavaScript can be defined using the
Objects and Prototypes:
- Objects in JavaScript are collections of key-value pairs where keys are strings (or Symbols) and values can be any data type.
- Prototypal inheritance is a fundamental concept in JavaScript. Each object has a prototype chain, which allows it to inherit properties and methods from its prototype.
- Constructor functions are used to create objects with a shared prototype. They are typically capitalized to distinguish them from regular functions.
- The
class
syntax, introduced in ECMAScript 6, provides a more familiar syntax for creating constructor functions and defining methods. However, under the hood, JavaScript still uses prototypal inheritance. - Object-oriented programming patterns such as encapsulation, inheritance, and polymorphism can be implemented in JavaScript using prototypes.
Arrays:
- Arrays in JavaScript are dynamic, meaning their size can change dynamically as elements are added or removed.
- They can hold elements of different data types, including other arrays (nested arrays).
- JavaScript arrays have a variety of built-in methods for manipulation and iteration, such as
push()
,pop()
,shift()
,unshift()
,splice()
,slice()
,map()
,filter()
,reduce()
, and more.
Asynchronous Programming:
- JavaScript is single-threaded, meaning it can only execute one task at a time. Asynchronous programming allows JavaScript to perform non-blocking operations, enabling it to handle multiple tasks concurrently.
- Callback functions are a traditional way of handling asynchronous operations in JavaScript. However, they can lead to "callback hell" or deeply nested code.
- Promises, introduced in ECMAScript 6, provide a more elegant solution for handling asynchronous operations. They represent a value that may be available now, in the future, or never.
- Async/await, introduced in ECMAScript 8, offers a more concise and readable syntax for asynchronous programming. It allows developers to write asynchronous code that looks synchronous, making it easier to understand and maintain.
These are just a few key aspects of JavaScript, but there's much more to explore, including closures, scopes, modules, regular expressions, error handling, and more. JavaScript's versatility and flexibility make it a popular choice for a wide range of applications, from simple web scripts to complex enterprise applications.