JavaScript Tutorial
Written By: Avinash Malhotra
Updated on
JavaScript
JavaScript is an object oriented, general purpose and high level programming language used in Website's Frontend, Backend and Software applications. JavaScript is light weight and easy to learn programming language with JIT Compiler integration in modern web browsers for fast performance.
JavaScript was developed by Netscape in 1995 as a scripting programming language for web browser only. JavaScript is used to build interactive websites with dynamic features and to validate form data. JavaScript is high-level and dynamic programming language with first class functions, supported by all modern web browsers. Apart from web browser, JavaScript is also used to build scalable web applications using Node JS / Deno / Bun.
JavaScript is also known as the Programming Language of Web as it is the only programming language for Web browsers. 100% websites are using JavaScript Programming language for frontend.
JS is single thread with support of asynchronous events and callbacks functions to improve performance. Unlike Other scripting languages, it is very fast as modern web browsers use Just in Time compilers, although earlier till 2009, JavaScript was interpreted and perform slower in browsers.
Prerequisite to learn JavaScript
To learn javascript, the basics of html and css are required. Prior technical background or knowledge of programming languages like C or C++ is not compulsory. JavaScript is an easy to learn programming language if using for Frontend.
- HTML
- CSS
JavaScript is easier than C, C++, Java and C# (Asp.net) Object Oriented Programming Languages.
Why to learn JavaScript in 2024?
JavaScript is the top most demanding technology in 2024. Even JavaScript is the Top Most Popular Technology as per Stack Overflow Survey 2023. The reason is popularity of web, wide variety of applications, super fast performance and availability on both frontend and backend.
HTML can only create webpage structure, css can style html, but to add functionality, we need javascript. Unlike HTML and CSS, JavaScript is dynamic. Earlier JavaScript was meant for browser environment only, but now JavaScript is also used on server Node JS and Software Development (React Native).
By using javascript, we can build both frontend and backend of a website.
JavaScript Applications
- Frontend Development
- Backend Development
- Software Development
- Console Applications
- Mobile Apps Development
- Web Animations
- Games
- AR and VR
- 2D and 3D
- Machine Learning
- Data Science
- AI
- JavaScript is the Most Popular Programming Language on Stack Overflow and Github since last 10 Years Surveys.
- In Stack Overflow survey 2015, JavaScript was the second most popular programming language in the world. First was Java.
- Latest Stack overflow survey shows that JavaScript is the most popular programming language.
- JavaScript is also among highest paid in IT Sector.
JavaScript Facts
Here are some very interesting and informative facts about JavaScript.
- JavaScript is World's Top Programming Language as per Github and Stack overflow surveys.
- JavaScript can be used on both frontend and backend ( Node JS & Deno).
- JavaScript is easy to learn as syntax is based on scripting languages.
- JavaScript was build as a scripting programming language, but supports Just In Time (JIT) Compilation for faster execution.
- JavaScript is Single Threaded and asynchronous, but supports asynchronous programming using callback functions.
- JavaScript also use Web Workers to perform operations on another thread.
- JavaScript manage memory automatically, so developer need to focus on logic part only.
- JavaScript is Multi-paradigm, means its supports both functional and object oriented programming.
JavaScript History
WWW was formed in 1990. Initially it was a bunch of web-pages linked together. But soon people want more interactive and dynamic websites. So on demand of Netscape, Brenden Eich, (inventor of Javascript) in 1995 invented a prototype based language for their Navigator Browser. Initially it was called "LiveScript", but later on renamed as "Javascript".
The same time, Microsoft also invented JScript, the Microsoft's client side scripting language for their Internet Explorer 3. But JScript was meant for Internet Explorer only.
In 1998, ECMA standardized Javascript, not JScript. Thus Microsoft start using Javascript in Internet Explorer 4 and Javascript become popular.
In today's world, Javascript is the top most demanding technology as it can handle both front end and Back-end.
JavaScript was written in 10 days only for Netscape navigator browser. That time, JavaScript was developed to validate form data on client side.
Timeline of JavaScript
Here is a Timeline of JavaScript, with Year of launch and other details.
Year | Event |
---|---|
1995 | JAVASCRIPT Launched |
1998 | JAVASCRIPT was standardized by ECMA |
1998 | DHTML( Html + Javascript) |
2005 | AJAX Introduced |
2009 | Included in HTML5 |
ECMA
ECMA stands for European Computers Manufacturers Association. When the browsers war happened around 1997, ECMA took responsibility to build standards for web. As Microsoft's JScript was used in Internet Explorer, and Netscape use JavaScript, ECMA standardize javascript as Programming Language for web. Since then, ECMA build standards for JavaScript.
JavaScript is Trade Marked under Oracle (since 2009), earlier Sun Microsystems. As Oracle own the trademark of JavaScript, ECMA version is called ECMA Script. ECMA Script is the standard of JavaScript, JScript and ActionScript. ECMA Release the standards for ECMA Script and JavaScript follows those standards.
ECMAScript Definition
(From ECMA Official Website)ECMAScript is a object-oriented programming language for performing computations and manipulating computational objects within a host environment. ECMAScript was originally designed to be used as a scripting language, but has become widely used as a general-purpose programming language.
What is Scripting language?
A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language.
ECMAScript was originally designed to be a Web scripting language used to perform client side functionalities, like form validation, event handling etc.
ECMAScript is now a full-fledged programming language. It is fully featured General purpose programming language.
JavaScript Versions ( ECMA Versions )
JavaScript was initially developed for Netscape Navigator browser only. After ECMA standardize JavaScript, ECMA starts development of JavaScript Under developer.mozilla.com. Here is a list a JavaScript Versions or ECMA Versions.
Year | Version | Description |
---|---|---|
1997 | ECMA 1 | First Edition |
1997 | ECMA 2 | Some Editorial Changes |
1999 | ECMA 3 | Add Regular Expressions, Try Cache, new string handlers. |
---- | ECMA 4 | Abandoned |
2009 | ECMA 5 | Add Strict Mode, getter and setters, JSON and More features in Objects. |
2011 | ECMA 5.1 | ECMA Standards are fully aligned with 3rd Edition of ISO/IEC. |
2015 | ECMA 6 (ES6) |
Also known as ES2015, adds Classes and Modules, let & const, Arrow functions and Promises. |
2016 | ECMA 7 | Also known as ES2016, includes two new features: the exponentiation operator (**) and Array.prototype.includes. |
2017 | ECMA 8 | Also known as ES2017 includes await/async, generators, Object.values, Object.entries |
2018 | ECMA 9 | Also known as ES2018 includes rest and spread, |
2019 | ECMA 10 | Also known as ES2019 includes Array.flat, Object.Entries, trimStart, trimEnd, stable Array.sort |
2020 | ECMA 11 | Also known as ES2020 includes String.matchAll, import(), BigInt, Promise.allSettled, globalThis. |
2021 | ECMA 12 | replaceAll in strings, Promise.any , AggregateError, Nullish assignment (??=), &&=, ||=, Numeric literal separators(1_000 for 1000) |
2022 | ECMA 13 | top level await, public and private fields in class, Object.hasOwn |
2023 | ECMA 14 | toSorted, toReversed, with, findLast, toSpliced and findLastIndex methods on Array |
JavaScript Engines
JavaScript Engines are the computer programs used to interpret or compile JavaScript into machine code. JavaScript was primarily developed for browser environment only, but non-browser environments are also using JavaScript now, like Node JS, Deno and Bun.
There are so many JavaScript engines available, but the most popular JavaScript Engines are
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, Previous Edge | n/a |
- Chrome V8 is open source and the most popular JavaScript Engine. V8 is one of the fastest JavaScript Engine and also supports non browser environment like Node JS, Deno, MongoDB etc.
- SpiderMonkey is the First JavaScript Engine developed by Brendan Eich at Netscape. It is currently maintained by Mozilla Foundation.
- Chakra is the slowest javascript engine with no support for ES6. Even IE is legacy browser and will ends support in 2021.
- JavaScript was initially interpreted language, but SpiderMonkey JS Compiler was introduced in Firefox 3.5 in 2009. In Chrome and Node JS, JS is compiled by V8 with just-in-time (JIT) compilation to speed up the code execution.
Javascript Code Execution, Interpreted or Compiled 🤔
JavaScript was build as Client Side Scripting language for web in 1995. All Scripting languages are interpreted like Php, Python and Ruby.
Scripting languages are usually slower in performance then traditional Compiled Programming Languages. That's why C, C++ and Java are Faster then Python, Ruby and Php.
But on the other sides, scripting languages use less and easy syntax, dynamic types datatypes, automatic memory management and error handling. Learning Scripting language is very easy then Compiled Programming Languages. Thats why Scientist use Python for Higher Mathematics and Simulations.
Initial Approach
JavaScript was primarily a scripting language. In scripting languages, the code is translated line-by-line at runtime by an interpreter within the hosted Environment ( Web Browser ) for execution.
This offers flexibility to write easy code with faster development.
Modern JIT Compilation Approach
Google Chrome was launched in 2008 and becomes the top browser in 2012. The main reason for the success of chrome was faster performance then competitors.
Chrome use Just-In-Time (JIT) compilation. Others browsers also follow the same trend later on. JIT translates JS code into machine code for faster compilations.
JIT Compilations occurs on runtime, not as separate pre-executions step used in traditional compilation.
This approach balances the use of same JS Scripting Code (Loosely Typed ), but with improved performance.
Its like putting a Turbo Engine in a normal car🏎️. You will get upto 50% more power🔋 and efficiency with same engine capacity and same fuel.
Final Verdict
- JavaScript is interpreted at its core because it is using syntax of scripting languages. Initial parsing and execution need interpretations.
- JIT Compilation at Run Time. Code get translated into machine code for better performance.
- It use characteristics of both Interpreter and Compiler for flexibility and faster compilation.
- This Hybrid Approach makes JavaScript a versatile and powerful🚀 programming language for both Web and Software based Applications.
How to write JavaScript Code
Based on where JavaScript code is written, javascript is categorized in three parts, Internal Javascript, External Javascript, and Inline Javascript.
Here are the examples with code.
Internal Javascript
In Internal Javascript, javascript coding is written inside head or body within <script>
tag.
<script>
document.body.textContent="Hello JavaScript";
</script>
External Javascript
In External JavaScript, javascript code is written in external file with .js extension and then linked with script tag. Here is an example of external js.
<script src="custom.js"></script>
Inline Javascript
In Inline Javascript, javascript code is written directly inside html tags. All though this is not recommended. Script should be written in separate file( external) or in <script>
tag. See example
<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 Program
Javascript can be placed on both Head or Body tag of our HTML Page using <script>
tag. When Webpage loads, script code executes and can slow down page speed.
Write JavaScript coding in head tag only when we want script to execute first, like to disable text selection, page redirection, notifications etc. Rest all script like JQuery, Angular JS or custom JS should be written just before body closing tag. This can load DOM content first, then scripts will execute, and hence optimize webpage performance.
Javascript Code in Head
<!doctype html>
<html>
<head>
<title>Javascript</title>
<meta charset="utf-8">
<script >
// Write JS Code here
</script>
</head>
<body>
// body content
</body>
</html>
JavaScript Code in Body
<!doctype html>
<html>
<head>
<title>Javascript</title>
<meta charset="utf-8">
</head>
<body>
// content in body
<script>
// Write Js Code here
</script>
</body>
</html>
Important terms in JavaScript
For a beginner to start learning javascript, you must know following terms. As JavaScript is a general purpose programming language, we will discuss only programming terms.
Object
Anything which has property and method is called an object. Like a car is an object. Car can have properties like power, engine and methods like run, reverse. To access property or method of object, use dot (.) or brackets []. Know more about JavaScript Objects
let car=new Object();
car.power=190;
car.engine=2000;
Functions
Functions are first class objects in javascript used to store multiple statements to reuse code. Functions are called or invoked using parenthesis (). Know more about JavaScript Functions
let car=new Object();
car.run();
Operators
Operators are symbols used in programme to perform mathematical or logical operations. For example +
is used to add numbers, =
is used to assign values. Know more about JavaScript Operators
let x=3; // = is assignment operator
let y=x+10; // + is addition operator
JS console
JS Console is a build-in object in javascript to access browser console. To print JS output in console window of web browser, javascript use console.log() function. console is a build-in JavaScript Object and log() is build-in a Function of console object. Any syntax error in JavaScript is shown in console window. Also global variables and functions are accessible in console.
Print in JavaScript Console
hello string
<script>
let x="hello string";
console.log(x);
</script>
Know more about JavaScript Console object.
JavaScript Dialog Box
JavaScript supports three dialog box. These dialog boxes are build in functions of window object. Three dialog box in javascript are alert, prompt and confirm.
- alert
- prompt
- confirm
JavaScript Alert, alert()
JavaScript alert is build-in function used to show output in dialog box. For alerts , use alert(). Alert generally block the code, thus next code block will run only after alert is closed.
<script>
let x="hello js";
alert(x);
</script>
JS Prompt, prompt()
prompt() or window.prompt() dialog box is used to receive input from user. The default datatype of prompt object is string. But if prompt is cancelled, it will return null.
<script>
let x=prompt("Enter Name");
alert(x);
</script>
JS Confirm, confirm()
confirm() or window.confirm() dialog box is used to get confirmation from user. This will show ok or Cancel in dialog box. ok will return true and cancel will return false.
<script>
let x=confirm("Press Ok or Cancel");
alert(x);
</script>
JS Dialog box block JS code till they are closed. Do not use JS Dialog box in production code. Use dialog boxes only for testing purpose.
In Firefox, there is a option to avoid multiple dialog boxes.
JavaScript Comments
Comments are used to write explanations, hints, and to stop execution of code. JavaScript use two comments syntax. One is Single line comment, and second is Multi-line comment.
Single Line Comment in JavaScript
Single Line comments in javascript are used using //
. This will comment only right hand side of code.
JavaScript Single Line Comment
<script>
// single line comment
</script>
Multi-line Comment in JavaScript
JavaScript Multi-line Comments are recommended comments as they have opening and closing. Multi-line Comments are used using /*
opening and */
closing, same like css comments.
JavaScript Multi-line Line Comment
<script>
/* Multi-line Comment */
</script>
Always prefer Multi-line comments in javascript for production. Single line comments in javascript are good for development purpose. But in production, they can create errors after JS Minification.
Noscript Tag
<noscript> tag is an html element used to display warnings when javascript is disabled in web browser. If javascript is enable, noscript tag is invisible.
Noscript Tag use
<noscript>Please Enable Javascript</noscript>
<script>
console.log('Javascript Working');
</script>
In HTML5, type="text/javascript" and language attributes from script tag has been deprecated. So we can write javascript code directly in script tag without any attribute.
JavaScript Code Editor
VS Code is the recommended Code Editor for modern JavaScript. VS Code can also be used for Vanilla js, jQuery, React JS, Angular and Node JS Development.
- VS Code
- Atom
- Sublime Text
- Brackets
- WebStorm
- NetBeans
VS Code is the recommended Code Editor for JavaScript. It open source and available for all desktop platforms, like MacOS, Windows, and Linux. VS Code comes with great features like intellisense, debugger, git support etc. ALso we can use VS Code for advance frameworks like Angular and React or Backend Node JS. Its an All in one editor for JS Stack.