20 Essential JavaScript Concepts I Wish I Knew Way Earlier (Explained with Examples)

Ankit Kumar
Stackademic
Published in
5 min readJan 9, 2024

--

JavaScript is a powerful and versatile programming language that forms the backbone of interactive web development. Whether you’re a beginner or an experienced developer, mastering key JavaScript concepts is essential for writing efficient and maintainable code. In this article, we’ll explore 20 fundamental JavaScript concepts, complete with illustrative code examples.

1. Closures:

Closures are a powerful aspect of JavaScript that involves functions retaining access to variables from their outer scope even after the outer function has finished executing.

// Code Example
function outerFunction() {
let outerVariable = "I am from outer function";

function innerFunction() {
console.log(outerVariable);
}

return innerFunction;
}

const closureExample = outerFunction();
closureExample(); // Outputs: I am from outer function

2. Promises:

Promises are objects representing the eventual completion or failure of an asynchronous operation, providing a cleaner alternative to callbacks.

// Code Example
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve("Operation succeeded!");
} else {
reject("Operation failed!");
}
}, 2000);
});
}

asyncOperation()
.then(result => console.log(result))
.catch(error => console.error(error));

3. Callbacks:

Callbacks are functions passed as arguments to other functions, executed after a particular operation has completed.

// Code Example
function fetchData(callback) {
setTimeout(() => {
const data = "Callback Example Data";
callback(data);
}, 1000);
}

fetchData(result => console.log(result));

4. Hoisting:

Hoisting involves the automatic moving of variable and function declarations to the top of their containing scope during the compilation phase.

// Code Example
console.log(hoistedVariable); // Outputs: undefined
var hoistedVariable = "I am hoisted!";

5. Scope and Scope Chain:

Understanding the scope and scope chain is crucial for variable accessibility in different parts of your code.

// Code Example
function outerFunction() {
let outerVariable = "I am from outer function";

function innerFunction() {
console.log(outerVariable);
}

innerFunction();
}

outerFunction(); // Outputs: I am from outer function

6. Event Delegation:

Event delegation allows you to listen for events on a parent element instead of adding event listeners to individual elements.

<!-- HTML Example -->
<ul id="parentList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<!-- JavaScript Example -->
<script>
document.getElementById("parentList").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
console.log("Clicked on", e.target.textContent);
}
});
</script>

7. Prototype and Prototypal Inheritance:

JavaScript is prototype-based, and understanding prototypes is key to comprehending inheritance in JavaScript.

// Code Example
function Animal(name) {
this.name = name;
}

Animal.prototype.sayHello = function() {
console.log("Hello, I'm " + this.name);
};

const cat = new Animal("Whiskers");
cat.sayHello(); // Outputs: Hello, I'm Whiskers

8. Arrow Functions:

Arrow functions provide a concise syntax and automatically bind to the surrounding context.

// Code Example
const add = (a, b) => a + b;
console.log(add(5, 3)); // Outputs: 8

9. Async/Await:

Async/Await provides a more readable and synchronous-looking way to handle asynchronous operations.

// Code Example
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async function asyncTask() {
console.log("Task started");
await delay(2000);
console.log("Task completed after 2 seconds");
}

asyncTask();

10. ES6+ Features:

ECMAScript 6 (ES6) introduced several features like destructuring, template literals, and spread/rest operators.

// Code Example
const person = {
name: "John",
age: 30,
};

const { name, age } = person;
console.log(name, age); // Outputs: John 30

11. The `this` Keyword:

Understanding how the `this` keyword behaves in different contexts is crucial for managing the current execution context.

// Code Example
const person = {
name: "John",
greet: function() {
console.log("Hello, " + this.name);
},
};

person.greet(); // Outputs: Hello, John

12. Strict Mode:

Enabling strict mode (`’use strict’;`) helps catch common coding errors and prevents the use of certain error-prone features.

// Code Example
"use strict";
nonDeclaredVariable = "This will throw an error";

13. DOM Manipulation:

Understanding how to manipulate the Document Object Model (DOM) is fundamental for creating dynamic web pages.

<!-- HTML Example -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Manipulation Example</title>
</head>
<body>

<div id="myDiv">Hello, World!</div>

<script>
// JavaScript Example
const myDiv = document.getElementById("myDiv");
myDiv.innerHTML = "Hello, JavaScript!";
myDiv.style.color = "blue";
</script>

</body>
</html>

14. LocalStorage and SessionStorage:

LocalStorage and SessionStorage provide simple key-value storage options in the browser.

// Code Example
// LocalStorage
localStorage.setItem("username", "John");
console.log(localStorage.getItem("username")); // Outputs: John

// SessionStorage
sessionStorage.setItem("token", "abc123");
console.log(sessionStorage.getItem("token")); // Outputs: abc123

15. Web Storage vs Cookies:

Understanding the differences between Web Storage and cookies for client-side data storage.

16. Asynchronous Programming:

Understanding how to work with asynchronous code, using callbacks, promises, and async/await.

17. AJAX (Asynchronous JavaScript and XML):

AJAX involves making asynchronous requests to the server without reloading the entire page.

// Code Example
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();

18. Module Systems (CommonJS, AMD, ES6 Modules):

Understanding different module systems and how to use them for modularizing code.

// Code Example
// File: module.js
export const greeting = "Hello, ";
export function sayHello(name) {
console.log(greeting + name);
}

// File: main.js
import { greeting, sayHello } from './module.js';
sayHello("John"); // Outputs: Hello, John

19. Error Handling:

Proper error handling using `try`, `catch`, and `finally` blocks to deal with unexpected issues.

// Code Example
try {
// Code that may throw an error
throw new Error("This is an error");
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("This block always executes");
}

20. Debugging Tools:

Familiarizing yourself with browser developer tools and using `console.log` for debugging.

In conclusion, mastering these JavaScript concepts lays a solid foundation for writing efficient and maintainable code. As you continue to explore the language, these concepts will become invaluable tools in your development journey.

Happy coding!

If you like this post, you can buy me a coffee.

Also, to be notified about my new articles and stories: Follow me on Medium.

Subscribe to my YouTube Channel for educational content on similar topics

Follow me on Medium and GitHub, to connect quickly

You can find me on LinkedIn as it’s a professional network for people like me and you.

Cheers!!

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

--

Engineering Manager | Solution Architect | Engineering Mentor | Navodayan