Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

JavaScript Tutorial for Beginners

Published On: August 11, 2025

JavaScript Tutorial for Beginners

Starting a web development career can be daunting the first time around, given the enormity of the puzzle that lies ahead. The sheer number of languages, frameworks, and tools makes the pursuit overwhelming to new entrants. Many are at a loss as to how to start, what to learn first, and how to create those truly interactive web pages.

We’ll take you from the very basics of JavaScript for starters to more advanced topics such as asynchronous programming, equipping you to create dynamic and interactive web applications. In this JavaScript tutorial, we’ll make use of easy-to-understand JavaScript examples and simplify complicated concepts, providing a clear grasp of this fundamental web technology. Dive deep into our extensive JavaScript Course Syllabus to learn more.

What is JavaScript? And Why You Should Learn It

JavaScript (JS) is a high-level, interpreted language that is one of the three primary technologies of the World Wide Web, the other two being HTML and CSS. It provides interactive web pages and is a crucial constituent of frontend web development.

Brief History: Developed in 1995 by Brendan Eich at Netscape, originally called “Mocha.” Not having anything to do with Java, despite the name. Officially specified as ECMAScript (ES).

Where JavaScript Runs:

  • Web Browsers: The place of origin, where all the major browsers have a JavaScript engine (e.g., V8 in Chrome, SpiderMonkey in Firefox). Where your client-side JavaScript runs.
  • Node.js: Environments under which JavaScript can execute on servers, making backend JavaScript programming possible.
  • Desktop Apps: Environments such as Electron enable you to create cross-platform desktop apps (e.g., VS Code, Slack).
  • Mobile Apps: Environments such as React Native and NativeScript permit JavaScript for mobile app development.
  • IoT Devices & More: Its reach only widens.
What You Can Do with JavaScript:
  • Make web pages interactive (forms, animations, galleries).
  • Create full-fledged web applications (Single-Page Applications with frameworks).
  • Create server-side applications and APIs.
  • Build games, browser extensions, and much more.

JavaScript learning leads to many web development career opportunities. Enroll in our JavaScript online course and kickstart your career in web development.

Setting Up Your JavaScript Development Environment

Two core tools are all you need to begin writing your very first JavaScript code:

A Code Editor: This is where you create your code.

  • Visual Studio Code (VS Code): Most recommended for JavaScript development. Free, robust, and provides great support for JavaScript with the likes of syntax highlighting, autocompletion, and a built-in terminal.
  • Download VS Code: code.visualstudio.com

A Web Browser with Developer Tools: Needed to run and debug your JavaScript.

  • Google Chrome (Chrome DevTools): Hit F12 (or right-click and select “Inspect”) to show the DevTools. The “Console” is where your JavaScript output and errors will appear.
  • Alternatives: Mozilla Firefox, Microsoft Edge.

Your First JavaScript Program: “Hello, World!”

Let’s create the classic “Hello, World!” and see JavaScript in action. We’ll use console.log(), a core function to debug JavaScript and print to the browser’s console.

Embedding JavaScript in HTML:

There are three ways to include JavaScript in your HTML. For modern JavaScript development, external files are the standard.

Inline JavaScript (Discouraged for most cases):
  • JavaScript code directly within an HTML tag’s attribute (e.g., onclick).
  • Use Case: Very simple, one-off interactions.

Example:

<button onclick=”alert(‘Hello from inline JS!’);”>Click Me</button>

 Internal JavaScript (Inside <script> tags):
  • JavaScript code placed directly within <script> tags inside your HTML file.
  • Best placed just before the closing </body> tag to ensure HTML content loads first.

Example (index.html):

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Internal JS Example</title>

</head>

<body>

    <h1>My First Internal JS Page</h1>

    <p>Check the browser console!</p>

    <script>

        // This is an internal JavaScript block

        console.log(“Hello, World! From internal script.”);

        alert(“Welcome to my first JavaScript page!”); // This will show a popup

    </script>

</body>

</html>

Save this as index.html and open it in your browser. Open DevTools (F12) to see the console output.

External JavaScript File:

Your JavaScript code lives in a separate .js file, linked to your HTML using the src attribute of the <script> tag. This is crucial for scalable JavaScript applications.

  • Separation of Concerns: HTML for structure, CSS for style, JavaScript for behavior.
  • Maintainability: Easier to organize and manage larger codebases.
  • Reusability: The same .js file can be used across multiple HTML pages.
  • Caching: Browsers can cache external files, speeding up subsequent page loads.
