After PHP, HTML, and CSS, Javascript(JS) is the next logical step in every Web-Developer’s journey and is one of the core languages used. This guide walks through the fundamental concepts of JavaScript, including basic syntax, DOM manipulation, promises, event handling, and ES6 modules.
JavaScript: Origins
In 1995, the internet was just starting to take shape and become a mainstream thing. There was not a lot of dynamic content, the Web was mostly made up of static text, images. The browser wars between Microsoft’s Internet Explorer and Netscape’s Navigator was just starting to heat up. Netscape being the underdog here wanted to stand out. So, Netscape engineers started working on improving the browsers dynamic content management. Enter Brendan Eich, a software engineer at Netscape. He was tasked with creating a new scripting language That would help in this use case.
He built the first prototype of the language in just 10 days. Initially it was called Mocha, then Livescript and finally Javascript. This name contained “Java” to capitalize on the growing popularity of Java at that time. However, JavaScript and Java are not directly related at all.
Basics
Javascript uses var
, let
, and const
to declare variables, var
was the traditional way to declare variables, but now the modern JavaScript favors the usage of let
.
let name = "Lakshyajeet"; const number = 9;
Then coming to the Data Types, Javascript has several built-in data types: string
, number
, boolean
, null
, undefined
, and object
.
Control statement are the fundamental concept of any programming language, in JS we have if
–else
statements and switch
statements for this purpose.
if (condition) { // if condition is true } else if (anotherCondition) { // if anotherCondition is true } else { // all conditions are false } // Switch Statement switch(expression) { case x: // code block break; case y: // code block break; default: // code block } // Ternary Operator let result = condition ? value1 : value2;
Apart from these we have loops, i.e., for
, while
, and do-while
loops in Javascipt.
for (let i = 0; i < 5; i++) { // ... } while (condition) { // ... } do { // ... } while (condition); // similar to for-each loop for (let item of array) { // ... }
While all these statements are able to accomplish any use case, sometimes it’s better to group together parts of code that are repeating or used to achieve a common thing, these groups of code are called functions.
function greet(name) { console.log("Hello, " + name); } greet("ABCD"); // Outputs: Hello, ABCD
DOM Manipulation
The Document Object Model (DOM) represents the overall structure of an HTML document. With Javascript we can interact with the DOM, allowing us to manipulate the content dynamically.
With DOM Manipulation we can achieve various thing like—selecting elements, modifying elements, and also creating new elements.
const header = document.getElementById("header"); // Selecting header.style.color = "blue"; const title = document.querySelector(".title"); title.textContent = "New Title"; // Modifying the content const newParagraph = document.createElement("p"); newParagraph.textContent = "This is a new paragraph."; document.body.appendChild(newParagraph); // Adding new element
Promises
Now all the code before this point was synchronous, i.e., it ran sequentially as its written each time, with promises this changes because promises are asynchronous.
Promise is like a promise in real life which has two possible situations that eventually it will either fulfill or reject.
Creating a Promise:
A promise can be created using the new Promise()
constructor, which takes in function with two arguments: resolve
and reject
.
const fetchData = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Promise successful"); } else { reject("Promise rejected"); } });
Handling Promises:
Promises can be handled using .then()
for success(resolve) and .catch()
for errors(reject).
fetchData .then((message) => { console.log(message); }) .catch((error) => { console.error(error); });
Asynchronous with Async/Await:
With ES6, Javascript introduced async
and await
keywords, which simplifies working with promises.
async function getData() { try { const data = await fetchData; console.log(data); } catch (error) { console.error(error); } } getData();
Event Handling
As a part of dynamic interaction, JS lets us run certain part of code depending on the user’s interactions like clicks, scrolls, hover, etc.
Adding Event Listeners:
The most common way to handle events by adding event listeners in Javascript is using the addEventListener()
function.
const button = document.getElementById("myButton"); button.addEventListener("click", () => { alert("Button clicked!"); });
Event Delegation:
Instead of attaching an event listener to each of the child element, it is more efficient to attach a single listener to the parent element.
document.querySelector("#parent").addEventListener("click", (event) => { if (event.target && event.target.matches("button")) { console.log("Button clicked"); } });
Event Propagation:
Events in Javascript tend to bubble up from the target element towards the root of the DOM (this is called bubbling). To can prevent or control this behavior we can use stopPropagation()
and preventDefault()
.
document.querySelector("#myDiv").addEventListener("click", (event) => { event.stopPropagation(); });
ES6 Modules
ES6 (ECMAScript 2015) introduces modules functionality which allows the developers to organize and maintain their code in smaller and reusable pieces.
There modules can be used and imported or exported between JS files.
Exporting Functions and Variables:
A JS file can export variables, functions, or objects using the export
keyword.
// math.js export const add = (a, b) => a + b; export const subtract = (a, b) => a - b;
Importing Functions:
The import
statement allows us to use the exports one file into of another.
// app.js import { add, subtract } from './math.js'; console.log(add(5, 3)); console.log(subtract(5, 3));
Default Exports:
A module can also export a single value as the default.
// user.js const user = { name: "John", age: 30 }; export default user;
// app.js import user from './user.js'; console.log(user.name);
Conclusion
JavaScript continues to be an essential and leading language for web development, powering interactive websites and applications. By understanding the basic syntax, DOM manipulation, and other things mentioned developers can write cleaner, more efficient, and maintainable code.
Additional content can be found in a Javascript cheatsheet here.
Leave a Reply