JavaScript Tutorial
Written by Avinash Malhotra
Updated on
Start by running JavaScript in the browser console, then add a script to an HTML page. The examples introduce objects, functions, operators, dialogs and comments.
What is JavaScript?
JavaScript is a programming language used to make web pages interactive and to write applications outside the browser. On a web page, it can respond to a click, update content or give feedback as someone fills in a form.
Brendan Eich created JavaScript at Netscape in 1995 for the Navigator browser. Runtimes such as Node.js, Deno and Bun also run JavaScript outside a browser.
JavaScript is often called the programming language of the web because browsers can execute it directly. A page built with HTML and CSS can also work without scripts.
Within one JavaScript thread, each task runs to completion. The browser can run a callback after the current work finishes, for example when a network response is ready. Modern engines can also use JIT compilation to speed up frequently executed code.
What should you know before learning JavaScript?
Why learn JavaScript?
JavaScript is useful when a page needs to respond to a reader. For example, a form can check an entry immediately and explain how to correct it.
HTML defines the form fields, CSS controls their appearance and JavaScript handles events such as typing or submitting. Beyond the browser, Node.js runs server code and React Native lets developers build mobile apps.
In a full-stack project, JavaScript can handle form input in the browser and process the submitted data on the server.
JavaScript Applications
Where is JavaScript used?
- Frontend Development
- Backend Development
- Software Development
- Console Applications
- Mobile app development
- Web Animations
- Games
- AR and VR
- 2D and 3D
- Machine Learning
- Data Science
- AI
JavaScript Facts
These features explain where JavaScript runs and how it handles work.
- JavaScript was the most commonly used programming language among respondents to the 2023 Stack Overflow Developer Survey. GitHub activity measures a different population.
- JavaScript runs on the frontend in browsers and on the backend in runtimes such as Node.js and Deno.
- You can try a JavaScript expression directly in the browser console.
- Modern engines can compile frequently executed JavaScript into machine code.
- Browsers and Node.js support both synchronous execution and asynchronous operations. A callback function can run when an operation finishes.
- Web Workers can run JavaScript on a separate thread and exchange messages with the page.
- JavaScript manages memory automatically. Its garbage collector can reclaim objects once they are unreachable.
- JavaScript supports several programming styles, including functional and object-oriented programming.
JavaScript History
Early pages on the WWW connected documents through links. In 1995, Brendan Eich developed a prototype-based language that let authors add behaviour to pages in Netscape Navigator.
The language had the development name Mocha. Netscape later called it LiveScript before announcing JavaScript with Sun Microsystems.
Microsoft introduced its own implementation, JScript, in Internet Explorer 3.
In 1997, Ecma published the first edition of ECMA-262. The specification gave browser vendors a common language standard.
Today, developers can use JavaScript for both client-side interfaces and server-side applications.
Eich built the first prototype in ten days. Checking form entries before sending them to a server was an early use of browser scripting.
Timeline of JavaScript
The timeline shows how browser scripting and the language standard developed.
| Year | Event |
|---|---|
| 1995 | Netscape introduces JavaScript |
| 1997 | Ecma publishes the first edition of ECMA-262 |
| 2005 | The term “Ajax” is introduced for updating a page with data from a server. |
| 2014 | HTML5 becomes a W3C Recommendation and specifies how browsers process scripts. |
| 2015 | ECMAScript 2015 (ES6) is published |
ECMA
Ecma International, originally the European Computer Manufacturers Association, publishes ECMA-262. Its technical committee TC39 develops the language specification. The standard grew out of the need for implementations such as JavaScript and JScript to behave consistently.
ECMAScript is the name of the standard. Sun Microsystems originally held the JavaScript trademark, which later transferred to Oracle. JavaScript, JScript and ActionScript have all implemented editions of ECMAScript.
ECMAScript Definition
Based on the ECMAScript language specificationECMAScript defines JavaScript’s core syntax, data types, built-in objects and execution rules. JavaScript engines implement that specification. A host supplies additional APIs, such as the browser’s document object for reading and updating a web page.
What is a scripting language?
A scripting language lets a program automate tasks in a host environment. In a browser, a script can read a form field, respond to a click or change the text of a heading.
Early web scripts often handled events and checked form entries on the client.
Today, ECMAScript also supports general-purpose programming outside the browser.
JavaScript Versions (ECMAScript editions)
The table lists editions of ECMA-262 and selected features from each. ES6 and ECMAScript 2015 refer to the same edition. A feature’s publication year tells you when it entered the standard. Browser and runtime support depends on the version you use. See the ECMAScript edition history for details.
| Year | Version | Description |
|---|---|---|
| 1997 | ES1 | First Edition |
| 1998 | ES2 | Editorial revisions to align the specification with ISO/IEC 16262. |
| 1999 | ES3 | Added regular expressions, try/catch and new string methods. |
| ---- | ES4 | Abandoned |
| 2009 | ES5 | Added strict mode, getters and setters in object literals, JSON support and new object methods. |
| 2011 | ES5.1 | Aligned with ISO/IEC 16262:2011. |
| 2015 | ES6 (ES2015) | Added classes, modules, let, const, arrow functions and promises. |
| 2016 | ES7 | Added the exponentiation operator (**) and Array.prototype.includes(). |
| 2017 | ES8 | Added async functions, await, Object.values and Object.entries. Generator functions first appeared in ES2015. |
| 2018 | ES9 | Added object rest and spread properties, async generators and asynchronous iteration. |
| 2019 | ES10 | Added Array.prototype.flat, Object.fromEntries, trimStart and trimEnd, and required stable array sorting. |
| 2020 | ES11 | Added String.prototype.matchAll, dynamic import(), BigInt, Promise.allSettled and globalThis. |
| 2021 | ES12 | Added String.prototype.replaceAll, Promise.any, AggregateError, logical assignment (??=, &&=, ||=) and numeric separators (1_000). |
| 2022 | ES13 | Added top-level await in modules, public and private class fields, and Object.hasOwn. |
| 2023 | ES14 | toSorted, toReversed, with, findLast, toSpliced and findLastIndex methods on Array |
| 2024 | ES15 | Promise.withResolvers, Object.groupBy, Map.groupBy, String.prototype.isWellFormed, String.prototype.toWellFormed |
| 2025 | ES16 | Added iterator helpers such as map, filter and toArray, new Set methods, JSON modules, RegExp.escape, Promise.try and Float16Array. |
| 2026 | ES17 | Array.fromAsync(), Error.isError(), Math.sumPrecise(), Map and WeakMap Upsert, Iterator.concat(), Uint8Array Base64 and Hex methods, and JSON source text access |
JavaScript Engines
A JavaScript engine parses and executes JavaScript. A host such as a browser or a runtime such as Node.js, Deno or Bun provides the engine with APIs for its environment.
The table pairs engines with browsers and other environments that use or have used them.
| JavaScript Engine | Browser | Other Environments |
|---|---|---|
| Chrome V8 | Google Chrome, Chromium, Opera, Brave, Microsoft Edge ( Jan 2020 onwards ) |
Node.js, Deno |
| SpiderMonkey | Firefox, Netscape Navigator | MongoDB 3.2 and above, Adobe Acrobat and Reader, CouchDB |
| JavaScriptCore | Safari | Bun |
| Chakra ( Deprecated ) | Internet Explorer, legacy Microsoft Edge | n/a |
| Carakan ( Deprecated ) | Older Opera releases | n/a |
| LibJS | Ladybird browser | n/a |
- V8 is the open-source engine used by Chromium, Node.js and Deno. MongoDB also used V8 in earlier releases.
- Brendan Eich developed SpiderMonkey, the first JavaScript engine, at Netscape. Mozilla develops it for Firefox.
- Chakra powered Internet Explorer 9–11 and the original Microsoft Edge. Chromium-based Edge uses V8.
- Firefox 3.5 introduced a tracing JIT compiler in 2009. V8 also uses JIT compilation to improve execution speed.
Is JavaScript interpreted or compiled?
JavaScript engines can use both interpretation and compilation. An engine can interpret bytecode and compile frequently used code to machine code while the program runs. ECMAScript defines the language behaviour and leaves the execution strategy to the engine.
The same distinction applies to languages such as PHP, Python and Ruby. Performance depends on the implementation and the workload. Java, for example, can also use just-in-time compilation.
Dynamic typing and automatic memory management let developers write scripts without declaring a type for every variable or freeing each object manually. Python, for example, is widely used for scientific calculations and simulations.
Initial Approach
An interpreter executes instructions while the program runs. An engine can first translate the source into an intermediate form called bytecode and then interpret that bytecode.
For a learner, this means you can edit a script and reload the page to run it again.
Modern JIT Compilation Approach
Google Chrome launched in 2008 with V8. V8 compiles JavaScript, and its execution strategy has evolved over time.
Modern V8 can start by interpreting bytecode. As a function runs repeatedly, the engine gathers information that helps it generate optimised machine code.
Just-in-time compilation takes place while the program runs. Ahead-of-time compilation takes place before that execution begins.
For example, a loop that repeatedly adds numbers gives the engine information about the types of values it usually encounters.
If those values change, the engine can switch back to a less specialised version of the code.
How interpretation and compilation work together
- Parsing checks the syntax and builds an internal representation of the source.
- An interpreter can execute bytecode, while a JIT compiler can generate machine code for frequently executed functions.
- Both approaches can operate within one engine.
- The language rules apply whether the host is a browser or a server runtime.
How to write JavaScript Code
An HTML page can use an internal script, load an external JavaScript file or put code in an inline event handler.
The examples below show each form.
Internal JavaScript
An internal script contains JavaScript directly inside a <script> element. Place the example in the body after any content it needs to access. It sets document.body.textContent to replace the page body’s contents with “Hello JavaScript”.
<script>
document.body.textContent="Hello JavaScript";
</script>
External JavaScript
Store external JavaScript in a separate .js file. The src attribute of the <script> element tells the browser which file to load. In this example, put custom.js next to the HTML file.
<script src="custom.js"></script>
Module Pattern
You can also load an external script as a module. A module can import and export functions, objects and values.
<script type="module" src="custom.js"></script>
ES6 introduced JavaScript modules. Top-level declarations stay in module scope, and the browser fetches external modules and their dependencies without blocking HTML parsing. Module scripts normally start executing after the page is parsed.
Inline JavaScript
An inline event handler puts JavaScript in an HTML attribute such as onclick. In new code, register event listeners in a script with addEventListener(). The examples show older patterns, including the obsolete <marquee> element and a javascript: URL.
<button onclick="alert('Hello JS')">Check</button>
<marquee onmouseover="stop()" onmouseout="start()">Hello Javascript</marquee>
<a href="javascript:void(0)">Void</a>
How to Run JavaScript in HTML
To run JavaScript in HTML, put code inside a <script> element or point its src attribute to a JavaScript file. A classic script in the initial HTML without async or defer pauses parsing while it runs. If that script is external, parsing also waits while the browser fetches it.
If a script needs page elements, place it after them or load an external classic script with defer in the head. Deferred classic scripts run in document order once HTML parsing is complete. See the HTML Standard’s script element reference for details.
JavaScript Code in Head
<!doctype html>
<html>
<head>
<title>JavaScript</title>
<meta charset="utf-8">
<script >
// Write JS Code here
</script>
</head>
<body>
<!-- Page content -->
</body>
</html>
JavaScript Code in Body
<!doctype html>
<html>
<head>
<title>JavaScript</title>
<meta charset="utf-8">
</head>
<body>
<!-- Page content -->
<script>
// Write Js Code here
</script>
</body>
</html>
Important terms in JavaScript
Objects, functions and operators appear together in even a short JavaScript program.
Object
An object groups properties under keys. A car object might store engine size as a property and a function as a method. Use dot or bracket notation to access a property. Learn more about JavaScript objects.
const car=new Object();
car.power=190;
car.engine=2000;
Functions
A function is a callable object. You can assign one to a variable or an object property, pass it to another function and invoke it with parentheses. The example calls the car’s run method. Learn more about JavaScript functions.
const car=new Object();
car.run=function(){ console.log("Car is running") };
car.run();
Operators
Operators act on values. For example, + adds two numbers and = assigns a value. See the guide to JavaScript operators.
let x=3; // = is assignment operator
let y=x+10; // + is addition operator
JavaScript Console
Open Developer Tools in your browser and select the Console tab. Type 2 + 3 and press Enter to see 5. Use console.log() to print values from a script. The Console also shows errors and lets you inspect variables that are in scope.
Print in JavaScript Console
The example prints hello string in the console.
<script>
let x="hello string";
console.log(x);
</script>
Explore the JavaScript console methods.
JavaScript Dialog Boxes
Browsers provide three built-in window methods for simple dialogs. Use alert() to show a message, prompt() to request text and confirm() to ask for a decision.
- alert
- prompt
- confirm
JavaScript Alert, alert()
alert() displays a message. When the browser shows the dialog, the script normally pauses until the user dismisses it.
<script>
let x="hello js";
alert(x);
</script>
JS Prompt, prompt()
window.prompt() asks the user to enter text. Selecting OK returns a string. If the field is empty, it returns an empty string (""). Selecting Cancel returns null.
<script>
let x=prompt("Enter Name");
alert(x);
</script>
JS Confirm, confirm()
window.confirm() asks the user to accept or cancel an action. It returns true for OK and false for Cancel.
<script>
let x=confirm("Press Ok or Cancel");
alert(x);
</script>
Modal dialogs interrupt interaction with the page. For routine feedback, show a message next to the control that needs attention.
Browsers, including Firefox, can suppress dialogs in some circumstances.
JavaScript Comments
Comments explain code or temporarily disable statements while testing. JavaScript supports line comments and block comments.
Single Line Comment in JavaScript
A line comment begins with // and continues to the end of the line.
JavaScript Single Line Comment
<script>
// single line comment
</script>
Multi-line Comment in JavaScript
A block comment starts with /* and ends with */. Like a CSS comment, it can span several lines.
JavaScript Block Comment
<script>
/* Multi-line Comment */
</script>
Classic browser scripts recognise legacy HTML-like comment syntax such as <!--comment-->. Use JavaScript comment syntax for new code. HTML-like comments are invalid in modules.
Both comment styles work in production. A JavaScript-aware minifier handles line endings correctly. Simply deleting line breaks can cause a line comment to swallow the next statement.
The noscript Element
The HTML noscript element provides fallback content when scripting is disabled. A browser with scripting enabled skips the fallback, even if a particular script fails to load.
Fallback content example
<noscript>Please Enable Javascript</noscript>
<script>
console.log('Javascript Working');
</script>
For a classic script in HTML, omit the type attribute. JavaScript is the default. The language attribute is obsolete. Use type="module" when loading a JavaScript module.
JavaScript Code Editor
VS Code supports plain JavaScript, jQuery, React, Angular and Node.js. The list also includes editors used in older projects.
- VS Code
- Atom (discontinued)
- Sublime Text
- Brackets
- WebStorm
- NetBeans
VS Code is available for Windows, macOS and Linux and is built on an open-source project. IntelliSense provides code completion, the debugger lets you inspect a running script, and Git integration helps you track changes.
JavaScript Video Tutorial
Watch the introductory lesson, then learn how to name and store values in the JavaScript variables tutorial.