Browse by Domains

JavaScript Tutorial | Introduction to JavaScript

What is JavaScript

JavaScript is known as a verb of the web page that defines all the actions to be performed on a webpage. It is an object-oriented programming language that uses JIT compiler.

JavaScript or JS has various application such as web development, mobile development. It is everywhere and all web browsers are installed with it. JavaScript is easy, simple and very compatible with HTML and CSS . It is must to have skills for any software engineer out there.

Now, you can enroll to Free Online JavaScript Course in Hindi

JavaScript History

  • JS was founded by was Brendan Eich
  • He developed JS in 1995
  • He also developed first JS Engine, Spider Monkey which is still used by Mozilla firefox
  • JS name was later changed to ‘mocha’ and ‘LiveScript’ but it still remains JS due to some trademark reasons

JavaScript Tools

For working with JavaScript, we just need two things:

  • Text editor
    • For writing and editing of JS code, we need a simple editor that can be notepad too.
    • But there are other powerful editors that provide additional functionalities like autocomplete, indentation, highlights, etc.
    • Example: Visual Studio Code, Sublime Text, Atom, etc.
  • Browser
    • All browsers come with an inbuilt JS engine.
    • They are used for executing JS code and also for debugging purposes.

JavaScript  Hello World

Before jumping right into coding, let us understand different ways to write js code. It is important to note that JS basically gets merged into HTML which is a skeleton of web page

We can write our JS in 3 ways

1.Console

Either just press Ctrl + Shift + I to open the console or you can right-click and then go to inspect. Now since you are in the console you can start writing your code

console.log("hello world");

Output:

VM312:1 hello world
undefined 

 console.log is used to print output

2.Script tag

<script> tag is used for writing javascript in HTML directly.But every console.log() will print the output in console of browser

<!DOCTYPE html>
<html>
<head>
	<title>Home</title>
</head>
<body>
	<h1>My First JS Code</h1>
<script>
	console.log("Hello World!");
</script>
</body>
</html>

3.External file

JS code is written in a separate file and is incorporated in the HTML using <script> tag.This is the most efficient way. It also enforces reusability and keeps code short, simple, and easy to understand.

--------  html file ----------
<!DOCTYPE html>
<html>
<head>
	<title>Home</title>
</head>
<body>
	<h1>My First JS Code</h1>
<script type="text/javascript" src="home.js"></script>
</body>
</html>

-------- JS file ----------

console.log("Hello World!");

JavaScript Comments

  • Comments are extra info that helps in the understanding of code and is not passed on to compiler at compilation.
  • In JS, there are 2 types of comment
    • Single line 
	//…………..
  • Multiline 
/*
……….
……….
*/
  • Example:
HTML Code
<!DOCTYPE html>
<html>
<head>
	<title>Home</title>
</head>
<body>
	<h1>My First JS Code</h1>
<script type="text/javascript" src="home.js"></script>
</body>
</html>

JS Code
console.log("Hello World!");
/*console.log("!");
console.log("!");
console.log("!");
console.log("!");*/
//console.log("Hello !");
console.log("Bye");



JavaScript Variables

  • Variables are memory locations with names that store the temporary data.
  • Naming convention:
    • Variable names should begin with a letter, $, or an underscore(_).
    • The first character can be then followed by any combination of letters or digits.
    • A variable name cannot be the same as any keyword as they are reserved for special purposes.
    • Variable names case sensitive.
    • Eg: valid- apple, _name, $address1
    • Eg: invalid- 123apple, *roll, @email
  • In JS, a variable is defined using the var keyword
    • Eg: var a=5;
  • There are 2 types of variable in java depending on scopes
    • Local
      • They are defined inside a function or block.
      • It is accessible within the scope it is defined
      • Example:
function sum(a,b)
{
	var ans=a+b;
	console.log(ans); //prints 5
}
sum(2,3);
console.log(ans); //error

Output:

5
Uncaught ReferenceError: ans is not defined
at :7:13
  • Global
    • A variable defined in window scope, outside of all function scope.
    • It is accessible everywhere in the program.
    • Example:
