JavaScript Complete Guide: Basics to Advanced with Examples
If you want to learn web development, app development, or programming, JavaScript is a language that is almost impossible to ignore. Today, millions of websites and web applications around the world use JavaScript. Whenever you click a button on a website, submit a form, open a menu, use an image slider, or see data update without reloading the page, JavaScript is working behind the scenes.
Many beginners get confused after learning HTML and CSS. They often ask what they should learn next. If you have the same question, the answer is JavaScript. HTML creates the structure of a website, CSS makes it look beautiful, and JavaScript brings the website to life. That is why JavaScript is considered the most important programming language for web development.In this complete guide, we will learn JavaScript from the very beginning and slowly move to advanced concepts. Every topic will be explained in simple English so that even beginners can understand everything easily.
What Is JavaScript?
JavaScript is a high-level programming language that is used to make websites interactive.Let's understand it in simple words.
If you use only HTML, your website will look like a simple page.If you add CSS, your website will look beautiful. But if you want animations, popups, calculators, login validation, search bars, dark mode, image sliders, or live updates, then you need JavaScript.
That is why JavaScript is also called the brain of a website. Today, JavaScript is not only used for websites. It is also used to build mobile applications, desktop software, browser extensions, games, AI tools, APIs, and servers.
Why Should You Learn JavaScript?
There are many reasons to learn JavaScript today. The first reason is that every modern browser supports JavaScript. The second reason is that JavaScript is in very high demand, and companies almost always look for JavaScript skills when hiring web developers.
The third reason is that with one programming language, you can build frontend applications, backend applications, mobile apps, and desktop software. If you want to become a freelancer, get a remote job, or build your own projects, JavaScript is an excellent choice
How Does JavaScript Work?
JavaScript runs inside the browser. When a user opens a website, the browser first reads the HTML. Then it applies the CSS.
Finally, it executes the JavaScript code. JavaScript controls the DOM. DOM stands for Document Object Model. Let's understand it in simple words. Every element on a website, such as a heading, image, button, paragraph, or form, can be changed using JavaScript.
That is why a website can update without reloading the page. This process gives users a fast and smooth experience.
Where Does JavaScript Run?
JavaScript mainly runs in two places. Inside the browser For example, Chrome, Edge, Firefox, and Safari. On the server With the help of Node.js, JavaScript can also run on the server. This means you can build a complete web application using just one programming language.
What Do You Need to Run JavaScript?
You only need a few basic things to start learning JavaScript.
- A computer or laptop
- Google Chrome browser
- Visual Studio Code editor
- That's all.
Your First JavaScript Program
First, create an HTML file.
Write the following code inside it.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1>Hello JavaScript</h1>
<script>
alert("Welcome to JavaScript");
</script>
</body>
</html>
Now save the file and open it in your browser. As soon as the page opens, a popup message will appear on the screen.
This is your first JavaScript program.
How to Print Output in the Console
The console is used a lot while learning programming.
console.log("Hello World");
Open your browser.
Right-click with your mouse.
Click on Inspect.
Open the Console tab.
Now you will see Hello World printed in the console.
How to Add JavaScript to HTML
There are two ways to add JavaScript to an HTML file.
The first method is Internal JavaScript.
<script>
console.log("Internal JavaScript");
</script>
The second method is External JavaScript.
First, create a file.
script.js
Write the following code inside it.
console.log("External JavaScript");
Now connect it to your HTML file.
<script src="script.js"></script>
In professional projects, you should always use an external JavaScript file because it keeps your code clean and makes it easier to manage.
What Are Variables?
In programming, a variable is like a container that stores data. If you want to use a value multiple times or change its value in the future, you use a variable.
Let's understand this with a real-life example.
Suppose a student's name is "Rahul." If we want to use this name in a program, we store it in a variable.
let studentName = "Rahul";
console.log(studentName);
Output
Rahul
Here, studentName is the variable, and Rahul is its value.
How to Create Variables in JavaScript
JavaScript uses three keywords to create variables.
var
let
const
In modern JavaScript projects, developers mainly use let and const. var is the older method, and it is not recommended for new projects.
Use let when the value may change in the future.
Example
let age = 20;
console.log(age);
age = 21;
console.log(age);
Output
20
21
Here, the value of age changes later, so let is used.
const Keyword
Use const when the value will never change.
Example
const country = "India";
console.log(country);
If you try to change the value of country later, JavaScript will show an error.
That is why using const for fixed values is considered a best practice.
var Keyword
Example
var city = "Delhi";
console.log(city);
This also creates a variable, but it has some problems. That is why var is usually avoided in modern JavaScript.
If you are a beginner, focus only on let and const.
Variable Naming Rules
A variable name should be meaningful.
Good Examples
let firstName = "Ali";
let totalMarks = 500;
let userAge = 22;
Bad Examples
let a = 10;
let xyz = "Hello";
let data1 = "Test";
Always choose a variable name that clearly explains its purpose.
JavaScript Data Types
A data type tells you what kind of value is stored inside a variable. JavaScript has many data types.
- String
- Number
- Boolean
- Undefined
- Null
- Object
- Array
- BigInt
- Symbol
For beginners, the first five data types are the most important.
String
A string stores text.
Example
let name = "Kabir";
console.log(name);
Output
Kabir
Number
A number stores both integer and decimal values.
Example
let marks = 95;
let price = 199.99;
console.log(marks);
console.log(price);
Boolean
A Boolean stores only two values.
true
false
Example
let isLoggedIn = true;
console.log(isLoggedIn);
It is mostly used in conditions and login systems.
Undefined
A variable is undefined when it is created but no value is assigned to it.
Example
let mobile;
console.log(mobile);
Output
undefined
Null
Null means an intentionally empty value.
Example
let profileImage = null;
console.log(profileImage);
How to Check a Data Type
JavaScript uses the typeof operator to check the data type.
Example
let language = "JavaScript";
console.log(typeof language);
Output
string
Another example.
let age = 25;
console.log(typeof age);
Output
number
This is very useful while debugging your code.
JavaScript Operators
Operators are used for calculations and comparisons. The most important operators are:
- Arithmetic Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
Arithmetic Operators
These operators are used for mathematical calculations.
Addition
let a = 20;
let b = 10;
console.log(a + b);
Subtraction
console.log(a - b);
Multiplication
console.log(a * b);
Division
console.log(a / b);
Remainder
console.log(a % b);
Power
console.log(a ** 2);
Assignment Operators
Example
let total = 100;
total += 50;
console.log(total);
Output
150
In the same way, there are also assignment operators for subtraction, multiplication, and division.
Comparison Operators
These operators compare two values.
Example
let x = 10;
let y = 20;
console.log(x == y);
console.log(x != y);
console.log(x < y);
console.log(x > y);
console.log(x >= y);
console.log(x <= y);
The result is always true or false.
Strict Equality Operator
In JavaScript, == and === are different.
Example
console.log(10 == "10");
Output
true
But
console.log(10 === "10");
Output
false
Professional developers always use === because it compares both the value and the data type.
Logical Operators
Logical operators are used to combine conditions.
AND
let age = 20;
console.log(age > 18 && age < 30);
OR
console.log(age > 18 || age > 60);
NOT
console.log(!(age > 18));
These operators are widely used in login systems, forms, and permission-based applications.
How to Take Input from the User
In JavaScript, you can use prompt() to take input from the user.
Example
let userName = prompt("Enter Your Name");
console.log(userName);
When the page opens, the browser will display an input box.
Whatever the user enters will be stored in the variable.
How to Show an Alert Message
Example
alert("Welcome To My Website");
This displays a popup message in the browser.
What Are Conditions?
In real life, we make decisions based on conditions every day. If it rains, I will take an umbrella. If I pass the exam, I will celebrate.
If I have enough money, I will buy a mobile phone. Programming works in the same way. In JavaScript, conditions help the program decide which code should run in different situations.
if Statement
The if statement is used when you want to run code only if a condition is true.
Example
let age = 20;
if (age >= 18) {
console.log("You can vote.");
}
Output
You can vote.
Here, the value of age is greater than or equal to 18, so the message is printed.
if else Statement
If the condition is false, the else block will run.
Example
let age = 15;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote.");
}
Output
You cannot vote.
else if Statement
Use else if when you need to check multiple conditions.
Example
let marks = 82;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 50) {
console.log("Grade C");
} else {
console.log("Fail");
}
This allows a program to handle different situations.
Real-Life Example
On an online shopping website, if the total amount is more than 1000, the customer may get free delivery.
Example
let totalAmount = 1500;
if (totalAmount >= 1000) {
console.log("Free Delivery Available");
} else {
console.log("Delivery Charge Applied");
}
Examples like this are commonly used in e-commerce websites.
Switch Statement
When you need to check multiple values of the same variable, using a switch statement is easier.
Example
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid Day");
}
Output
Wednesday
What Are Loops?
A loop is used when you want to run the same code multiple times. Suppose you want to print numbers from 1 to 100. If you write console.log() one hundred times, it will take a lot of time. A loop solves this problem.
for Loop
The for loop is the most commonly used loop.
Example
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Output
1
2
3
4
5
6
7
8
9
10
while Loop
A while loop runs as long as the condition is true.
Example
let number = 1;
while (number <= 5) {
console.log(number);
number++;
}
do while Loop
A do while loop always runs at least once.
Example
let count = 1;
do {
console.log(count);
count++;
} while (count <= 5);
What Are Functions?
A function is a reusable block of code.
If you need to use the same code again and again, you can place it inside a function.
This makes your code cleaner and easier to manage.
Simple Function
Example
function welcome() {
console.log("Welcome To My Website");
}
welcome();
Every time you call the welcome function, the message will be printed.
Function with Parameters
Parameters allow you to pass values into a function.
Example
function greet(name) {
console.log("Hello " + name);
}
greet("Rahul");
greet("Aman");
greet("Sara");
Output
Hello Rahul
Hello Aman
Hello Sara
Function Return Value
Sometimes a function does not only print output but also returns a value.
Example
function add(a, b) {
return a + b;
}
let total = add(10, 20);
console.log(total);
Output
30
This method is widely used in real-world projects.
What Are Arrays?
An array is used to store multiple values of the same type in a single variable.
Example
let fruits = ["Apple", "Banana", "Orange", "Mango"];
console.log(fruits);
Accessing the First Item of an Array
Example
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]);
Output
Apple
Second item
console.log(fruits[1]);
Third item
console.log(fruits[2]);
Adding a New Item to an Array
Example
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
Removing the Last Item from an Array
Example
fruits.pop();
This removes the last item from the array.
What Are Objects?
An object stores multiple related pieces of information inside a single variable.
Example
let student = {
name: "Ali",
age: 20,
course: "JavaScript"
};
console.log(student);
Accessing Object Values
Example
console.log(student.name);
console.log(student.age);
console.log(student.course);
Output
Ali
20
JavaScript
Objects are very important in real-world projects.
For example, a user's name, email, mobile number, and address can all be stored inside a single object.
Practical Example
Let's calculate a student's result.
let student = {
name: "Rahul",
marks: 92
};
if (student.marks >= 50) {
console.log(student.name + " Passed");
} else {
console.log(student.name + " Failed");
}
What Is the DOM?
DOM stands for Document Object Model. When a browser loads an HTML page, it treats every element on that page as an object. JavaScript can access these objects and make changes to them. Let's understand it in simple words. If HTML is the structure of a website, then the DOM is the live version of that structure that JavaScript controls. That is why you can change text, replace images, disable buttons, and add new elements without reloading the page.
How to Select an HTML Element
First, create an HTML file.
<h1 id="title">Welcome</h1>
Now select it using JavaScript.
let heading = document.getElementById("title");
console.log(heading);
This code selects the heading element.
Changing Text
Example
let heading = document.getElementById("title");
heading.innerText = "Welcome To My Website";
Now the heading will automatically change in the browser.
Changing HTML Content
If you also want to add HTML tags, use innerHTML.
Example
document.getElementById("title").innerHTML = "<span>Hello JavaScript</span>";
Changing CSS
You can also change CSS using JavaScript.
Example
let heading = document.getElementById("title");
heading.style.color = "blue";
heading.style.fontSize = "40px";
This changes the color and font size of the heading.
Button Click Event
The most common event on a website is the click event.
HTML
<button onclick="showMessage()">Click Me</button>
JavaScript
function showMessage() {
alert("Button Clicked");
}
When the user clicks the button, an alert message will appear.
Event Listener
In professional projects, addEventListener() is used instead of onclick.
HTML
<button id="btn">Click Me</button>
JavaScript
let button = document.getElementById("btn");
button.addEventListener("click", function () {
alert("Hello User");
});
This is the modern and recommended method.
Getting Input from a Text Field
HTML
<input type="text" id="username">
<button onclick="showName()">Submit</button>
JavaScript
function showName() {
let name = document.getElementById("username").value;
alert(name);
}
Changing an Image with the DOM
HTML
<img id="photo" src="image1.jpg">
JavaScript
document.getElementById("photo").src = "image2.jpg";
JavaScript Frameworks and Libraries
Once you have a good understanding of JavaScript basics, you can start learning frameworks and libraries.
React
React is the most popular frontend library. It is used by Facebook, Instagram, and many other large companies.
Vue
Vue is considered beginner-friendly. It has a simple syntax and can be used for both small and large projects.
Angular
Angular is a complete frontend framework that is mainly used for enterprise-level applications.
Next.js
Next.js is a framework built on top of React. It is very popular for building SEO-friendly websites and high-performance web applications.
Best Code Editors for Learning JavaScript
Visual Studio Code
Visual Studio Code is the most popular editor and the best choice for beginners. Its extensions make coding easier and more productive.
Frequently Asked Questions
Is JavaScript Easy for Beginners?
Yes. If you have basic knowledge of HTML and CSS and practice every day, learning JavaScript is not difficult.
How Long Does It Take to Learn JavaScript?
If you practice for one to two hours every day, you can learn the basics well in one to two months. Advanced concepts and real-world projects require continuous practice.
Can I Get a Job by Learning Only JavaScript?
Learning JavaScript along with HTML, CSS, Git, and one frontend framework such as React can greatly increase your chances of getting a job or finding freelancing opportunities.
Can JavaScript Build Mobile Apps?
Yes. With frameworks like React Native, you can build Android and iOS applications.
Is JavaScript Used for Backend Development?
Yes. With the help of Node.js and Express.js, you can build backend applications, APIs, and servers.
What Should I Learn After JavaScript?
After completing JavaScript, a good next step is to learn Git, GitHub, React, Node.js, Express.js, and MongoDB.