JavaScript Fundamentals – Complete Beginner to Advanced Guide (2026)

Table of Contents

Introduction to JavaScript

JavaScript is one of the most widely used programming languages for web development.

HTML creates the structure of a webpage.

CSS provides styling.

JavaScript adds:

  • Interactivity
  • User Input Handling
  • Dynamic Content Updates
  • Form Validation
  • Animations
  • API Integration
  • Real-Time Updates

Without JavaScript, websites would be static and less interactive.


Why Learn JavaScript?

JavaScript powers:

  • Websites
  • Web Applications
  • Mobile Apps
  • Desktop Applications
  • Games
  • APIs
  • Server-Side Development using Node.js

Popular platforms built with JavaScript include:

  • Netflix
  • Facebook
  • Google
  • PayPal

Ways to Add JavaScript

1. Inline JavaScript

<button onclick="alert('Hello World')">
Click Me
</button>

2. Internal JavaScript

<script>

alert("Welcome");

</script>

3. External JavaScript

on index.html

<script src="script.js"></script>
script.js
alert("External JavaScript");

JavaScript Output Methods

alert()

alert("Welcome to JavaScript");

console.log()

console.log("Hello Developers");

document.write()

document.write("Hello World");

Variables in JavaScript

Variables store data values.


Using var

var name = "Akshay";

Using let

let age = 25;

Using const

const PI = 3.14159;

Rules for Creating Variables in JavaScript

A variable name (identifier) must follow specific rules.


1. Variable Names Can Contain

– Letters (A-Z, a-z)

let name = "Akshay";

- Numbers (0-9)
let student1 = "Rahul";
– Underscore (_)
let first_name = "Akshay";
– Dollar Sign ($)
let $price = 100;

2. Variable Names Cannot Start with a Number

– Invalid

let 123name = "Akshay";
– Valid
let name123 = "Akshay";

3. No Spaces Allowed

– Invalid

let first name = "Akshay";
– Valid
let firstName = "Akshay";
or
let first_name = "Akshay";

4. Reserved Keywords Cannot Be Used

JavaScript keywords cannot be variable names.

– Invalid

let if = 10;
let for = 20;
let while = 30;
Some reserved words:
if
else
for
while
switch
return
class
function
const
let
var

5. Variable Names Are Case Sensitive

These are different variables:

let name = "Akshay";
let Name = "Rahul";
let NAME = "Amit";

JavaScript treats all three separately.


6. Use Meaningful Names

– Poor Practice

let x = 100;
let y = 50;
– Better Practice
let totalMarks = 100;
let passingMarks = 50;

7. Use Camel Case (Recommended)

JavaScript convention:

let firstName;
let studentAge;
let totalMarks;
let accountBalance;
This style is called camelCase.

8. Constants Should Use Uppercase (Optional Convention)

const PI = 3.14159;
const MAX_USERS = 100;

Examples of Valid Variable Names

let name;
let firstName;
let student1;
let totalMarks;
let _count;
let $price;
let userEmail;

Examples of Invalid Variable Names

let 123name;
let first name;
let @email;
let if;
let for;

Best Practices for Creating Variables in JavaScript

// Good
let studentName = "Akshay";
let mobileNumber = "9876543210";
let totalMarks = 450;

// Avoid
let a = "Akshay";
let b = "9876543210";
let c = 450;
Quick Summary
Rule Example
Start with letter, _ or $ name, _count, $price
Cannot start with number 123name
No spaces allowed first name
No reserved keywords let if = 10;
Case sensitive nameName
Use meaningful names studentName
Prefer camelCase totalMarks

Recommended naming style for modern JavaScript: use let and const with meaningful camelCase variable names.


Difference Between var, let and const

Feature var let const
Redeclare Yes No No
Reassign Yes Yes No
Scope Function Block Block

JavaScript Data Types

String

let name = "Akshay";

Number

let marks = 85;

Boolean

let status = true;

Undefined

let city;

Null

let value = null;

Array

let subjects = ["HTML","CSS","JavaScript"];

Object