var ans=2;
function sum(a,b)
{
	ans=a+b;
	console.log(ans);
}
sum(2,3);
console.log(ans);

Output:

5
5
  • Variable shadowing 
    • When a variable with the same name is defined in function and global scope then variable shadowing occurs.
    • That means that when we are dealing with variables in function scope then it gives priority to its local variable and overshadows the global variable.
    • Example:
var ans=2;
function sum(a,b)
{
	var ans=a+b;
	console.log(ans);
}
sum(2,3);
console.log(ans);

Output:

 5
 2
  • Undefined Vs Undeclared
    • Undefined
      • It’s a variable that has been declared but no value has been assigned to it yet.
      • Example:
var str;
console.log(str)


Output:

 undefined
  • Undeclared
    • It’s a variable that has not even been declared yet.
    • Example:
console.log(str)
 

Output:

 Uncaught ReferenceError: str is not defined
     at :1:13

JavaScript Hoisting

  • In JS, there is a phenomenon that takes place when var of function keyword is encountered which is known as Hoisting
  • When JS code gets parsed, whenever it encounters var or function keyword, it declares it in its execution context
  • Example 1: var weather is declared and defined in the global execution context, so it will get hoisted in the global scope.
function changeWeather()
{
	console.log("original weather: "+weather);
	weather="rainy";
	console.log("changing weather : "+weather);
}
var weather="sunny";
changeWeather();

Output:

original weather: sunny
changing weather: rainy
 

This will get treated as:

var weather="sunny";
function changeWeather()
{
	console.log("original weather: "+weather);
	weather="rainy";
	console.log("changing weather: "+weather);
}
changeWeather();

Example 2: Here weather is declared in both global and local execution contexts. So here the weather will be hoisted in both the scopes.

var weather="sunny";

function changeWeather()
{
	console.log("original weather: "+weather);
	var weather="rainy";
	console.log("changing weather: "+weather);
}

changeWeather();

Output:

original weather: undefined
changing weather: rainy 

This will get treated as:

var weather="sunny";

function changeWeather()
{
	var weather;
console.log("original weather: "+weather);
	weather="rainy";
	console.log("changing weather: "+weather);
}

changeWeather();

JavaScript Data Types

  • JS is a dynamically typed language and does not need to specify the data type explicitly of the variable.
  • There are 8 different types of data types in JS which are categorised in 2 categories
    • Primitive
      • Number, String, Boolean, Undefined, Null, Symbol
      • Example:
var num=23;
var string="hello";
var boolean=true;
var undef;
var nullValue=null;
var symbol=Symbol();

num
>>23

string
>>"hello"

boolean
>>true

undef
>>undefined

nullValue
>>null

symbol
>>Symbol()
  • Symbol
    • generally used for creating unique properties of objects
    • Example:
let sym1 = Symbol();
let sym2 = Symbol('foo');
let sym3 = Symbol('foo');
sym2===sym3

false
  • Undefined vs Null
    • undefined basically used when the variable’s value is yet not known.
    • null is used when we explicitly want to define a variable with null.
  • Non Primitive
    • Object
      • It is basically a collection of key-value pairs
      • It is defined within {}
      • Example:
var fruits ={
	'apple':'red',
	'watermelon':'green',
	'mango':'yellow'
};

fruits['apple'];

Output:

"red"
  • Arrays
    • It is used to store ordered data together.
    • It is defined within square brackets( [ ] ) and can have elements of different types
    • Example
var a=[1,true,'hello']
a[2]

Output:

"hello"

JavaScript Let and Const

  • Let and const keywords are also used for declaring variables.
  • It also stops hoisting.
    • Example
function changeWeather()
{
	console.log("original weather : "+weather);
	let weather="rainy";
	console.log("changed weather : "+weather);
}

changeWeather();

Output:

 Uncaught ReferenceError: Cannot access 'weather' before initialization
    at changeWeather (<anonymous>:3:36)
    at <anonymous>:8:1 
  • It enables the block-level scope.
    • Example
