Photo by Claudio Schwarz on Unsplash
7 Key JavaScript Concepts and Functionalities Every Beginner Should Know
Introduction
JavaScript (JS) is one of the most widely used programming languages in the world. It is an enormously powerful and versatile language which can be used in a variety of fields like building web applications or complex data visualisation. While concepts of JS can seem quite tricky in the beginning, this article will take you through all the major concepts so that you get a solid understanding by the end. So, let's dive in!
Key Concepts
1. Variables and Data Types
Variables are entities which are used to store data, on which you can perform different operations. There are three different keywords for declaring a variable in ES6 - var
, let
and const
. var
makes a variable available globally while let
allows only a local scope. const
is used to hold values which are meant to stay fixed throughout your code.
JS consists of eight data types -
Number - Used to hold integer or decimal number
BigInt - Used to operate on large integers
String - Used to hold a sequence of characters
Symbol - Used as a unique identifier
Boolean - Hold only two values -
true
orfalse
Null - Holds the value
null
(Remember,null
is NOT zero!)Undefined - Used to denote that the variable has not been defined/ assigned yet
Object (Discussed later)
// Declare a variable with the string data type var greeting = "Hello, world!"; // Declare a variable with the number data type var age = 30; // Declare a variable with the Boolean data type var isCorrect = true; // Declare a variable with null and undefined value var question = null; var answer = undefined;
2. Control Structures
Control structures allow you to control the flow of your code and make decisions based on certain conditions. These are characterised by several types of loops and their variations.
If Statements : This is used to perform certain operations based on some prerequisites which are to be met. An
if
statement is paired with anelse if
and /orelse
statement and each conditional block hold certain actions to be performed on fulfilment of the given condition.// Check if a number is greater than or equal to 10 var num = 15; if (num >= 10) { console.log("The number is greater than or equal to 10"); } else { console.log("The number is less than 10"); } // Result : The number is greater than or equal to 10
For Loops : This type of loop is used to iterate over a certain block of code multiple times.
// Iterate over an array of names var names = ["Alice", "Bob", "Charlie"]; for (var i = 0; i < names.length; i++) { console.log(names[i]); } // Result : // Alice // Bob // Charlie
While Loops : These are used to repeat a block of code as long as a certain condition is true. This is particularly helpful when we don't know about the number of iterations to be performed beforehand. A variation of this is a
do-while
loop.// Check if a user has entered a valid input var isValid = false; while (!isValid) { var input = prompt("Enter a number between 1 and 10: "); if (input >= 1 && input <= 10) { isValid = true; } else { alert("Invalid input. Please try again."); } }
Switch Case Statements - Switch case statements are used to test a single variable against multiple values.
// Check the grade of a student var grade = 'A'; switch (grade) { case 'A': console.log('Excellent'); break; case 'B': console.log('Good'); break; case 'C': console.log('Fair'); break; case 'D': console.log('Poor'); break; default: console.log('Invalid grade'); break; } // Result : Excellent
3. Functions
A JavaScript function is a block of code designed to perform a specific task. The main advantage of using functions is their reusability. E.g., you want to add two numbers and display the result in your console. If you hard-code this for all the values, you'll find it exhausting and repetitive. Instead, you can design a function for adding two numbers and then use it anywhere with values of your choice. This makes the code reusable and maintainable as well.
// Function without arguments
function greet(){
console.log("Hello World!");
}
greet();
// Result : Hello World
// Function with arguments
function addNumbers(a, b) {
return a + b;
}
addNumbers(10, 5);
// Result : 15
A function can accept arguments. Like in the previous example, your custom addNumbers
function accepts two arguments corresponding to two numbers which are to be added. You can pass all sorts of data types, even other functions, as arguments.
Note that a function will normally return a value (unless it contains only print statements). This value can be all sorts of data types including other functions. E.g., the addNumbers
function returns a number.
JS has "function scope", where each function has its own scope. This is different from the global and local scope as discussed earlier. In the case of function scope, the keywords var
, let
and const
behave quite similarly. Variables declared inside a function are accessible only inside the function. They are created when the function starts and deleted when it ends.
// Double a number
function double(num) {
let a = 2;
return num * a;
}
In the above example, the variable a
has function scope, which means you can only work with this variable inside this function, and not anywhere else.
4. Arrays
An array is an especially useful data structure that allows you to store and manipulate a collection of values. Arrays can be used to hold a list of values of the same or different data types, such as numbers, strings, objects, and Booleans. Arrays are ordered, so you can track elements inside an array using the index positions of the elements. The level of complexity of arrays can range from simple single-level arrays to complex nested arrays (multi-dimensional arrays).
// Create an array
let numbers = [1, 2, 3];
// Access second element of an array
console.log(numbers[1]);
// Result : 2
There are lots of useful methods which can be performed upon an array. Methods like push()
, pop()
, shift()
and unshift()
are used to add or retrieve elements from a given array.
let numbers = [1, 2, 3, 4, 5];
// Push method
numbers.push("new"); // Adds 6 at the end of the array
console.log(numbers) // Result : [1, 2, 3, 4, 5, "new"]
// Pop method
let popElement = numbers.pop(); // Removes 5 from the end of the array and stores it in popElement variable
console.log(numbers); // output: [1, 2, 3, 4, 5]
console.log(popElement); // output: "new"
// Shift method
let shiftElement = numbers.shift(); // Removes 1 from the beginning of the array and stores it in shiftElement variable
console.log(numbers); // Result : [2, 3, 4, 5]
console.log(shiftElement); // Result : 1
// Unshift method
numbers.unshift("new"); // Adds "new" at the beginning of the array
console.log(numbers); // Result : ["new", 2, 3, 4, 5]
Apart from these, there are methods like slice()
, splice()
, forEach()
, map()
, filter()
, reduce()
etc which are used to perform complex operations on arrays.
5. Objects
Objects are one of the most important data structures in JavaScript. They allow you to store collections of key-value pairs, where the keys are unique identifiers, and the values can be any data type. Objects allow us to represent complex data in a structured way. Objects can be predefined (e.g. - arrays, strings, dates etc.) or built from scratch with their own properties and methods.
// Creating a new object - Method 1
const person = {
name: 'John Doe',
age: 30,
address: {
city: 'New York',
state: 'NY'
}
};
// Creating a new object - Method 2
const newPerson = new Object();
newPerson.firstName = "Betty";
newPerson.lastName = "Anderson";
newPerson.age = 50;
newPerson.eyeColour = "blue";
You can access the properties of any object using dot (.
) notation or parentheses ([]
). You can modify, add, or delete properties of an object.
// Dot notation to access object properties
console.log(person.name); // output: 'John Doe'
console.log(person.address.city); // output: 'New York'
// Parentheses to access object properties
console.log(person['name']); // output: 'John Doe'
console.log(person['address']['city']); // output: 'New York'
// Modify a property
person.age = 35;
console.log(person.age); // output: 35
// Add new property
person.email = 'john.doe@example.com';
console.log(person.email); // output: john.doe@example.com
// Delete a property
delete person.email;
JavaScript provides several built-in methods for objects, which can be used to manipulate objects and their properties. Every object has a prototype, which is a reference to another object. When you access a property of an object, JavaScript first looks for the property in the object itself. If it can't find the property, it then looks for it in the object's prototype. You can refer to the documentation for an in-depth study and understanding of objects.
6. DOM Manipulation
DOM (Document Object Model) is the structured representation of an HTML document, and by manipulating it, we can dynamically change the content and appearance of a web page. JavaScript can perform finely in this task. You can create, add, modify, or delete DOM elements. You can also "listen" to events, perform specific operations, and then reflect the changes in the target DOM element. Understanding DOM manipulation is especially important in building customisable web applications.
<div id="content">
<h1>Welcome to my blog!</h1>
<div id="posts">
<!-- blog post elements will be added here -->
</div>
<button id="new-post-button" onclick="createNewPost()">Create New Post</button>
</div>
In this example, we want to add a new post inside the <div>
with id="posts"
dynamically (in the event of the button click). First, we assign the onclick
attribute of the button to a function named createNewPost()
. Inside the function, we create a new title element for the new post along with a paragraph element to hold the content of the new post. Then we append them to the parent div
with id="content"
.
function createNewPost() {
// Create a new h2 element
const newHeading = document.createElement("h2");
// Set its text content
newHeading.textContent = "New Blog Post Title";
// Create a new p element
const newParagraph = document.createElement("p");
// Set its text content
newParagraph.textContent = "This is the blog paragraph text";
// Append the new elements to an existing element with id "posts"
const postsElement = document.getElementById("posts");
postsElement.appendChild(newHeading);
postsElement.appendChild(newParagraph);
}
7. Asynchronous JavaScript
Asynchronous programming is an important concept in modern web development because it allows the browser to execute multiple tasks simultaneously without blocking the main thread of execution. JavaScript is a single-threaded programming language - which means it can perform a single task at a time. But, with the use of asynchronous programming, JS enables developers to write code that can perform time-consuming tasks in the background, without blocking the main thread. This means that the user interface can remain responsive even while the application is doing work behind the scenes.
This can be explained in simple terms with a for loop which takes considerable time to complete the entire operation. This blocks all the other operations and waits until the for loop finishes iteration.
// A function that performs a long-running operation synchronously
function longOp() {
// Simulate a long-running operation by looping for many iterations
for (let i = 0; i < 1000000000; i++) {}
return "Done!";
}
console.log(longOp());
// This will block the main thread until the function completes. So you will get the "Done!" message after a considerable wait.
console.log("This line will not be executed until the long running operation is complete.");
In the case of asynchronous operations, the longOpAsync()
function performs a long-running operation using setTimeout()
to simulate a non-blocking asynchronous operation. When this function is called, it immediately returns and the second console.log()
statement is executed without waiting for the long-running operation to complete. The callback
function is called asynchronously when the operation is complete, allowing the result to be handled without blocking the main thread.
// A function that performs a long-running operation asynchronously
function longOpAsync(callback) {
// Simulate a long-running operation by looping for a large number of iterations
setTimeout(() => {
for (let i = 0; i < 1000000000; i++) {}
callback("Done!");
}, 0);
}
// Call the function and log the result
longOpAsync(result => console.log(result));
console.log("This line will be executed immediately, before the long running operation is complete.");
Summary
Congratulations on completing your journey into fundamental JavaScript concepts and functionalities! Throughout this learning experience, you have gone through several key concepts that form the building blocks of JavaScript programming. You started with an understanding of variables and keywords used to declare them and learnt about several types of data structures that can be used to organize and manipulate data. Next, you explored various looping techniques such as conditional, switch cases, and iterative methods. You also learned about the importance of reusable code with functions.
Moving forward, you delved into arrays and objects, which are fundamental to handling and manipulating complex, structured data. You also explored the Document Object Model (DOM) and ways of DOM manipulation for changing web page content and structure. Finally, you learned about asynchronous non-blocking code in JS, which helps to improve performance by executing code without blocking the main thread.
With these foundational concepts and functionalities, you are now equipped with the necessary tools to write efficient and effective JavaScript code. You can now unlock endless possibilities for creating dynamic and interactive web experiences and continue to build upon your knowledge and expertise in JavaScript programming. So once again, let's code!