Steps Involved:
  • Create script.js: In the same folder as your index.html, create a file named script.js.
  • Add JS to script.js:

// script.js

console.log(“Hello, World! From external script.”);

// A simple function (we’ll cover functions soon!)

function greet(name) {

    console.log(`Hello, ${name}!`); // Using template literals (ES6)

}

greet(“JavaScript Learner”); // Call the function

  • Link in index.html:

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>External JS Example</title>

</head>

<body>

    <h1>My First External JS Page</h1>

    <p>Open the browser console to see the magic!</p>

    <script src=”script.js”></script>

</body>

</html>

Save both files and open index.html in your browser. Check the console for the output. 

Suggested: JavaScript Interview Questions and Answers.

Variables and Data Types: Storing Information

Variables are fundamental for storing data in JavaScript. Think of them as named containers for values. JavaScript is dynamically typed, meaning you don’t declare the variable’s type explicitly; its type is determined at runtime based on the value it holds.

Declaring Variables: var, let, and const

This is a critical concept for modern JavaScript best practices.

  • var (The Old Way – Function-Scoped):
    • Variables declared with var are function-scoped (or globally scoped if declared outside a function). This means they are accessible throughout the entire function.
    • They are also “hoisted,” meaning their declaration (but not assignment) is moved to the top of their scope. This can lead to confusing behavior.

var oldSchoolVar = “I’m old school”;

if (true) {

    var oldSchoolVar = “I’m updated in the same scope!”; // Re-declares the same variable

    console.log(oldSchoolVar); // “I’m updated in the same scope!”

}

console.log(oldSchoolVar); // “I’m updated in the same scope!”

  • let (The New Way – Block-Scoped, Reassignable):
    • Introduced in ES6 (ECMAScript 2015).
    • let variables are block-scoped. A block is any code enclosed in curly braces {} (e.g., if statements, for loops, functions).
    • Values can be reassigned.

let modernLet = “I’m block-scoped”;

if (true) {

    let modernLet = “I’m a new variable in this block!”; // A new variable, distinct from the outer one

    console.log(modernLet); // “I’m a new variable in this block!”

}

console.log(modernLet); // “I’m block-scoped” (outer variable unaffected)

modernLet = “I can be reassigned!”;

console.log(modernLet); // “I can be reassigned!”

  • const (The New Way – Block-Scoped, Constant Reference):
    • Also introduced in ES6.
    • const variables are block-scoped.
    • Their reference cannot be reassigned after initial declaration. This means the variable always points to the same memory location.

const PI = 3.14159;

// PI = 3.1; // Error: Assignment to constant variable.

const user = { name: “Alice”, age: 30 };

user.age = 31; // ALLOWED: Modifying a property of the object

console.log(user); // { name: “Alice”, age: 31 }

// user = { name: “Bob”, age: 25 }; // NOT ALLOWED: Reassigning the ‘user’ variable itself

Recommended: Node JS Course Online for Freshers.

JavaScript Data Types (Primitives and Objects)

JavaScript values belong to specific data types. There are two main categories: Primitive Data Types (simple, immutable values) and Non-Primitive (Object) Data Types (complex, mutable values).

Primitive Data Types:
  • String: It represents text. Enclosed in single quotes (‘…’), double quotes (“…”), or backticks (`…`) for template literals (ES6).

let greeting = “Hello, World!”;

let name = ‘Alice’;

let message = `My name is ${name} and the greeting is “${greeting}”.`; // Template literal with interpolation

console.log(typeof message); // “string”

  • Number: It is used to represent both integers and floating-point numbers. No int or float data type.

let age = 30; // Integer

let price = 19.99; // Floating-point

let largeNumber = 1_000_000; // Numeric separators (ES2021) for readability

console.log(typeof age); // “number”

Special Numeric Values: Infinity, -Infinity, NaN (Not-a-Number). NaN is the result of an invalid mathematical operation (for example, 0 / 0, ‘hello’ * 5).

  • Boolean: It is used to represent a logical value: true or false. Crucial to JavaScript conditional logic.

let isActive = true;

let isAdmin = false;

console.log(typeof isActive); // “boolean”

  • null: It is used to represent the deliberate lack of any object value. Means “nothing” or “empty” but is a definite, assigned value.

let userLoggedIn = null;

console.log(typeof userLoggedIn); // “object” (This is a well-known historical bug in JavaScript; `null` is a primitive.)

  • undefined: It describes a variable that has been declared but has not yet been initialized.