let student = {
name:"Akshay",
age:25
};

Operators in JavaScript

Arithmetic Operators

let a = 10;
let b = 5;

console.log(a+b);
console.log(a-b);
console.log(a*b);
console.log(a/b);
console.log(a%b);

Comparison Operators

console.log(10>5);
console.log(10<5);
console.log(10==5);
console.log(10!=5);

Logical Operators

let x = true;
let y = false;

console.log(x && y);
console.log(x || y);
console.log(!x);

User Input

Using prompt()

let name = prompt("Enter Your Name");

alert(name);

Conditional Statements

if Statement

let age = 18;

if(age>=18){
alert("Eligible");
}

if else

let marks = 40;

if(marks>=35){
console.log("Pass");
}
else{
console.log("Fail");
}

else if Ladder

let marks = 75;

if(marks>=80){
console.log("A Grade");
}
else if(marks>=60){
console.log("B Grade");
}
else{
console.log("C Grade");
}

Switch Statement

let day = 2;

switch(day){

case 1:
console.log("Monday");
break;

case 2:
console.log("Tuesday");
break;

default:
console.log("Invalid Day");

}

Loops in JavaScript


for Loop

for(let i=1;i<=5;i++){
console.log(i);
}

while Loop

let i=1;

while(i<=5){

console.log(i);

i++;

}

do while Loop

let i=1;

do{

console.log(i);

i++;

}
while(i<=5);

Functions

Functions are reusable blocks of code.


Simple Function

function welcome(){

alert("Welcome");

}

welcome();

Function with Parameters

function add(a,b){

return a+b;

}

console.log(add(10,20));

Arrays

Arrays store multiple values.

let colors = ["Red","Green","Blue"];

console.log(colors[0]);

Array Methods

colors.push("Yellow");

colors.pop();

colors.shift();

colors.unshift("Black");

Objects

Objects store data as key-value pairs.

let student = {

name:"Akshay",

age:25,

course:"Web Design"

};

console.log(student.name);

String Methods

let name = "JavaScript";

console.log(name.length);

console.log(name.toUpperCase());

console.log(name.toLowerCase());

Math Object

console.log(Math.PI);

console.log(Math.sqrt(25));

console.log(Math.random());

Date Object

let today = new Date();

console.log(today);

DOM (Document Object Model)

The DOM allows JavaScript to access and modify HTML elements.

The Document Object Model (DOM) is a programming interface that represents an HTML (or XML) document as a hierarchical tree of nodes, where each tag, text, and attribute becomes an object that scripts can read and modify. JavaScript interacts with this tree to dynamically change structure, style, and content, enabling rich, interactive web applications.

What is the DOM?

  • The DOM treats the entire webpage as a tree starting from a root document node, with elements like <html>, <head>, and <body> as children.
  • Every element (<div>, <p>, <a>), text node, and attribute can be accessed and manipulated via JavaScript, allowing scripts to add, remove, or modify parts of the page.
  • The DOM is language-independent: JavaScript is most common in browsers, but the model itself is defined so that different languages could use it.

Why DOM manipulation matters

  • Interactivity: Enables dynamic behaviors such as dropdown menus, tabs, modals, form validation feedback, and interactive dashboards.
  • Real-time updates: Content can be updated without a full page reload (e.g., updating a cart count, chat messages, live scores), improving perceived performance.
  • Partial updates instead of reloads: Combined with AJAX / fetch, only specific sections of the DOM are updated, reducing bandwidth usage and server load.
  • Enhanced UX: Smooth transitions, inline form validation, live search suggestions, and conditional UI states all rely on DOM manipulation.

Core DOM access and modification methods

  • Selecting elements
    • document.getElementById(id)

– Returns the element whose id matches the given string (fast, unique).

    • document.getElementsByClassName(className)

– Returns an HTMLCollection of elements with a given class.

    • document.getElementsByTagName(tagName)

– Returns elements by tag name (e.g., “p”, “button”).

    • document.querySelector(selector)

