top

Search

JavaScript Tutorial

JavaScript, often known as JS, is a high-level, both interpreted and compiled programming language. It is characterized by weakly-typed language in which functions are first-class citizens. It is different then traditional programming languages like C++ and Java which are strongly typed and where classes are the main thing.In Java and C++, we declare a variable with their type in front of it. It is declared as a string, Boolean, integer as below.string str = “This is a string”; int i = 10; boolean bool = trueOn the other hand in JavaScript, everything is a var(although two new types – let and const were introduced in ES6).var str = “This is a string”; var I = 10; var bool = true;These can also be reassigned later without any errors in JavaScript.Next JavaScript is mainly a function based language where a lot of emphases is given on functional programming comparison to languages like C++ and Java where everything is a Class.Also, we can implement the concept of classes in JavaScript using constructor function and even ES6 has a class keyword, but they are different then Classes in Java or C++.As earlier said JavaScript is both interpreted and compiled programming language.Let’s first understand what is a compiled language and interpreted language.Compiled Languages are languages in which we turn a program first from human-readable format to machine format, generally through a compiler. After that, we execute that code. So, it is generally a two-step process. Languages like C, C++ and Java are examples of Compiled languages. For example, if we have a “C” program(hello.c), we will first convert it into machine code by using a gcc(Gnu C compiler) like below:gcc hello.c -o helloIf no error it will generate an executable “hello” and we will run it by:./helloInterpreted Languages are languages in which code doesn’t need to be compiled first. Language like Perl, Python are interpreted languages. To run a python code we just need to run it directly by a command like below:python hello.pyThe above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.JavaScript is a special case where you directly execute your source code. A web page will directly execute your JavaScript. So, for that reason, many people think JavaScript as an interpreted language.However, there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.Compilation Step – During this step, the compiler mainly registers the variable declarations.Let consider the below example. The compilation steps mainly look at the var keyword. It is not bothered by what is assigned in these variables.var a = 10;var b = 20;console.log(a+b);When the compiler goes to line 1, it encounters var and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t find any var, so don’t do anything.Interpretation Step – During this the actual execution takes place.For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it has a variable “a” in Global scope and the compiler has it. So, it assigns the value 10 to it.Next, the same step is repeated for line 3 and interpreter assigns 20 to variable “b”.Now once the interpreter goes to line 5, it finds the console. It first looks for the console at global scope from the compiler but doesn’t find it. So, it checks in the JavaScript global and finds it. Inside the console, there are variable a and b, which it finds at global scope. It then adds them using the addition operator and displays the result.JS Where To / PlacementIn HTML document to run JavaScript code we need to place it inside <script>…</script> tags. We can insert the <script> tag inside <head> or <body>, but it affects the way HTML is parsed. It is because the moment the browser parser encounters <script> tag, it stops HTML parsing till all the code inside <script> tag is executed. Let’s us check the different ways to load JavaScript.JavaScript in <head>..</head> sectionIt is useful to put the script in the head if you want to capture something like a click event. You should keep in mind that the page HTML will not show until the script is fully executed. So, putting a code which is doing a lot of operations, like doing some network request will be a bad practise because the user visiting your website will see a blank page until all JavaScript code is executed.<html>   <head>            <script>                     function sayHello() {               console.log("Hello JavaScript")            }      </script>        </head>   <body>      <input type = "button" onclick = "sayHello()" value = "Hello JS" />   </body>   </html>It will show a button on the page and on clicking it will show the text “Hello JavaScript” on console log.JavaScript in <body>..</body> sectionYou can put the script tag anywhere inside the body section. But again we should keep in mind that the browser will not parse further until all JavaScript code is executed. Below is the case which needs the script to generate content for the page.<html>   <head>   </head>      <body>      <script>             document.write("Hello JavaScript")      </script>            <p>This is web page body </p>   </body> </html>The code will show the following result on the webpage.Hello JavaScriptThis is web page bodyThe best practice, however, is to put the script tag just before the </body> tag ends. This way the user, especially on slower networks will not see a blank page and the HTML will be rendered. After that, the script can be loaded, which generally adds interactivity to buttons and other elements.JavaScript in an external fileAs the JavaScript code grows, we separate it from the HTML file and keep it in a separate file with .js extension. Notice that it can be put anywhere in <head> or <body> and will block the execution of HTML code accordingly.<html>   <head>      <script src = "filename.js" ></script>   </head>   <body>      .......   </body> </html>Script tag attributesWe can have two attributes also in script tag – async and defer. As told earlier that when the browser encounters a script tag, it blocks any other parsing till the JavaScript is executed.We will look at all three types of execution here – Normal, async and defer.Normal ExecutionTake the example of <script> been located somewhere in the middle of the body.<html> <head> ... </head> <body>    ...    <script src="script.js">    .... </body> </html>As mentioned earlier, the HTML parsing will stop to fetch and then execute the script.Async ExecutionThe async attribute in the script tag indicates to the browser that script file can be executed asynchronously.<html> <head> ... </head> <body>    ...    <script async src="script.js">    .... </body> </html>The script is fetched on parallel with the HTML parsing. But once the script is fetched, the HTML parsing is paused to execute the script.Defer ExecutionThe defer attribute in the script tag indicates to the browser that script file to be executed only once the HTML parsing is completed.<html> <head> ... </head> <body>    ...    <script defer src="script.js">    .... </body> </html>Like async the script can be fetched in parallel to HTML parsing. But even if the script is fetched before the HTML parsing is completed, it will wait for the parsing to be completed before executing the script.JS OutputJavaScript doesn’t have any built-in capabilities like C, C++, Java to print and display. Below is the function in these three traditional languages to print something.printf(“C programming”); cout << “C++ programming”; System.out.println(“Java programming”);JavaScript doesn’t have any, so it uses the browser’s window and document object for display and print. Mostly there are four ways to display data in JavaScript.innerHTML:- For writing into HTML element.document.write():- For Writing into HTML for Output.window.alert():- Writing into an alert boxconsole.log():- For writing into browser console.innerHTMLTo access an HTML element, JavaScript uses various methods of document like getElementById(), getElementsByClassName(), querySelector(), querySelectorAll() and others. The most popular nowadays in querySelector() because we can use it with both ids and classes.<!DOCTYPE html> <html> <body> <h1 class="first"></h1> <p id="demo"></p> <script> document.querySelector(``.first").innerHTML = "My First Web Page"; document.querySelector("#demo").innerHTML = 5 + 6; </script> </body> </html>document.write()The write() method writes string of text to a document stream. The document.write() should be embedded inside an document.open() and document.close().If not mentioned, it is automatically added by the JS engine.<html> <head>  <title>write example</title>  <script>    function latestContent () {      document.open();      document.write("<h1>Out with the old - in with the new!</h1>");      document.close();    }  </script> </head> <body onload="latestContent();">  <p>The original document.</p> </body> </html>In the above example, the text The original document is replaced by Out with the old - in with the new!. It is because if write() is called after the HTML document is loaded, will delete all existing HTML.window.alert()The window.alert() method displays an alert dialog with the optional specified content and an OK button.The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message.Dialog boxes are actually modal windows which prevent the user from accessing the rest of the webpage until the dialog box is closed. <!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <p>My first paragraph.</p> <script> window.alert(5 + 6); alert(); </script> </body> </html>console.log()The console.log() method writes a message to the web console. It is used extensively by developers to check the output of some variable at some point.<!DOCTYPE html> <html> <body> <h1>Open the Web console</h1> <script> console.log("The sum of 5 + 6 is ", 5 + 6); </script> </body> </html>Javascript StatementsA program is a list of instructions to be executed by the computer. In JavaScript, these programming instructions are called statements.Below is a simple JavaScript program, which consists of many JS Statements.var x, y, z;    // Statement 1 x = 5;          // Statement 2 y = 6;          // Statement 3 z = x * y;      // Statement 4 console.log("z is", z); // Statement 5Semicolons(;)-Semicolons are used to separate lines of the statement as in the above example. We can also put multiple statements on a single line until they are separated by semicolons. We will refactor the above code a bit.var x, y, z;    // Statement 1 x = 5; y = 6;   // Statement 2 z = x * y;      // Statement 3 console.log("z is", z); // Statement 4One more thing to keep in mind is that we can omit the semicolon at the end of the line. The JavaScript compiler will automatically insert it.var x, y, z    // Statement 1 x = 5; y = 6   // Statement 2 z = x * y      // Statement 3 console.log("z is", z) // Statement 4White SpaceJavaScript ignores multiple white spaces. You can use these white spaces to make your code more readable and presentable. Consider the below example.var coder="Harry";   // Less readable var coder= "Harry";   // More readable z=x*y;      // Less readable z = x * y;      // More readable for(var i=0;i<=10;i++) // Less readable for(var i=0; i<=10 ; i++) // More readableCode BlocksJavaScript statements can be grouped together inside curly brackets. This patter is mostly seen in functions, loops and conditional statements.//JavaScript function function addNumbers(num1, num2) { return num1 + num2; } //for loop for( var i=0; i<10 ; i++){ console.log(i); } //if-else statement if(age > 18) { return “Adult”; } else { Return “Not adult”; }JavaScript  KeywordsJavaScript has a set of keywords which have special meaning to JS compiler. We cannot use them for the variable name as they have special meanings.KeywordDescriptionbreakTerminates any loopcontinueJumps out of that iteration of the loopdebuggerStops the execution of JavaScriptdo…whileType of a loop, which is guaranteed to execute at least onceforType of a loop, which is used most frequentlyfunctionUsed to declare a functionif…elseConditional statementreturnExists from functionswitchType of conditional statement.try…catchUsed to implement error handling in a block of codevarDeclares a variable. It can be of any type.
logo

JavaScript Tutorial

What is Javascript

JavaScript, often known as JS, is a high-level, both interpreted and compiled programming language. It is characterized by weakly-typed language in which functions are first-class citizens. It is different then traditional programming languages like C++ and Java which are strongly typed and where classes are the main thing.

In Java and C++, we declare a variable with their type in front of it. It is declared as a string, Boolean, integer as below.

string str = “This is a string”;
int i = 10;
boolean bool = true

On the other hand in JavaScript, everything is a var(although two new types – let and const were introduced in ES6).

var str = “This is a string”;
var I = 10;
var bool = true;

These can also be reassigned later without any errors in JavaScript.

Next JavaScript is mainly a function based language where a lot of emphases is given on functional programming comparison to languages like C++ and Java where everything is a Class.

Also, we can implement the concept of classes in JavaScript using constructor function and even ES6 has a class keyword, but they are different then Classes in Java or C++.

As earlier said JavaScript is both interpreted and compiled programming language.
Let’s first understand what is a compiled language and interpreted language.

Compiled Languages are languages in which we turn a program first from human-readable format to machine format, generally through a compiler. After that, we execute that code. So, it is generally a two-step process. Languages like C, C++ and Java are examples of Compiled languages. For example, if we have a “C” program(hello.c), we will first convert it into machine code by using a gcc(Gnu C compiler) like below:

gcc hello.c -o hello

If no error it will generate an executable “hello” and we will run it by:

./hello

Interpreted Languages are languages in which code doesn’t need to be compiled first. Language like Perl, Python are interpreted languages. To run a python code we just need to run it directly by a command like below:

python hello.py

The above code does not need to be compiled first but it does require that python is installed on any machine that needs to run the script.

JavaScript is a special case where you directly execute your source code. A web page will directly execute your JavaScript. So, for that reason, many people think JavaScript as an interpreted language.

However, there is a compilation step just before the interpretation step in JavaScript. So, JS is both compiled and interpreted language.

Compilation Step – During this step, the compiler mainly registers the variable declarations.

Let consider the below example. The compilation steps mainly look at the var keyword. It is not bothered by what is assigned in these variables.

var a = 10;
var b = 20;

console.log(a+b);

Compilation Step

When the compiler goes to line 1, it encounters var and registers it in the global scope and then goes to line 3 and registers the var b. Line 5 is only a console and it doesn’t find any var, so don’t do anything.

Interpretation Step – During this the actual execution takes place.

For the above example, the interpreter starts at line 1 and see a variable a and ask the compiler, if it has a variable “a” in Global scope and the compiler has it. So, it assigns the value 10 to it.
Next, the same step is repeated for line 3 and interpreter assigns 20 to variable “b”.
Now once the interpreter goes to line 5, it finds the console. It first looks for the console at global scope from the compiler but doesn’t find it. So, it checks in the JavaScript global and finds it. Inside the console, there are variable a and b, which it finds at global scope. It then adds them using the addition operator and displays the result.

JS Where To / Placement

In HTML document to run JavaScript code we need to place it inside <script>…</script> tags. We can insert the <script> tag inside <head> or <body>, but it affects the way HTML is parsed. It is because the moment the browser parser encounters <script> tag, it stops HTML parsing till all the code inside <script> tag is executed. Let’s us check the different ways to load JavaScript.

JavaScript in <head>..</head> section

It is useful to put the script in the head if you want to capture something like a click event. You should keep in mind that the page HTML will not show until the script is fully executed. So, putting a code which is doing a lot of operations, like doing some network request will be a bad practise because the user visiting your website will see a blank page until all JavaScript code is executed.

<html>
  <head>      
     <script>         
           function sayHello() {
              console.log("Hello JavaScript")
           }
     </script>     
  </head>
  <body>
     <input type = "button" onclick = "sayHello()" value = "Hello JS" />
  </body>  
</html>

It will show a button on the page and on clicking it will show the text “Hello JavaScript” on console log.

Hello JavaScript

JavaScript in <body>..</body> section

You can put the script tag anywhere inside the body section. But again we should keep in mind that the browser will not parse further until all JavaScript code is executed. Below is the case which needs the script to generate content for the page.

<html>
  <head>
  </head>   
  <body>
     <script>
            document.write("Hello JavaScript")
     </script>      
     <p>This is web page body </p>
  </body>
</html>

The code will show the following result on the webpage.

Hello JavaScript

This is web page body

The best practice, however, is to put the script tag just before the </body> tag ends. This way the user, especially on slower networks will not see a blank page and the HTML will be rendered. After that, the script can be loaded, which generally adds interactivity to buttons and other elements.

JavaScript in an external file

As the JavaScript code grows, we separate it from the HTML file and keep it in a separate file with .js extension. Notice that it can be put anywhere in <head> or <body> and will block the execution of HTML code accordingly.

<html>
  <head>
     <script src = "filename.js" ></script>
  </head>
  <body>
     .......
  </body>
</html>

Script tag attributes

We can have two attributes also in script tag – async and defer. As told earlier that when the browser encounters a script tag, it blocks any other parsing till the JavaScript is executed.

We will look at all three types of execution here – Normal, async and defer.

Normal Execution
Take the example of <script> been located somewhere in the middle of the body.

<html>
<head> ... </head>
<body>
   ...
   <script src="script.js">
   ....
</body>
</html>

As mentioned earlier, the HTML parsing will stop to fetch and then execute the script.

Execute the script

Async Execution

The async attribute in the script tag indicates to the browser that script file can be executed asynchronously.

<html>
<head> ... </head>
<body>
   ...
   <script async src="script.js">
   ....
</body>
</html>

The script is fetched on parallel with the HTML parsing. But once the script is fetched, the HTML parsing is paused to execute the script.

HTML parsing is paused to execute the script.

Defer Execution

The defer attribute in the script tag indicates to the browser that script file to be executed only once the HTML parsing is completed.

<html>
<head> ... </head>
<body>
   ...
   <script defer src="script.js">
   ....
</body>
</html>

Like async the script can be fetched in parallel to HTML parsing. But even if the script is fetched before the HTML parsing is completed, it will wait for the parsing to be completed before executing the script.

Parsing to be completed before executing the script

JS Output

JavaScript doesn’t have any built-in capabilities like C, C++, Java to print and display. Below is the function in these three traditional languages to print something.

printf(“C programming”);
cout << “C++ programming”;
System.out.println(“Java programming”);

JavaScript doesn’t have any, so it uses the browser’s window and document object for display and print. Mostly there are four ways to display data in JavaScript.

innerHTML:- For writing into HTML element.
document.write():- For Writing into HTML for Output.
window.alert():- Writing into an alert box
console.log():- For writing into browser console.

innerHTML

To access an HTML element, JavaScript uses various methods of document like getElementById(), getElementsByClassName(), querySelector(), querySelectorAll() and others. The most popular nowadays in querySelector() because we can use it with both ids and classes.

<!DOCTYPE html>
<html>
<body>
<h1 class="first"></h1>
<p id="demo"></p>
<script>
document.querySelector(``.first").innerHTML = "My First Web Page";
document.querySelector("#demo").innerHTML = 5 + 6;
</script>
</body>
</html>

My first web page in JavaScript

document.write()
The write() method writes string of text to a document stream. The document.write() should be embedded inside an document.open() and document.close().
If not mentioned, it is automatically added by the JS engine.

<html>
<head>
 <title>write example</title>
 <script>
   function latestContent () {
     document.open();
     document.write("<h1>Out with the old - in with the new!</h1>");
     document.close();
   }
 </script>
</head>
<body onload="latestContent();">
 <p>The original document.</p>
</body>
</html>

In the above example, the text The original document is replaced by Out with the old - in with the new!. It is because if write() is called after the HTML document is loaded, will delete all existing HTML.

window.alert()
The window.alert() method displays an alert dialog with the optional specified content and an OK button.

The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message.

Dialog boxes are actually modal windows which prevent the user from accessing the rest of the webpage until the dialog box is closed. 

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
alert();
</script>
</body>
</html>

My first web page in JavaScript

console.log()
The console.log() method writes a message to the web console. It is used extensively by developers to check the output of some variable at some point.

<!DOCTYPE html>
<html>
<body>
<h1>Open the Web console</h1>
<script>
console.log("The sum of 5 + 6 is ", 5 + 6);
</script>
</body>
</html>

Open the web console in JavaScript

Javascript Statements

A program is a list of instructions to be executed by the computer. In JavaScript, these programming instructions are called statements.
Below is a simple JavaScript program, which consists of many JS Statements.

var x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x * y;      // Statement 4
console.log("z is", z); // Statement 5

Semicolons(;)-

Semicolons are used to separate lines of the statement as in the above example. We can also put multiple statements on a single line until they are separated by semicolons. We will refactor the above code a bit.

var x, y, z;    // Statement 1
x = 5; y = 6;   // Statement 2
z = x * y;      // Statement 3
console.log("z is", z); // Statement 4

One more thing to keep in mind is that we can omit the semicolon at the end of the line. The JavaScript compiler will automatically insert it.

var x, y, z    // Statement 1
x = 5; y = 6   // Statement 2
z = x * y      // Statement 3
console.log("z is", z) // Statement 4

White Space

JavaScript ignores multiple white spaces. You can use these white spaces to make your code more readable and presentable. Consider the below example.

var coder="Harry";   // Less readable
var coder= "Harry";   // More readable
z=x*y;      // Less readable
z = x * y;      // More readable
for(var i=0;i<=10;i++) // Less readable
for(var i=0; i<=10 ; i++) // More readable

Code Blocks

JavaScript statements can be grouped together inside curly brackets. This patter is mostly seen in functions, loops and conditional statements.

//JavaScript function
function addNumbers(num1, num2) {
return num1 + num2;
}
//for loop
for( var i=0; i<10 ; i++){
console.log(i);
}
//if-else statement
if(age > 18) {
return “Adult”;
} else {
Return “Not adult”;
}

JavaScript  Keywords

JavaScript has a set of keywords which have special meaning to JS compiler. We cannot use them for the variable name as they have special meanings.

KeywordDescription
breakTerminates any loop
continueJumps out of that iteration of the loop
debuggerStops the execution of JavaScript
do…whileType of a loop, which is guaranteed to execute at least once
forType of a loop, which is used most frequently
functionUsed to declare a function
if…elseConditional statement
returnExists from function
switchType of conditional statement.
try…catchUsed to implement error handling in a block of code
varDeclares a variable. It can be of any type.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Janani

I have learned many things from this article. It is beneficial for me. Thank you!

Nilesh Chakrabarty

Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..

michael

This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.

qtsinfo it

Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.

knowledge-wisdom

You have shared great information with me i appreciate your work!

Suggested Tutorials

Node JS Tutorial

Build various types of web applications,command-line application,etc.
Node JS Tutorial

Build various types of web applications,command-line application,etc....

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More