let email; // Declared but no value assigned

console.log(email); // undefined

console.log(typeof email); // “undefined”

  • Symbol (ES6): An immutable and unique primitive value, frequently employed as an identifier for object attributes to prevent name clashes. Less frequently used by new coders.

const uniqueId = Symbol(‘myId’);

const anotherId = Symbol(‘myId’);

console.log(uniqueId === anotherId); // false

console.log(typeof uniqueId); // “symbol”

  • BigInt (ES2020): It denotes integers with arbitrary-precision, larger than what the Number type can safely represent (up to 2^53 – 1). Suffix with n.

const hugeNumber = 9007199254740991n + 5n;

console.log(hugeNumber); // 9007199254740996n

console.log(typeof hugeNumber); // “bigint”

Non-Primitive Data Type
  • Object: A group of properties, each with a name (key) and a value. The basis for more advanced data structures such as JavaScript Arrays and custom objects.

let person = {

    firstName: “Jane”,

    lastName: “Doe”,

    age: 28,

    isStudent: false

};

console.log(typeof person); // “object”

The typeof Operator:

Utilize typeof to get the data type of a value or variable.

console.log(typeof “JavaScript”); // “string”

console.log(typeof 123);          // “number”

console.log(typeof true);         // “boolean”

console.log(typeof undefined);    // “undefined”

console.log(typeof null);         // “object” (the bug)

console.log(typeof {});           // “object”

console.log(typeof []);           // “object” (arrays are also objects)

console.log(typeof function(){}); // “function” (functions are also objects, but typeof gives “function”)

Explore: Angular JS Course Online.

Operators: Executing Operations on Data

Operators are reserved characters used to execute operations on one or more values (operands) to arrive at a result.

Arithmetic Operators:

It is utilized for arithmetic operations.

OperatorDescriptionExampleResult
+Addition10 + 515
Subtraction10 – 55
*Multiplication10 * 550
/Division10 / 52
%Modulus (Remainder)10 % 31
**Exponentiation (ES6)2 ** 3 (2 cubed)8
++Increment (x++ or ++x)let x = 5; x++;x is 6
Decrement (x– or –x)let y = 5; y–;y is 4

Assignment Operators:

To assign values to variables.

OperatorExampleEquivalent To
=x = 10
+=x += 5x = x + 5
-=x -= 2x = x – 2
*=x *= 3x = x * 3
/=x /= 2x = x / 2
%=x %= 3x = x % 3
**=x **= 2x = x ** 2

Comparison Operators:

Compare two values and return a Boolean (true or false). These are crucial for JavaScript control flow.

OperatorDescriptionExampleResult
==Equal to (loose equality)5 == ‘5’TRUE
===Strict Equal to (value AND type)5 === ‘5’FALSE
!=Not equal to (loose)5 != ‘4’TRUE
!==Strict Not Equal to (value AND type)5 !== ‘5’TRUE
>Greater than10 > 5TRUE
<Less than3 < 7TRUE
>=Greater than or equal to8 >= 8TRUE
<=Less than or equal to4 <= 5TRUE

Logical Operators:

They are used to combine or negate boolean expressions.

OperatorDescriptionExampleResult
&&ANDtrue && falseFALSE
``OR
!NOT!trueFALSE

let isAdult = true;

let hasTicket = false;

console.log(isAdult && hasTicket); // false (because hasTicket is false)

console.log(isAdult || hasTicket); // true (because isAdult is true)

console.log(!isAdult);             // false

Ternary Operator (Conditional Operator):

A shorter form to write simple if-else statements.

Syntax: condition ? value_if_true : value_if_false;

Example:

let age = 17;

let access = (age >= 18) ? “Granted” : “Denied”;

console.log(access); // “Denied”

Suggested: Web Development Course in Chennai.

Type Conversion (Coercion): Data Type Conversions

Type coercion in JavaScript refers to the conversion of a value from one type to another. JavaScript does this automatically in some situations (implicit coercion) or you may do it explicitly. This is important to know in order to prevent ugly JavaScript bugs.

Implicit Coercion (Automatic):

When JavaScript does the type conversion automatically.

  • To Number: In arithmetic operations (with the exception of + with strings).

console.log(’10’ – 5);    // 5 (string ’10’ becomes number 10)

console.log(‘5’ * ‘2’);   // 10 (both strings become numbers)