let weather="sunny";
function changeWeather()
{
	let weather="rainy";
	console.log("changed weather: "+weather);
}
changeWeather();
console.log("original weather: "+weather);

Output:

changed weather: rainy
original weather: sunny 
  • Const is used to declare the variables whose value is not going to change once defined.
    • Example
const weather="sunny";
function changeWeather()
{
	weather="rainy";
	console.log("changed weather : "+weather);
}
changeWeather();
console.log("original weather : "+weather);

Output

 Uncaught TypeError: Assignment to constant variable.
    at changeWeather (<anonymous>:4:9)
    at <anonymous>:7:1 

JavaScript Operators

  • Unary operator
    • It needs one operand
    • we have 2 major operators here i.e, increment and decrement and each one has 2 variations of postfix and prefix
    • Increment – to increase the value by 1
      • postfix: first assign then increment
      • prefix: first increment then assign
      • Example
var a=2; a++;
>>2

var a=2; ++a;
>>3
  • Decrement – to decrease the value by 1
    • postfix: first assign then decrement
    • prefix: first decrement then assign
    • Example
var a=2; a--;
>>2

var a=2; --a;
>>1
  • Arithmetic operator
    • It comprises all binary arithmetic operations, like add, subtract, multiply, divide, etc.
    • Another addition operator is modulus(%), which gives you the remainder.
    • Example:
var a=2,b=5;
console.log("a+b : "+ (10+5));
console.log("a-b : "+ (10-5));
console.log("a*b : "+ (10*5));
console.log("a/b : "+ (10/5));
console.log("a%b : "+ (10%5));

Output

a+b : 15
a-b : 5
a*b : 50
a/b : 2
a%b : 0
  • Shift operator
    • Two variations – left and right shift
    • left shift: shift bits in left direction for the specified value
    • right shift: shift bits in the right direction for the specified value
    • Example:
var a=8,b=2;
console.log("a<<b : "+ (a<<b));
console.log("a>>b : "+ (a>>b));

Output:

a<<b : 32
a>>b : 2
  • Relational operator
    • It comprises operators for comparisons
    • There are operators to check inequality i.e., < ,>, <=, >=
    • For equality check, we have 2 operators i.e., == and !=
    • Difference between == and ===
      • == allow type coercion i.e, one type can change into another at the time of comparison
      • === does not allow type coercion
      • Note:
NaN==NaN
>>false
NaN===NaN
>>false
+0 == -0
>>true
+0 === -0
>>true 
  • Example:
console.log('2=="2" : '+ (2=="2"));
console.log('2==="2" : '+ (2==="2"));
console.log('2!="2" : '+ (2!="2"));
console.log('2!=="2" : '+ (2!=="2"));
console.log('2>"2" : '+ (2>"2"));
console.log('2>="2" : '+ (2>="2"));
console.log('2<"2" : '+ (2<"2"));
console.log('2<="2" : '+ (2<="2"));

Output

2=="2" : true
 2==="2" : false
 2!="2" : false
 2!=="2" : true
 2>"2" : false
 2>="2" : true
 2<"2" : false
 2<="2" : true
  • Bitwise operator
    • It computes by going bit by bit
    • Both sides are checked irrespective of what the first expression computes to
    • 4 major bit operators are:
      • & – bitwise and, which returns 1 if both bits are 1 else 0.
      • | – bitwise or, which returns 1 if either of bits is 1 else 0.
      • ^ – bitwise xor, which returns 1 if both bits are different else 0.
      • ~ – bitwise not, which changes 1 to 0 and vice versa.
    • Example:
var a=8,b=2;
console.log('a&b : '+ (a&b));
console.log('a|b : '+ (a|b));
console.log('a^b : '+ (a^b));
console.log('~a : '+ (~a));

Output

a&b : 0
 a|b : 10
 a^b : 10
 ~a : -9
  • Logical operator
    • are used for conditions comparison that basically checks for the validity of them
    • They are also used in loops as part of termination conditions.
    • If the first condition is enough to give the final verdict, it will not evaluate the second one.
    • 3 operators are there:
      • && – logical AND, returns true when both conditions evaluate to true
      • || – logical OR, returns true when either of the conditions evaluates to true
      • ! – logical not, return true when the condition evaluates to false
    • Example:
