JavaScript is a foundational programming language that allows developers to make websites interactive and user-friendly. In this blog, you will learn JavaScript for beginners with content that starts with answering “What is JavaScript?”. With JavaScript examples, we will discuss how to add actions to webpage elements, handle events, and manipulate content dynamically without reloading the page. By the end of this article, you will understand core concepts, key features, modern ECMAScript updates (ES6+), and practical applications of JavaScript in web development and beyond.
What is JavaScript?
JavaScript is a flexible language that helps you create interactive web pages and enhance user experience. With JavaScript, you add actions to webpage elements, like buttons, forms, and menus. It also allows you to display pop-up messages, update content dynamically, and respond to user events without reloading the page. By completely understanding and mastering JavaScript, you can build responsive websites, web applications, and real-time features efficiently. It is important to learn these core skills as they will help you learn modern frameworks like React, Angular, and Vue.js better and work with them.
Brief History of JavaScript
JavaScript was created in 1995 by Brendan Eich while working at Netscape. Firstly, it was called Mocha, then LiveScript, and was finally called JavaScript. In 1997, it became standardized and was officially called ECMAScript. Now, JavaScript is one of the powerful languages that is used to build websites and apps. And today it is used by developers all over the world.
Why JavaScript is Important
JavaScript is very popular among developers. Let’s understand the reason why it is considered important among developers:
- Actionable: It allows you to add dynamic elements to your website without reloading the full content.
- Real-Time Updates: JavaScript is important to create a website that can update its content of the website without reloading the webpage. This is helpful in making websites where content changes dynamically.
- Making Web Apps: JavaScript helps you to create Popular web apps like Gmail, Facebook, and other websites.
- Works Everywhere: JavaScript is used by most developers because it works on all browsers and devices.
- Helpful libraries: You can create websites easily with various JavaScript libraries like React and Vue.js
How JavaScript Works in the Browser?
JavaScript is a dynamic language that will help you to do things like modify the text or update a page without reloading the page. Here is complete information about the working of JavaScript:
1. The JavaScript Engine
Every browser has a JavaScript engine that is responsible for running the JavaScript code inside the console. When you open a website on the browser, the browser loads the JavaScript and first checks for mistakes. Then it runs the code.
Every web browser uses a different JavaScript engine:
- Google Chrome uses the V8 engine.
- Firefox uses the SpiderMonkey engine.
- Safari uses the JavaScriptCore engine.
2. Document Object Model
The document object model (DOM) is the blueprint for the webpage. This model contains headings, buttons, and other HTML elements in a tree-like structure based on hierarchy. JavaScript uses the DOM to change things on the page without needing to reload the full page.
For example, JavaScript can:
- You can change the text on a button.
- You can add new elements, like images or paragraphs.
- You can also change the style, like changing a button to red when clicked.
Example: The text of the button changed when the user clicked.
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
button.innerHTML = "You Clicked Me!";
});
</script>
Here,
- When you click the button, JavaScript changes its text using the DOM.
Find out why using document.write() in JavaScript is considered bad practice through this blog.
3. Event Handling and Listeners
Whenever any user takes actions, like clicking on a button, it is marked as event in JavaScript. These events are handled using event listeners in JavaScript.
For example, JavaScript can listen for a click on a button and show a message:
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
Here,
When the button is clicked, JavaScript shows an alert saying “Button clicked!” because it is listening for the click event.
Basic Concepts of JavaScript
JavaScript is a universal programming language with several foundational components. Below are the concepts which is required to be understood by each beginner:
1. Variables and Data Types
Variables are used as storage containers for storing values. And this is used whenever it is required.
Example:
let name = "Intellipaat";
Data Types: It is used to specify the data type that a variable can store. Common data types include:
- String: “Hello”
- Number: 42, 3.14
- Boolean: true or false
- Object: {name: “Intellipaat”, age: 15}
- Array: [1, 2, 3]
2. Operators
Operators are symbols used to perform operations on variables or values. Some common types of operators include:
Arithmetic Operators: It is used to perform mathematical calculations.
Example: +, -, *, /
let sum = 5 + 3; (Result: 8)
Comparison Operators: It is used to compare two values.
Example: ==, !=, >, <
5 > 3 (Result: true)
Logical Operators: It is used to combine multiple conditions.
Example: && (AND), || (OR), ! (NOT)
3. Functions
A function in JavaScript is a block of code that can be used to perform a particular task in code. Once a function is created, it can be used multiple times in code.
Example:
function greet(name) {
console.log("Hello, " + name);
}
greet("Intellipaat");
Output:
- Functions in JavaScript will help you in organizing code and avoiding repetition. You can pass the values as parameters inside the function and get some results as output.
4. Objects and Arrays
Objects are used to store collections of data in key-value pairs.
Example:
let person = {
name: "Intellipaat",
age: 25,
isStudent: false
};
console.log(person);
Output:
Example: Storing multiple values inside a single variable
let numbers = [1, 2, 3, 4, 5];
5. Conditionals and Loops
Conditional statements in JavaScript allow you to run a block of code based on conditions. This block of code will run when the condition is evaluated to true. You can use if-else statements to use conditionals inside code.
Example:
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Output:
Loops: In JavaScript, loops are used to repeat certain lines of code multiple times until a certain condition is met.
Example of a for loop:
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
Find out why you should avoid using eval() in JavaScript in this blog.
JavaScript Syntax
JavaScript Syntax refers to the set of rules that are used to define how you can write code in JavaScript. Understanding these rules helps you a lot to run code correctly. Here are some of the syntax rules that everyone needs to follow while writing code:
1. Writing JavaScript Code
You can write JavaScript code either in an HTML file directly using the <script> tag. You can also do this by creating a new file with a .js extension. Here’s how you can do it:
In an HTML file:
<html>
<head>
<title>My JavaScript Page</title>
</head>
<body>
<script>
let message = "Hello, Intellipaat!";
console.log(message);
</script>
</body>
</html>
In an external .js file:
For linking the external script.js file to your HTML, use the <script> tag with the src attribute:
<script src="script.js"></script>
2. Common Syntax Errors
Here are some of the common errors that you may find while writing and running code in JavaScript:
Missing semicolon: Every line of code should end with a semicolon (;).
Incorrect:
let name = "Intellipaat"
console.log(name)
Correct:
let name = "Intellipaat";
console.log(name);
Unmatched parentheses or curly braces: Always make sure you close parentheses () and curly braces {}.
Incorrect:
if (x > 10 {
console.log("Greater than 10");
Correct:
if (x > 10) {
console.log("Greater than 10");
}
Using reserved keywords: Some words are reserved by JavaScript and cannot be used as variable names (like let, function, etc.).
Incorrect:
let function = "Hello, Intellipaat";
Correct:
let greeting = "Hello, Intellipaat";
Comments in JavaScript play a very important role when you are working in a team. It will help others to understand the code. In JavaScript, there are two types of comments:
Single-line comment: Starts with //, and everything after that on the same line is ignored by JavaScript.
Example:
// This is a single-line comment
let name = "Intellipaat"; // This is an inline comment
Multi-line comment: Starts with /* and ends with */. It’s used for commenting multiple lines of code.
Example:
/* This is a
multi-line comment */
let age = 25;
Documentation comments: It is used to explain the function or code blocks. Documentation comments are always written in multiple lines.
Example:
/**
* This function calculates the area of a rectangle.
* @param {number} width - The width of the rectangle.
* @param {number} height - The height of the rectangle.
* @returns {number} The area of the rectangle.
*/
function calculateArea(width, height) {
return width * height;
}
Key Features of JavaScript
JavaScript is very popular among developers. Here are some of the features of JavaScript:
- Frameworks like React and Vue.js are used to write client-side code.
- You can perform an action when a user clicks on the button or performs an action.
- In JavaScript, there is no need to define the type of the variable. It can be automatically assigned at runtime.
- JavaScript allows running multiple operations at the same time.
- JavaScript is object oriented language, which means you can create and store data in the form of objects.
- JavaScript is built to run on all browsers and devices.
- JavaScript offers various libraries and frameworks for writing frontend and backend code.
Applications of JavaScript
Here are some of the common applications of JavaScript:
- JavaScript is used to create elements like buttons, forms, and animations on websites through which users can interact.
- Web Development Frameworks: JavaScript provides frameworks like React, Angular, and Vue to build web applications.
- Server-Side Development: With Node.js, JavaScript also allows backend development through server handling, APIs, and a database.
- Mobile Apps: JavaScript is used to develop cross-platform mobile apps with frameworks like React Native.
- Game Development: JavaScript can be used to create simple browser-based games using HTML5 canvas.
- Browser Extensions: JavaScript also allows you to enhance browser functionality with custom extensions for Chrome, Firefox, and others.
- Web APIs: JavaScript interacts with Web APIs to fetch data (e.g., weather info or social media feeds) and update the web page in real time.
- Real-Time Applications: JavaScript helps build real-time applications like chat apps and live notifications.
Explore more practical applications of JavaScript and career tips for success in this blog.
ECMAScript Versions: Modern JavaScript Explained
Version |
Year |
Feature |
ECMAScript 3 |
1999 |
Introduced basic features like regular expressions and string handling. |
ECMAScript 5 |
2009 |
Added strict mode, JSON support, and improved array/object methods. |
ECMAScript 6 (ES6) |
2015 |
Introduced let/const, arrow functions, classes, and promises. |
ECMAScript 2016 (ES7) |
2016 |
Added exponentiation operator (** ). |
ECMAScript 2017 (ES8) |
2017 |
Introduced async/await for handling asynchronous operations. |
ECMAScript 2018 (ES9) |
2018 |
Improved asynchronous operations and added rest/spread operators for objects. |
ECMAScript 2019 (ES10) |
2019 |
Added flat() for arrays and fromEntries() for objects. |
ECMAScript 2020 (ES11) |
2020 |
Introduced Nullish Coalescing (?? ) and Optional Chaining (?. ). |
ECMAScript 2021 (ES12) |
2021 |
Improved Promise handling and added replaceAll() for strings. |
ECMAScript 2022 (ES13) |
2022 |
Introduced class field declarations and top-level await. |
Modern JavaScript (ES6+) Features and Examples
Modern JavaScript, which is also called ES6, consists of all the JavaScript versions that are ECMAScript 2015 and beyond. It introduced many features that make writing clean, concise, and maintainable code easier. These features are widely used in professional web development, especially when working with frameworks like React, Angular, or Vue.js.
1. let and const vs var
In older JavaScript, variables were declared using var. Modern JavaScript uses let and const for better scope control. The JavaScript var method, used to declare a variable, was block-scoped. This means that these variables could have been used anywhere in the code. Let and const are a block-scoped way of declaring variables, which improves code safety and maintainability.
if (true) {
var x = 10;
}
console.log(x);
if (true) {
let y = 20;
const z = 30;
console.log(y);
console.log(z);
}
Output:
Explanation: let and const stay within their block, which prevents any accidental access and makes code more predictable.
2. Optional Chaining (?
)
Optional chaining makes it much easier (and safer) to access deeply nested object properties without writing long chains of checks. Before this feature, developers had to manually verify that each property existed, or else JavaScript would throw an error. This feature was introduced in ES2020.
const user = {
profile: {
name: "Intellipaat"
}
};
console.log(user?.profile?.name);
console.log(user?.address?.city);
console.log(user?.contact?.getEmail?.());
Output:
Explanation: In this way, your code won’t break if a property doesn’t exist, which is super useful when working with API responses or dynamic data.
3. Nullish Coalescing (??
)
Another feature that was added to JavaScript through the ES2020 update was the nullish coalescing operator (??). This operator lets you provide a fallback only when a value is null or undefined, unlike the || operator, which treats all falsy values (like 0 or ”) the same way.
const userInput1 = 0;
const userInput2 = null;
const userInput3 = undefined;
const userInput4 = "";
console.log(userInput1 ?? 100);
console.log(userInput2 ?? 100);
console.log(userInput3 ?? 100);
console.log(userInput4 ?? "Empty");
Output:
Explanation: Unlike ||, it doesn’t replace valid falsy values (like 0
or an empty string""
). This makes your defaults more accurate. Here, it gave
Limitations of JavaScript
JavaScript is great, but it does have some limitations. Let’s see what those limitations are:
- Works Only in Browsers: JavaScript mostly works in web browsers, so it’s not as useful outside of websites, though it can run on servers with Node.js.
- Security Issues: JavaScript can be vulnerable to attacks if not properly protected, like code injections (XSS).
- Can Be Slow: For complex tasks, JavaScript may be slower compared to other programming languages.
- Single Inheritance: JavaScript allows only one parent object for each object, unlike other languages that can have multiple parent objects.
- Different Browsers, Different Results: JavaScript might behave differently in different browsers, causing issues for developers.
- No Multithreading: JavaScript runs on one thread so it can struggle with tasks that need to happen at the same time, though there are solutions like Web Workers.
- Depends on the Browser: JavaScript performance can vary depending on the browser, so what works well in one may not in another.
Conclusion
Till now, you have a solid understanding of JavaScript, from basic concepts like variables, operators, functions, and loops to modern features such as let and const, optional chaining, and nullish coalescing. JavaScript is an essential tool for creating interactive websites, web apps, mobile apps, games, and real-time applications. With this knowledge, you are ready to explore advanced frameworks and libraries, write clean, maintainable code, and leverage ECMAScript versions effectively in professional web development.
Discover how to take screenshots directly in the browser using JavaScript in this blog.
These posts are crafted to support learning and exploration in various areas of technology.
How can I group by date time column without taking time into consideration? – Covers techniques to group SQL data by date while ignoring the time part for cleaner results.
Which of the following is a valid SQL type? – Lists valid SQL data types and clarifies their appropriate usage in database schemas.
Azure Active Directory Interview Questions – Features key interview questions focused on Azure Active Directory concepts and practices.
What are undefined reference unresolved external symbol errors in C++? – Explains why unresolved external symbol errors happen in C++ and how to resolve them.
Power BI COUNTIF Function – Demonstrates the use of COUNTIF in Power BI for counting records that satisfy specific conditions.
Power BI Ribbon Charts – Describes how to build ribbon charts in Power BI to visualize changes in data ranking over time.
What is JavaScript – FAQs
Q1. Why is JavaScript called a "scripting" language?
JavaScript is called a scripting language because it helps you do tasks in web browsers, like making websites interactive, without needing to compile code.
Q2. Can JavaScript be used for back-end development?
Yes, you can use JavaScript for writing backend code. For this, you have to install Node.js in your system.
Q3. What’s the difference between JavaScript and jQuery?
JavaScript is the main programming language, while jQuery is a tool (library) built with JavaScript to handle things like web page elements and making requests easier and faster.
Q4. What does “hoisting” mean in JavaScript?
Hoisting in JavaScript is a phenomenon where variables and functions are moved to the top of their respective scopes which means if you try to print a variable before its initialization, then JavaScript doesn’t return you an error.
Q5. What’s the difference between null and undefined in JavaScript?
The null is a primitive value that represents an empty value or the absence of a value for a variable. While undefined represents that the variable is declared, but not assigned a value.
Q6. What do the async and await keywords do?
The async keyword is used before the function that requires more time to execute, and the await keyword is used to pause the function until the result is generated.