Introduction to JavaScript: Basics
In this article, I am going to explain the basics of JavaScript through a beginners perspective. Let's get started.
Table of contents
- Prerequisites
- What is JavaScript?
- How JavaScript is different from other programming languages like Java or C++?
- How to include JavaScript in your HTML page?
- How to Write Comments in JavaScript?
- Variables in JavaScript
- Local variables :
- Global variable :
- Data types in JavaScript
- Primitive data types :
- Non-primitive data types :
- Operators in JavaScript
- Arithmetic Operators :
- Assignment Operators :
- Comparison Operators :
- Bitwise Operators :
- Logical Operators :
- Conditional Statements in JS
- if Statement :
- switch Statement :
- Loops in JavaScript
- for Loop :
- For-in Loop :
- while Loop :
- do-while Loop :
- Functions in JavaScript
- Parameters and Arguments :
- Function with Return Value :
- Function Scope :
- Conclusion
Prerequisites
Before starting this article, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS.
What is JavaScript?
JavaScript is a scripting language used to create and control dynamic web content. It is an interpreted, lightweight object-oriented programming language that enables dynamic interactivity on websites. It can be anything from animated graphics to an automatically generated Facebook timeline. Once you have created your basic structure(HTML) and elegant vibe(CSS), JavaScript makes your website dynamic(automatically updateable).
If you are a software developer who gravitated towards web development then you must learn javascript and once you have learned JavaScript there are many frameworks available that you can use to create multiple web applications. Nowadays javascript is also used in mobile app development, desktop app development, and game development. This opens many possibilities for you as a JavaScript developer.
How JavaScript is different from other programming languages like Java or C++?
The major difference is that JavaScript is a scripting language i.e it is not compiled and executed like C++ and java. It is dynamically typed whereas Java or C++ is statically typed. JavaScript is traditionally used to write scripts for web applications. The client receives the whole source of the script and the browser executes it - the browser has a JavaScript interpreter while the browser couldn't execute Java or C++ programs. Javascript does not support multithreading while java or C++ is a multi-threaded language.
Now, JavaScript can run on the server via Node.js.
How to include JavaScript in your HTML page?
JavaScript can either be embedded directly inside the HTML page or placed in an external script file and referenced inside the HTML page. There are three places to put javascript code-
between the head tag of an HTML page
Example-
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Embedding JavaScript</title> <script> document.getElementById("greet").innerHTML = "Hello World!"; </script> </head> <body> <div id="greet"></div> </body> </html>
between the body tag of an HTML page
Example-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Embedding JavaScript</title> </head> <body> <div id="greet"></div> <script> document.getElementById("greet").innerHTML = "Hello World!"; </script> </body> </html>
In .js file (external javascript file)
Example-
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Linking External JavaScript</title> </head> <body> <div id="greet"></div> <button onclick="greet()">Show message</button> <script src="script.js"></script> </body> </html>
script.js
function greet() { document.getElementById("greet").innerHTML = "Hello World!"; }
How to Write Comments in JavaScript?
Comments are a meaningful way to deliver messages. It is not necessary but recommended to use comments to add information about the code, warnings, or suggestions so that others can easily understand and interpret your code.
Types of comments in JavaScript
Single-line comment => Single-line comments are represented by double forward slashes " // ".
Example-
<script>
var x=1;
var y=2;
var z=x+y; // It adds values of x and y variable
document.write(z); // prints sum of x and y
</script>
Multi-line comment => It is represented by a forward slash with an asterisk " /* " and then an asterisk with a forward slash " */ ".
Example-
<script>
/*
The code below will change the heading with id = "myP" and the
paragraph with id = "myP" in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
Variables in JavaScript
Variable means anything that can vary. These are the containers for storing data values. Also, JavaScript variables are loosely typed which means it does not require a data type to be declared. There are some rules while declaring a variable in js:-
variable name must starts letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
after the first letter, we can use digits (0 to 9), for example- abc1
javascript variables are case sensitive(x and X are different variables)
Example of JavaScript variables
Correct JavaScript variables =>
<script>
var x=10;
var _value=1.1;
var flag1=true;
var Name; //declaration of variable
Name="neha"; //initialization of variable
</script>
Incorrect JavaScript variables =>
<script>
var 123=30;
var *aa=320;
</script>
There are two types of variables in JavaScript:
Local Variables
Global Variables
Local variables :
Local variables are the variables that are defined inside a block or function. They have a local scope which means that they are accessible within the function or block.
Example-
<script>
function fun()
{
var x=10; //local variable
console.log(x);
}
</script>
Global variable :
Global variables are the variables that are defined outside the functions or declared with a window object. They can be accessed from any function.
Example-
<script>
var data=200; //global variable
function a()
{
console.log(data);
}
function b()
{
console.log(data);
}
a(); //calling JavaScript function
b();
</script>
Data types in JavaScript
Data types specify what kind of data can be stored and manipulated within a program. JavaScript provides different data types to hold different types of values. In JS we don't need to specify the type of the variable because it is dynamically used by the JavaScript engine. Mainly there are two types of data types in javascript:-
Primitive data types
Non-Primitive data types
Primitive data types :
Primitive data types can hold only one value at a time. There are five types of primitive data types in JS:-
Non-primitive data types :
Non-primitive data types can hold collections of values and more complex entities. There are mainly three types of non-primitive data types:-
Operators in JavaScript
Operators are special symbols used to perform operations on operands. For example,
var a=10,b=20;
var sum=a+b;
Here, the " + " operator performs addition, and 'a' and 'b' are operands.
Arithmetic Operators :
Arithmetic operators are used to perform arithmetic calculations. The arithmetic operators are as follows:-
Assignment Operators :
Assignment operators are used to assign values to variables. The following are assignment operators in js:-
Comparison Operators :
Comparison operators compare two values and return a boolean value, either true or false. The following are Comparison operators in js:-
Bitwise Operators :
Bitwise operators perform operations on binary representations of numbers. The bitwise operators are as follows:
Logical Operators :
Logical operators perform logical operations and return a boolean value, either true or false. The following are logical operators in js:-
Conditional Statements in JS
Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run.
if Statement :
The most common type of conditional statement is the if-else statement. This statement only runs if the condition enclosed in parentheses () is true. There are three forms of if statements in JavaScript:-
If-statement
If-else statement
if-else-if statement
If statement example
<script> var a=20; if(a>=20) { alert("value of a is greater and equal to 20"); } </script>
if-else statement example
<script> var a=20; if(a>=20) { alert("value of a is greater and equal to 20"); } else { alert("value of a is less than 20"); } </script>
if-else if statement example
<script> var a=20; if(a>20) { alert("value of a is greater than 20"); } else if(a==20) { alert("value of a is equal to 20"); } else { alert("value of a is less than 20"); } </script>
switch Statement :
The switch statement is used to execute one code from multiple expressions. If there is a match, the associated block of code is executed and if there is no match, the default code block is executed.
Example:-
<script>
var grade='C';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
alert(result);
</script>
Loops in JavaScript
Loops are used for executing a block of statements repeatedly until a particular condition is satisfied. It makes the code compact. JavaScript supports different kinds of loops:
for loop
for-in loop
while loop
do-while loop
for Loop :
The for loop iterates the elements for a fixed number of times. Syntax of for
loop is as follows:
for(initialization; condition; increment)
{
//code block to be executed
}
Example:-
<script>
for(i=0;i<10;i++)
{
document.write(i + " ")
}
</script>
Output:- 1 2 3 4 5 6 7 8 9
For-in Loop :
The for-in loop iterates through the properties of an Object. Syntax of for
loop is as follows:
for (key in object) {
// code block to be executed
}
Example:-
<script>
var user = "";
var person = {fname:"Mrinmoy", lname:"Porel", age:21};
var x;
for (x in person) {
user += person[x] + " ";
}
document.write(user);
</script>
Output:- Mrinmoy Porel 21
while Loop :
The while loop iterates through a block of code as long as a specified condition is true. Syntax of while
loop is as follows:
while (condition)
{
// code to be executed
}
Example:-
<script>
var count=0;
while (count<=5)
{
document.write(count + " ");
count++;
}
</script>
Output:- 0 1 2 3 4 5
do-while Loop :
A do-while loop is similar to a while loop with one exception that the code is executed at least once whether the condition is true or false. Syntax of do-while
loop is as follows:-
do
{
//code to be executed
}while (condition);
Example:-
<script>
var i=1;
do{
document.write(i + "<br/>");
i++;
}while (i<=5);
</script>
Output:-1 2 3 4 5
Functions in JavaScript
Functions are one of the major pillars of JavaScript. It is a set of statements that performs some tasks or does some computation and then returns the result to the user. It helps you to divide a large program into small ones and makes a program a lot more efficient. The syntax for declaring a function is given below:-
function functionName(arg1, arg2, ...argN)
{
//code to be executed
}
Let’s first see the simple example of a function in JS that doesn't have any arguments.
<html>
<body>
<input type="button" onclick="msg()" value="call function"/>
<script>
function msg(){ //function definition
alert("Hello World!"); //create an alert in browser
}
</script>
</body>
</html>
Parameters and Arguments :
When you begin programming you may get confused between these two terms, but it is crucial to understand what they are and how are they different from each other. So Let's understand the difference between these two:-
Function with Return Value :
This is an optional JavaScript statement that returns a value from the function. We use the keyword return, followed by the statement or expression we want to return.
Example:-
<html>
<body>
<p>What is the value of PI?</p>
Ans:-<span id="demo"></span>
<script>
document.getElementById("demo").innerHTML = getPI();
function getPI() {
return Math.PI;
}
</script>
</body>
</html>
Note:- Return statement should be written in the last because it skips all code in the block written after that.
Function Scope :
As we know there are two types of variables in JS, local variables and global variables. Local variables are defined inside a function and cannot be accessed outside it. But a function can access any variable defined as a global variable.
Let's understand exactly what I mean with the help of the following code:
<html>
<body>
<h3>Function Scope</h3>
<script>
var num1 = 2; //global variable
document.write("Value of number 1 is " + num1 + "</br>"); //global scope
function parentFunction(){
var num2 = 4; //local variable
num1 = 8;
document.write("Number 1 is " + num1 + "</br>"); //inside parent func.
document.write("Number 2 is " + num2 + "</br>"); //local scope
childFunction(); //child function called
function childFunction(){ //nested function
var num3 = 0;
document.write("Number 2 is " + num2 + "</br>"); // inside child func.
document.write("Number 3 is " + num3 + "</br>"); //local scope
}
}
parentFunction(); //parent function called
</script>
</body>
</html>
Output:-
Conclusion
HTML is the language of web content, but JavaScript is the language of web functionality. It is one of the fastest evolving languages, in terms of practices, tooling, and ecosystem. It’s an incredibly exciting language to be using right now.
In this article, we have just scratched the surface of JavaScript. If you enjoyed learning and find it useful please do like and share so that, it reaches others as well 🤝.
Thanks for reading 😃
I would ❤ to connect with you on Twitter | LinkedIn | GitHub Let me know in the comment section if you have any doubts or feedback.