var a=true,b=false;
console.log('a&&b : '+ (a&&b));
console.log('a||b : '+ (a||b));
console.log('!a : '+ (!a));

Output

a&&b : false
 a||b : true
 !a : false
  • Assignment operator and Ternary operator 
    • The assignment operator(=): is used to assign right-hand side value to the left-hand-side variable.
    • Ternary operator(?:) : An alternative of if-else. Condition is placed before? and if evaluates to true then LHS of the colon gets executed else RHS of colon will.
    • Example:
var a=2;
console.log('a=2 : '+ (a=2));
console.log((a==2)?console.log("ok"):console.log("not ok"));


Output

 a=2 : 2
 ok

JavaScript Conditions

  • if-else
    • consist of 2 keywords, if and else
    • This is a way where there are 2 paths possible depending upon a condition
    • if condition manipulates to true then, if gets executed otherwise code is else will execute
    • you can multiple else if followed by else if there are more possible paths.
    • Also nested if and else are possible
    • Example:
var a=5,b=6;
if(a+b==11)
	console.log("equal");
else
	console.log("not equal");


Output:
 equal
  • switch
    • It is an elegant way to replace multiple else-if

Syntax:

switch(expression)
{
    case val: ... ; 
              break;
    case val: ... ; 
              break;
    case val: ... ; 
              break;
    default: ...;
}
  • Here depending upon the answer evaluated by the condition, case code gets executed.
  • every case must be followed by break unless it is required not to as per logic. Otherwise, all cases will start executing from the matched case till either break is encountered or all cases get exhausted
  • default is optional and holds the code which should be executed if no catches gets matched.
  • val can be integer, char or String in java.
  • Example:
var day="sun";
switch(day)
	{
	    case "mon": console.log("Today is monday");
	                   break;
	    case "tues": console.log("Today is tuesday");
	                   break;
	    case "wed": console.log("Today is wednesday");
	                   break;
	    case "thurs": console.log("Today is thursday");
	                   break;
	    case "fri": console.log("Today is friday");
	                   break;
	    case "sat": console.log("Today is saturday");
	                   break;
	    case "sun": console.log("Today is sunday");
	                   break;
	    default : console.log("day is invalid!");
		}



Output:
 Today is sunday

JavaScript Loops

  • Three major loops are there: for, while and do-while
  • for loop :
    • It is best to use when we know the specified number of times the code should execute.
    • Syntax:

for( initialization; termination; update){

}

  • initialization – is used to initialize the variable, which is being used for iteration.
  • termination – comprises conditions that determine when iteration will continue.
  • update – how our variable will get updated.

Example:

for(var i=0;i<5;i++)
	console.log("current value of i : "+i);



Output

current value of i : 0
  current value of i : 1
  current value of i : 2
  current value of i : 3
  current value of i : 4
  • for loop variations – for in and for of
    • for of
      • used for iterables i.e, arrays and strings
      • Example
let fruits=['apple','peach','orange']
for(item of fruits){ console.log(item); }

Output:
 apple
 peach
 orange
  • for in
    • used for enumerables i.e, objects
    • it can also be used for iterables in which index acts as the key
    • Example
for(item in fruits){ console.log(item); }


Output:
 0
 1
 2
  • while loop :
    • It is best to use when we know the specified expression depending on whose value the code should execute.
    • Syntax:

while( expression ){

}

  • expression- is used to dictate the condition that is responsible for loop continuation.
  • Example:
var i=0;
while(i<5){
	console.log("current value of i : "+i);
	i++;
}

Output:
 current value of i : 0
 current value of i : 1
 current value of i : 2
 current value of i : 3
 current value of i : 4
  • do-while loop :
    • It is best to use when we know that at least code must execute once irrespective of the condition.
    • Syntax:

do{

}while( expression );

  • expression- is used to dictate the condition who is responsible for loop continuation.
  • Example:
var i=0;
do{
    console.log("current value of i : "+i);
    i++;
}while(i<5);