console.log(‘abc’ / 2);   // NaN (cannot convert ‘abc’ to number)

  • To String: Whenever using the + operator when one of the operands is a string.

console.log(10 + ‘5’);    // ‘105’ (number 10 becomes string ’10’)

console.log(true + ‘ World’); // ‘true World’

  • To Boolean: In logical contexts (if statements, !, &&, ||).
    • Falsy values: false, 0, -0, “” (empty string), null, undefined, NaN.
    • Truthy values: All other values (e.g., ‘hello’, 1, {}, []).

if (“”) { console.log(“Won’t run”); }

if ([]) { console.log(“Will run, an empty array is truthy”); }

Explicit Coercion (Manual):

You are explicitly instructing JavaScript to change a type with built-in functions. It’s usually safer.

  • To String:
    • String(value): Converts any value.
    • value.toString(): Method for most types (not null or undefined).

let num = 123;

console.log(String(num));       // “123”

console.log(true.toString());   // “true”

console.log(String(null));      // “null”

  • To Number:
    • Number(value): General conversion.
    • parseInt(string): Parses string to integer.
    • parseFloat(string): Parses string to floating-point number.
    • Unary plus (+value): Quick way.

console.log(Number(“123”));      // 123

console.log(parseInt(“100px”));  // 100 (stops at ‘p’)

console.log(parseFloat(“3.14abc”));// 3.14

console.log(+”50″);             // 50

  • To Boolean:
    • Boolean(value): General conversion.
    • Double NOT (!!value): Common shorthand.

console.log(Boolean(1));       // true

console.log(Boolean(“”));      // false

console.log(!!0);              // false

console.log(!!”hello”);        // true

Explore: MEAN Stack Course in Chennai.

Control Flow and Functions: Guiding Your Code

JavaScript control flow is the sequence in which single statements or instructions are run. JavaScript functions are blocks of code that are reusable.

Conditional Statements: Making Decisions

Conditional statements enable your code to decide based on specific conditions.

  • if, else if, else: Runs a block of code if a specific condition is met.
  • switch Statement: Multiple Conditional Branches With One Variable. It gives a more organized approach to multiple if.else if statements.

Looping Constructs: Repeating Actions

JavaScript loops enable you to repeat a piece of code over and over. They are essential for operations such as iterating over data lists.

  • for Loop: The most popular loop, applied when you have an idea of iterations or a clear start/end.
  • while Loop: Runs a block of code as long as a given condition is true. Use when the iterations are unknown.
  • do.while Loop: Like while, but ensures code block runs at least once even if the condition initially is false.
  • for.of Loop (ES6): Used to loop over iterable objects such as JavaScript Arrays, Strings, Maps, Sets, etc. Offers direct access to values.
  • for.in Loop: For looping over enumerable properties of an object. Not generally recommended for arrays since it loops over property names (indices as strings) and may include inherited properties.
break and continue Statements:
  • break: Stops the innermost loop (or switch statement) without executing the remaining statements in the current iteration.
  • continue: Avoids the current iteration of the loop and continues to the next iteration.

Example:

for (let j = 0; j < 10; j++) {

    if (j === 3) {

        continue; // Skip 3

    }

    if (j === 7) {

        break;    // Stop at 7

    }

    console.log(j);

}

// Output: 0, 1, 2, 4, 5, 6

Explore: MERN Stack Course in Chennai.

Functions: Blocks of Code That Can Be Reused

Functions are the backbone of organized and modular JavaScript programming. They are reusable blocks of code that perform a specific task. Defining functions helps in reducing code duplication and making your programs more maintainable.

Defining Functions:

  • Function Declarations (Hoisted): The most common way. Functions declared this way are “hoisted,” meaning they can be called before they are defined in the code.

function sayHello(name) { // ‘name’ is a parameter

    console.log(`Hello, ${name}!`);

}

sayHello(“Alice”); // Call the function, “Alice” is an argument

sayHello(“Bob”);

  • Function Expressions (Not Hoisted): A function saved as a variable. They are not hoisted, thus you need to declare them before you invoke them.

const greetUser = function(user) {

    console.log(`Welcome, ${user}!`);

};

greetUser(“Charlie”);

// greetGuest(); // Error: greetGuest is not defined (if called before definition)

Parameters and Arguments

  • Parameters: The named variables in the function declaration (e.g., name in sayHello(name)). They are stand-ins for values.
  • Arguments: The value arguments that are actually fed to the function when called (e.g., “Alice” in sayHello(“Alice”)).