– Returns the first element matching a CSS selector (e.g., “.btn.primary”, “#loginForm”).

    • document.querySelectorAll(selector)

– Returns a static NodeList of all elements matching a CSS selector.

  • Reading and updating content
    • element.innerHTML – Gets/sets HTML markup inside an element (can insert nested tags).
    • element.innerText / element.textContent – Gets/sets plain text content.
    • element.value – Reads or changes the value of form fields (<input>, <textarea>, <select>).
  • Styling and attributes
    • element.style.propertyName – Applies inline styles (e.g., element.style.color = “red”;).
    • element.classList.add(), .remove(), .toggle() – Adds/removes CSS classes, preferred over editing style directly.
    • element.setAttribute(name, value) / getAttribute(name) – Manages attributes like src, href, alt, data-*.
  • Creating and removing elements
    • document.createElement(“div”) – Creates a new element node.
    • parent.appendChild(child) / parent.prepend(child) – Inserts elements into the DOM tree.
    • parent.removeChild(child) or element.remove() – Removes elements from the DOM.

Selecting Elements

document.getElementById("title");
document.querySelector(".box");

Changing Content

document.getElementById("title")
.innerHTML="Welcome";

Changing CSS

document.getElementById("title")
.style.color="red";

Event Handling

Events occur when users interact with a webpage.


Button Click Event

<button onclick="showMessage()">
Click Me
</button>
function showMessage(){

alert("Button Clicked");

}

Mouse Event

element.addEventListener(
"mouseover",
function(){

alert("Mouse Over");

});

Form Validation Example

<input type="text" id="username">

<button onclick="validate()">
Submit
</button>
function validate(){

let user =
document.getElementById("username").value;

if(user==""){

alert("Username Required");

}

}

ECMAScript 6 (ES6) – Modern JavaScript

What is ES6?

ES6 (ECMAScript 2015) is a major update to JavaScript that introduced many powerful features, making code cleaner, shorter, and easier to maintain.

Before ES6, developers primarily used var and traditional functions. ES6 introduced features like:

  • let and const
  • Arrow Functions
  • Template Literals
  • Destructuring
  • Spread Operator
  • Rest Parameters
  • Classes
  • Modules
  • Promises

Today, almost all modern JavaScript applications use ES6+ syntax.


Why Was ES6 Introduced?

ES6 was introduced to:

  • Reduce code complexity
  • Improve readability
  • Support modern application development
  • Make JavaScript more powerful
  • Simplify asynchronous programming

let and const

Before ES6:

var name = "Akshay";

ES6 introduced:

let name = "Akshay";
const PI = 3.14159;

Difference

Keyword Can Reassign Can Redeclare
var Yes Yes
let Yes No
const No No

Template Literals

Before ES6:

let name = "Akshay";

console.log("Welcome " + name);

Using ES6:

let name = "Akshay";

console.log(`Welcome ${name}`);

Benefits:

  • Cleaner syntax
  • Easier string formatting
  • Supports multiline strings

Arrow Functions

Traditional Function:

function add(a,b){
    return a+b;
}

ES6 Arrow Function:

const add = (a,b) => a+b;

console.log(add(10,20));

Benefits:

  • Shorter syntax
  • Cleaner code
  • Widely used in React and modern JavaScript

Destructuring

Extract values from arrays or objects easily.

Array Destructuring

const colors = ["Red","Green","Blue"];

const [first, second] = colors;

console.log(first);

Object Destructuring

const student = {
    name:"Akshay",
    age:25
};

const {name, age} = student;

console.log(name);

Spread Operator (…)

The spread operator expands arrays or objects.

const numbers1 = [1,2,3];

const numbers2 = [...numbers1,4,5];

console.log(numbers2);

Output:

[1,2,3,4,5]

Rest Parameters

Collect multiple values into one parameter.

function total(...numbers){

    let sum = 0;

    for(let num of numbers){
        sum += num;
    }

    return sum;
}

console.log(total(10,20,30));

Classes in ES6

ES6 introduced Object-Oriented Programming syntax.

class Student{

    constructor(name){

        this.name = name;
    }

    display(){

        console.log(this.name);
    }

}

const s1 = new Student("Akshay");

s1.display();

JavaScript Modules

Modules help organize code into separate files.

math.js

export function add(a,b){

    return a+b;

}

app.js

import {add} from './math.js';

console.log(add(10,20));

Benefits of ES6

  • Cleaner syntax
  • Improved readability
  • Better performance
  • Easier maintenance
  • Industry standard
  • Essential for React, Node.js, and Next.js

JSON (JavaScript Object Notation)

What is JSON?

JSON stands for JavaScript Object Notation.

It is a lightweight format used for storing and exchanging data between:

  • Browser and Server
  • APIs and Applications
  • Frontend and Backend Systems

JSON is one of the most widely used data formats on the internet.


Why JSON is Important?

JSON is used in:

  • REST APIs
  • AJAX Requests
  • Web Services
  • Database Applications
  • Mobile Applications

Whenever data travels between a server and a browser, JSON is commonly used.


JSON Structure

JSON stores data as key-value pairs.

Example:

{
    "name":"Akshay",
    "age":25,
    "city":"Nashik"
}

JavaScript Object vs JSON

JavaScript Object

const student = {

    name:"Akshay",
    age:25

};
JSON
{
    "name":"Akshay",
    "age":25
}

Difference

JavaScript Object JSON
Keys may be unquoted Keys must be quoted
Used in JavaScript code Used for data exchange
Supports functions Does not support functions

Converting Object to JSON

JSON.stringify()

const student = {

    name:"Akshay",
    age:25

};

const jsonData =
JSON.stringify(student);

console.log(jsonData);

Output:

{"name":"Akshay","age":25}

Converting JSON to Object

JSON.parse()

const jsonData =
'{"name":"Akshay","age":25}';

const student =
JSON.parse(jsonData);

console.log(student.name);

Output:

Akshay

JSON Array Example

[
    {
        "name":"Akshay",
        "course":"Web Design"
    },
    {
        "name":"Rahul",
        "course":"JavaScript"
    }
]

Real-World JSON Example

Data returned by an API:

{
    "id":101,
    "product":"Laptop",
    "price":45000,
    "stock":true
}

JavaScript can read this JSON and display it on a webpage dynamically.


ES6 and JSON in Modern Development

Modern technologies heavily depend on ES6 and JSON:

Technology Uses ES6 Uses JSON
React
Next.js
Node.js
Express.js
REST APIs
MongoDB Applications

Error Handling

try{
let x=10/0;
}
catch(error){
console.log(error);
}

Timers

setTimeout()

setTimeout(function(){

alert("Hello");

},3000);

setInterval()

setInterval(function(){
console.log("Running");
},1000);

Complete JavaScript Project Example

Build a Student Grade Calculator using:

  • Variables
  • Operators
  • Functions
  • DOM
  • Events

<!DOCTYPE html>
<html>
<head>
<title>Grade Calculator</title>
</head>

<body>

<h1>Grade Calculator</h1>

<input type=”number” id=”marks”>

<button onclick=”calculateGrade()”>
Calculate
</button>

<h2 id=”result”></h2>

<script>

function calculateGrade(){

let marks =
document.getElementById(“marks”).value;

let grade=””;

if(marks>=80){
grade=”A”;
}
else if(marks>=60){
grade=”B”;
}
else if(marks>=35){
grade=”C”;
}
else{
grade=”Fail”;
}

document.getElementById(“result”)
.innerHTML=”Grade : “+grade;

}

</script>

</body>
</html>


Common Interview Questions

What is JavaScript?

Difference between var, let and const?

What are JavaScript Data Types?

What is DOM?

Difference between == and ===?

What are Arrow Functions?

What is Event Handling?

What is JSON?

What is Hoisting?

What is Closure?


Best Practices

  • Use let and const instead of var
  • Keep functions small and reusable
  • Validate user input
  • Avoid global variables
  • Use external JavaScript files
  • Follow ES6+ standards

Examples to Check

Download Here some basic examples.

You may also like...

Leave a Reply

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