Output:
 current value of i : 0
 current value of i : 1
 current value of i : 2
 current value of i : 3
 current value of i : 4

JavaScript Function

  • It is referred to a code snippet that generally performs some operation
  • It helps in modularization of code and also enables reusability of it as and when required.
  • The function can be of 2 types in JS
    • Function expression:
      • Starts with a var and assignment operator
      • Example
var faith=function(){
 console.log("hope");
}
  • invocation : faith()
  • gets its definition at runtime
  • Function declaration :
    • starts will function keyword
    • Example
function happy(){
 console.log("I am grateful");
}
  • invocation : happy()
  • gets its definition at compile time

JavaScript Call, Apply and Bind

  • call() and apply() is implicitly used to call the function that is declared
function greet(){console.log("hello");}
greet()
>>VM1281:1 hello

greet.call()
>>VM1281:1 hello

greet.apply()
>>VM1358:1 hello

call and apply can be used to borrow methods of another object

let animal = { 
	name:'animal', 
	eat(){console.log("i "+name+" eating...")}
};

animal.eat()
>>VM2472:3 i  eating..

let human = { 
	name:'human'
};

animal.eat.call(human)
>>VM2510:3 i human eating...

animal.eat.apply(human)
>>VM2510:3 i human eating…

		passing arguments-
		let animal = { 
	name : 'animal', 
	eat(a,b){console.log("I "+this.name+" eating "+b+" "+a)}
};

animal.eat('apple',5);
>>VM2828:3 I animal eating 5 apple

animal.eat.call(human,'orange',2);
>>VM2828:3 I human eating 2 orange

animal.eat.apply(human,['orange',2]);
>>VM2828:3 I human eating 2 orange

bind returns the function definition that can be used later

let animal = { 
	name:'animal', 
	eat(a,b){console.log("I "+this.name+" eating "+b+" "+a)}
};

let human = { 
	name:'human'
};

let humanEat = animal.eat.bind(human)
humanEat('mango',10)
>>VM3076:3 I human eating 10 mango

JavaScript This keyword

  • this is an object whose property is the function
    • ex : obj.func(this)
  • function a is the property of window object
function a()
{ console.log(this); }
a()

>>VM808:2 Window {parent: Window, opener: null, top: Window, length: 4, fra

this gives excess of the object to its methods

var obj={
  name:"Sam",
  sing(){
    console.log(this.name+" singing");
  }
}

obj.sing();


Output
 Sam singing

executes same code on multiple objects

function getName() {
  console.log(this.name)
}
 
var name = 'Sunny';
var obj1 = { name: 'Cassy', getName: getName}
var obj2 = { name: 'Jacob', getName: getName}
 
getName()
obj1.getName()
obj2.getName()


Output
 Sunny
 Cassy
 Jacob

this is not lexically scoped rather it is dynamically scoped, which depends on where it is called

const obj = {
  name:'Sam',
  sing(){
    console.log('a',this);
    var anotherfunc=function(){
      console.log('b',this);
    }
    anotherfunc();
  }
}

obj.sing();


Output
 a {name: "Sam", sing: Æ’}
 b Window {parent: Window, opener: null, top: Window, length: 4, frames: Window, …}

JavaScript Arrow functions

To make this lexically bound, we can use arrow functions

const obj = {
  name:'Sam',
  sing(){
    console.log('a',this);
    var anotherfunc = () => {
      console.log('b',this);
    }
    anotherfunc();
  }
}

obj.sing();

Output
 a {name: "Sam", sing: Æ’}
 b {name: "Sam", sing: Æ’}

This brings us to the end of this article where we learned about the basics of JavaScript. To enhance your skills, you can take our free JavaScript Course. Click the banner below to know more.

Faizan Parvez
Faizan has been working as an Instructor of Data Structure and Algorithm for the last 1 year. He has expertise in languages such as Java, JavaScript, etc. He is a Subject Matter Expert in the field of Computer Science and a Competitive programmer. He has been working in technical content development and is a Research Analyst.

Leave a Comment

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

Great Learning Free Online Courses
Scroll to Top