Return Values:

Functions may return a value with the return statement. Omitting return makes the function return undefined by default.

function calculateArea(length, width) {

    return length * width; // Returns the calculated area

}

let area1 = calculateArea(10, 5);

console.log(area1); // 50

let area2 = calculateArea(7, 3);

console.log(area2); // 21

Scope: Global vs. Local:

JavaScript variable scope specifies where variables can be accessed.

  • Global Scope: Variables which are declared outside a block or a function are globally scoped. They are accessible anywhere in your code.
  • Function Scope (var): Variables which are declared with var within a function are available only within that function.
  • Block Scope (let, const): The variables that are declared with let or const within any block (like if, for, {}) are accessible only within the given block. This is generally recommended to have more control and predictability.
Default Parameters (ES6):

You can specify default arguments for function parameters. If no argument is supplied or is undefined, the default argument is taken.

Explore: Full Stack Course in Chennai.

Data Structures (Objects and Arrays): Structuring Your Data

JavaScript data structures are essential in order to organize and store lists of data.

Arrays: Ordered Collections

JavaScript Arrays are ordered arrays of values. They may store values of any data type, and their length can be changed dynamically. They are zero-indexed, i.e., the first element is at index 0.

const fruits = [“apple”, “banana”, “cherry”]; // Array literal (most common)

const numbers = new Array(1, 2, 3, 4, 5); // Using Array constructor (less common)

const mixedArray = [1, “hello”, true, { key: “value” }];

Objects: Unordered Key-Value Collections

JavaScript Objects are collections of key-value pairs (also called properties). They are used to store structured data and represent real-world entities. Object properties are typically strings (or Symbols).

for (const key in person) {

    if (person.hasOwnProperty(key)) { // Good practice to check

        console.log(`${key}: ${person[key]}`);

    }

}

console.log(Object.keys(person));   // [“firstName”, “lastName”, “age”, “hobbies”, “address”, “greet”, “email”]

console.log(Object.values(person)); // [“John”, “Doe”, 31, [“coding”, …], {street: “…”, city: “…”}, function, “john.doe@example.com”]

Recommended: AngularJS Tutorial for Beginners.

Error Handling: Making Your Code Reliable

Good JavaScript error handling is essential in creating stable and secure applications.

try.catch.finally:
  • try: Holds the code which could throw an error.
  • catch (error): Runs if there is an error in the try block. The error object holds information about the error.
  • finally: Runs independent of whether there was an error or not. Optional.

function divide(a, b) {

    if (b === 0) {

        throw new Error(“Division by zero is not allowed.”); // Throw a custom error

    }

    return a / b;

}

try {

    let result = divide(10, 2);

    console.log(“Result:”, result); // Result: 5

    let badResult = divide(10, 0); // This will throw an error

    console.log(“This line will not be reached.”);

} catch (e) {

    console.error(“An error occurred:”, e.message); // An error occurred: Division by zero is not allowed.

} finally {

    console.log(“Division attempt finished.”);

}

console.log(“Program continues after error handling.”);

Advanced JavaScript Concepts: Unleashing Full Potential

This section dives into more sophisticated JavaScript programming techniques, essential for building complex, interactive web applications.

The Document Object Model (DOM) – Interacting with HTML

The Document Object Model (DOM) is a web document programming interface. It is a tree of objects representing the structure of the page, making it possible for JavaScript to read and modify HTML and CSS. This is the heart of JavaScript web interactivity.

What is the DOM?
  • A language-neutral, platform-independent interface that views an XML or HTML document as a tree data structure, where a node is an object that represents a portion of the document (e.g., element, text, attribute).
  • Enables JavaScript to modify the structure, content, and appearance of a web page.
Event Handling: Handling User Actions

JavaScript event handling enables your web page to respond to user actions (such as clicks, key presses, mouse movement) or browser events (such as page loading).

Asynchronous JavaScript

Asynchronous JavaScript enables these operations to be executed in the background without interrupting the main execution thread, so your web page remains responsive. This is an important concept in developing responsive web applications.

Explore: All Software Training Courses.

Conclusion

You’ve now made great progress in learning JavaScript, the dynamic powerhouse that drives today’s web experiences. From simple variables and control flow to more advanced subject matter such as DOM manipulation and asynchronous code, you have the basics down to begin creating interactive sites. The next step: check out our in-depth JavaScript course in Chennai that takes these concepts further with hands-on exercises and expert instruction.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.