Mastering JavaScript Fundamentals: Guide to Basic Concepts and Techniques

From Variables to Promises: A Complete Guide to JavaScript Fundamentals

Manish Salunke
17 min readMar 12, 2023
900+ JavaScript Interview Questions | In-Depth Explanations

Hello! My name is Manish and I’m happy to introduce you to the world of JavaScript basics. JavaScript is a powerful programming language widely used for building dynamic and interactive web applications.

Whether you’re a beginner or an experienced developer, mastering the basics of JavaScript is essential to building a successful web application.

This guide covers the basic concepts and techniques of JavaScript programming. We’ll start by introducing you to the basics of JavaScript, including variables, data types, functions, and control structures.

We’ll dive deeper into more advanced topics like arrays, objects, and error handling here. It also explores the differences between synchronous and asynchronous programming and the different ways to create and manipulate arrays in JavaScript.

It also describes how to handle asynchronous code using promises and callbacks, and how to manipulate the Document Object Model (DOM) using JavaScript. Throughout this guide, we will use a ton of personas to make the material accessible and engaging.

Whether you’re new to programming or an experienced developer looking to advance your skills, this guide provides a solid foundation in JavaScript basics. Let’s get started and explore the exciting world of JavaScript programming!

JavaScript Questions we will cover:

  1. What is JavaScript and what are its basic features?
  2. What are variables in JavaScript and what are the different data types supported?
  3. What is the difference between == and === operators in JavaScript?
  4. How do you declare a function in JavaScript?
  5. What is hoisting in JavaScript and how does it work?
  6. What are closures in JavaScript and how do they work?
  7. What is the difference between let, const, and var in JavaScript?
  8. What are the different types of loops in JavaScript and how do they work?
  9. How do you handle errors and exceptions in JavaScript?
  10. What is JSON and how is it used in JavaScript?
  11. How do you create an object in JavaScript and what are the different ways to do it?
  12. What are callbacks in JavaScript and how do they work?
  13. What is the event loop in JavaScript and how does it work?
  14. How do you manipulate the DOM using JavaScript?
  15. What are the different types of events in JavaScript and how do you handle them?
  16. What is the difference between synchronous and asynchronous programming in JavaScript?
  17. How do you use promises in JavaScript?
  18. What are the different methods to create an array in JavaScript?
  19. How do you sort an array in JavaScript?
  20. What is the difference between map and filter methods in JavaScript?

900+ JavaScript Interview Questions | In-Depth Explanations

Understanding JavaScript and its Basic Features

JavaScript is a popular high-level programming language used to create interactive web pages and web applications. It is a lightweight, object-oriented language that supports both functional and imperative programming styles.

JavaScript can run on both the client-side and server-side of web applications, making it a versatile language that can be used for a wide range of web development projects.

Some of the basic features of JavaScript include:

  • The syntax that is similar to other programming languages, such as C++ and Java.
  • Dynamic typing means that variables do not need to be declared with a specific data type.
  • Support for object-oriented programming principles, such as encapsulation, inheritance, and polymorphism.
  • The ability to manipulate the Document Object Model (DOM) to create interactive web pages.
  • Built-in support for regular expressions and asynchronous programming.

Overall, JavaScript is a powerful language that is well-suited for web development projects of all sizes and complexities.

Understanding Variables and Data Types in JavaScript

Variables in JavaScript are used to store values that can be referenced later in a program.

JavaScript supports several data types, including:

  • Numbers, which include both integers and floating-point numbers.
  • Strings, which are sequences of characters enclosed in quotes.
  • Booleans can have one of two values: true or false.
  • Objects can contain multiple values of different data types.
  • Null, which represents the intentional absence of any object value.
  • Undefined, which represents a variable that has been declared but not yet assigned a value.

Variables in JavaScript can also be declared using the var, let, and const keywords.

Each of these keywords has different scoping rules and can be used in different situations.

Understanding the Difference between == and === Operators in JavaScript

The == and === operators in JavaScript are used to compare values. The == operator performs type coercion, which means that it converts the values being compared to a common data type before making the comparison. For example, the expression “5” == 5 would evaluate to true, because the string “5” is coerced into the number 5 before the comparison is made.

The === operator, on the other hand, performs a strict comparison that does not perform type coercion.

This means that the data types of the values being compared must be the same for the comparison to be true. For example, the expression “5” === 5 would evaluate to false, because the string “5” is not the same data type as the number 5.

In general, it is recommended to use the === operator for comparisons in JavaScript, as it avoids unexpected behavior that can result from type coercion.

Declaring a Function in JavaScript

Declaring a function in JavaScript involves defining a block of code that can be executed later in a program. Functions in JavaScript are declared using the function keyword, followed by the name of the function, and a set of parentheses that contain any arguments that the function accepts. The body of the function is then defined inside curly braces.

For example, the following code declares a function called “add” that accepts two arguments and returns their sum:

function add(a, b) {
return a + b;
}

Once a function is declared, it can be called later in the program using its name and passing any required arguments.

Understanding Hoisting in JavaScript

Hoisting in JavaScript refers to the behavior of moving variable and function declarations to the top of their respective scopes during the compilation phase of the program.

This means that even if a variable or function is declared after it is used in the code, the program will still behave as though the declaration occurred first.

For example, consider the following code:

x = 5;

console.log(x);

var x;

Even though the variable “x” is declared after it is used on the first line, the program will still output the value 5.

This is because the variable declaration is hoisted to the top of the scope, allowing the program to access it before it is officially declared.

It is important to note that only the declarations are hoisted, not the assignments.

This means that even though a variable or function declaration is hoisted to the top of the scope, any assignments made later in the code will still occur in their original order.

Understanding Closures in JavaScript

Closures in JavaScript are functions that have access to variables from an outer function that has already been returned. This allows the inner function to maintain access to the outer function’s scope, even after the outer function has completed execution.

For example, consider the following code:

function outerFunction() {
var outerVariable = "Hello, ";

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

return innerFunction;
}

var greeting = outerFunction();

greeting("John");

In this example, the outer function returns the inner function, which maintains access to the outer variable “outerVariable”.

When the inner function is called later in the program, it can still access this variable and output the message “Hello, John”.

Closures in JavaScript are a powerful feature that can be used to create functions that maintain state or encapsulate functionality.

JavaScript Basic Interview Questions

Understanding the Difference between let, const, and var in JavaScript

In JavaScript, variables can be declared using the let, const, and var keywords.

The main difference between these keywords lies in their scoping rules and whether the value of the variable can be reassigned.

The var keyword is used to declare variables with function scope or global scope. Variables declared with var can be reassigned and redeclared within their scope.

The let keyword is used to declare variables with block scope. Variables declared with let can be reassigned within their scope, but cannot be redeclared.

The const keyword is used to declare variables with block scope that cannot be reassigned. Once a value is assigned to a const variable, it cannot be changed.

For example:

function example() {
var x = 1;
let y = 2;
const z = 3;

if (true) {
var x = 4;
let y = 5;
const z = 6;

console.log(x, y, z); // output: 4 5 6
}

console.log(x, y, z); // output: 4 2 3
}

example();

In this example, the var variable “x” is reassigned within its scope, while the let variable “y” is only reassigned within its block scope. The const variable “z” cannot be reassigned at all.

Understanding the Different Types of Loops in JavaScript

Loops in JavaScript are used to execute a block of code repeatedly until a certain condition is met. There are several types of loops in JavaScript, including:

  • for loops: used to execute a block of code a specific number of times.
  • while loops: used to execute a block of code while a condition is true.
  • do-while loops: similar to while loops, but the block of code is always executed at least once.
  • for…in loops: used to loop over the properties of an object.
  • for…of loops: used to loop over the values of an iterable object, such as an array or string.

For example:

let numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

let i = 0;

while (i < numbers.length) {
console.log(numbers[i]);
i++;
}

do {
console.log(numbers[i]);
i++;
} while (i < numbers.length);

let person = { name: "John", age: 30, occupation: "Developer" };

for (let property in person) {
console.log(property, person[property]);
}

for (let number of numbers) {
console.log(number);
}

Handling Errors and Exceptions in JavaScript

Errors and exceptions are common occurrences in JavaScript, and it is important to handle them appropriately to ensure that the program runs smoothly. In JavaScript, errors can be caught using try…catch blocks.

A try block contains the code that might throw an error, while a catch block contains the code that handles the error if one is thrown.

If an error is thrown within the try block, the catch block will be executed with an error object that contains information about the error.

For example:

try {
let x = 1 / 0;
} catch (error) {
console.log("An error occurred:", error);
}

In this example, the code within the try block will throw an error because dividing by zero is not allowed. The catch block will then be executed, outputting a message that indicates an error occurred.

Understanding JSON and its Use in JavaScript

JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

JSON is often used for exchanging data between a server and a web application, as it can be easily converted to and from JavaScript objects.

In JavaScript, JSON data can be parsed using the JSON.parse() method, which takes a string containing JSON data and converts it to a JavaScript object. JSON data can also be created from a JavaScript object using the JSON.stringify() method, which converts the object to a JSON string.

For example:

let person = { name: "John", age: 30 };

let json = JSON.stringify(person);

console.log(json); // output: {"name":"John","age":30}

let object = JSON.parse(json);

console.log(object); // output: { name: "John", age: 30 }

Creating an Object in JavaScript and the Different Ways to Do It

Objects in JavaScript are used to store collections of data and functions that are related to a specific entity.

There are several ways to create objects in JavaScript, including:

  • Object literals: used to create a new object using curly braces and key-value pairs.
  • Constructor functions: used to create a new object using a function that acts as a constructor.
  • ES6 classes: used to create a new object using the class syntax.

For example:

// Object literal
let person = { name: "John", age: 30 };

// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
}

let john = new Person("John", 30);

// ES6 class
class Animal {
constructor(name) {
this.name = name;
}
}

let cat = new Animal("Fluffy");

Understanding Callbacks in JavaScript and How They Work

Callbacks in JavaScript are functions that are passed as arguments to other functions and are executed when the parent function has completed its task.

Callbacks are commonly used in asynchronous programming, where the parent function performs a task that takes some time to complete, and the callback function is executed once the task is finished.

For example, the setTimeout() function in JavaScript is used to delay the execution of a function by a certain number of milliseconds.

The setTimeout() function takes two arguments: a callback function to be executed after the delay, and the number of milliseconds to delay the execution.

function sayHello() {
console.log("Hello, world!");
}

setTimeout(sayHello, 1000);

In this example, the sayHello() function is passed as a callback to the setTimeout() function and is executed after a delay of 1000 milliseconds. Callbacks are an important part of JavaScript programming and are used extensively in many applications, including event handling, AJAX requests, and more.

Understanding the Event Loop in JavaScript and How it Works

The event loop in JavaScript is a mechanism that allows asynchronous code to be executed in a non-blocking manner. In JavaScript, all code is executed on a single thread, which means that long-running tasks can block the execution of other code.

The event loop works by constantly monitoring the call stack and the task queue. When the call stack is empty, the event loop checks the task queue for any pending tasks. If a task is found, it is added to the call stack and executed.

Asynchronous code in JavaScript can be created using callbacks, promises, and async/await syntax.

When a function that contains asynchronous code is called, it is added to the call stack and executed. However, when the asynchronous code is encountered, it is removed from the call stack and added to the task queue, allowing other code to be executed while the asynchronous code completes.

For example:

console.log("start");

setTimeout(() => {
console.log("timeout");
}, 0);

Promise.resolve().then(() => {
console.log("promise");
});

console.log("end");

In this example, the code is executed in the following order:

  1. “start” is output to the console.
  2. The setTimeout() function is added to the call stack, but because it has a delay of 0 milliseconds, it is immediately removed from the call stack and added to the task queue.
  3. The Promise.resolve() function is added to the call stack and executed. Because it contains a then() method, it is removed from the call stack and added to the microtask queue.
  4. “end” is output to the console.
  5. The event loop checks the microtask queue and executes the function passed to then().
  6. The event loop checks the task queue and executes the function passed to setTimeout().

JavaScript Intermediate Interview Questions

Manipulating the DOM Using JavaScript

The Document Object Model (DOM) in JavaScript is a programming interface that allows developers to manipulate the structure and content of a web page.

The DOM represents the HTML elements of a web page as a hierarchical tree of nodes, with each node representing an element, attribute, or piece of text.

To manipulate the DOM using JavaScript, developers can use methods and properties provided by the Document object, such as getElementById(), getElementsByClassName(), and querySelector().

These methods allow developers to select specific elements or groups of elements on a web page, and then modify their properties, attributes, or content.

For example:

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1 id="title">Hello, world!</h1>
<p class="content">Lorem ipsum dolor sit amet.</p>

<script>
let title = document.getElementById("title");
title.innerText = "New Title";

let content = document.getElementsByClassName("content");
content[0].style.color = "red";

let paragraph = document.createElement("p");
paragraph.innerText = "New Paragraph";
document.body.appendChild(paragraph);
</script>
</body>
</html>

In this example, the JavaScript code selects the h1 element with an id of “title” and changes its text to “New Title”.

It also selects the p element with a class of “content” and changes its color to red. Finally, it creates a new p element, sets its text to “New Paragraph”, and appends it to the body of the web page.

Understanding the Different Types of Events in JavaScript and How to Handle Them

Events in JavaScript are actions or occurrences that take place on a web page, such as a button click, a form submission, or a page load. There are several types of events in JavaScript, including:

  • Mouse events: such as click, mouseover, and mouseout.
  • Keyboard events: such as keydown, keyup, and keypress.
  • Form events: such as submit and reset.
  • Window events: such as load, resize, and scroll.

To handle events in JavaScript, developers can use event listeners or inline event handlers. Event listeners are functions that are executed when a specific event occurs on a specific element, while inline event handlers are functions that are specified in the HTML tag itself.

For example:

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<button id="btn">Click Me</button>

<script>
let button = document.getElementById("btn");
button.addEventListener("click", () => {
alert("Button clicked!");
});

function submitForm() {
alert("Form submitted!");
}
</script>

<form onsubmit="submitForm()">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>

In this example, the JavaScript code adds a click event listener to the button element that displays an alert message when the button is clicked. It also defines a function called submitForm() that displays an alert message when a form is submitted.

The form element contains an inline event handler that calls the submitForm() function when the form is submitted.

Events in JavaScript are a powerful feature that can be used to create interactive and dynamic web pages.

By understanding the different types of events and how to handle them, developers can create web applications that respond to user input and provide a great user experience.

Understanding the Difference between Synchronous and Asynchronous Programming in JavaScript

Synchronous programming in JavaScript is a programming paradigm where code is executed sequentially, blocking the execution of other code until the current task is complete.

In other words, each statement in the code is executed one after the other, in the order that they appear.

Asynchronous programming, on the other hand, is a programming paradigm where code is executed non-sequentially, allowing other code to run while the current task is still being executed.

Asynchronous programming in JavaScript is typically achieved through the use of callbacks, promises, and async/await syntax.

Synchronous programming can be useful when the code needs to be executed in a specific order, or when it is necessary to wait for a task to be completed before moving on to the next task.

Asynchronous programming, on the other hand, can be useful when the code needs to perform tasks that take a long time to complete, such as loading data from a server.

Using Promises in JavaScript

Promises in JavaScript are a programming construct that allows asynchronous code to be executed in a more readable and maintainable manner. Promises represent a value that may not be available yet, but will be available in the future.

A promise has three states: pending, fulfilled, and rejected. When a promise is pending, it means that the asynchronous operation is still in progress. When a promise is fulfilled, it means that the asynchronous operation has completed successfully, and the promised value is available. When a promise is rejected, it means that the asynchronous operation has failed, and the promise contains an error.

To use promises in JavaScript, developers can create a new Promise object, which takes a function that contains the asynchronous code. This function should call either the resolve() method if the operation is successful, or the reject() method if the operation fails.

For example:

function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded successfully!");
}, 1000);
});
}

getData()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});

In this example, the getData() function returns a new Promise object that resolves after a delay of 1000 milliseconds.

The then() method is called on the promise to handle the fulfilled state and log the data to the console. The catch() method is called to handle any errors that occur during the asynchronous operation.

Understanding the Different Methods to Create an Array in JavaScript

Arrays in JavaScript are used to store a collection of values in a single variable. There are several methods to create an array in JavaScript, including:

  • Array literals: used to create an array using square brackets and a list of comma-separated values.
  • Array constructor: used to create an array using the Array() constructor.
  • Array.from(): used to create an array from an array-like or iterable object.
  • Array.of(): used to create an array from a list of arguments.

For example:

// Array literal
let numbers = [1, 2, 3, 4, 5];

// Array constructor
let fruits = new Array("Apple", "Banana", "Orange");

// Array.from()
let str = "Hello, world!";
let chars = Array.from(str);

// Array.of()
let values = Array.of(1, "two", false, [4, 5, 6]);

In this example, the different methods to create an array in JavaScript are demonstrated. The array literal is used to create an array of numbers. The array constructor is used to create an array of fruits.

Sorting an Array in JavaScript

Sorting an array in JavaScript can be done using the sort() method, which sorts the elements of an array in place and returns the sorted array.

The sort() method sorts the elements of an array in ascending order by default, but a custom sorting function can be passed as an argument to the method to sort the elements in a different order.

For example:

let numbers = [5, 3, 7, 1, 9, 2, 6, 4, 8];

numbers.sort();

console.log(numbers); // output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

numbers.sort((a, b) => b - a);

console.log(numbers); // output: [9, 8, 7, 6, 5, 4, 3, 2, 1]

In this example, the sort() method is used to sort the numbers array in ascending order by default. The array is then sorted in descending order by passing a custom sorting function to the sort() method.

JavaScript Advanced Interview Questions | Predict the Output

Understanding the Difference between Map and Filter Methods in JavaScript

The map() and filter() methods in JavaScript are both used to transform arrays into new arrays.

The main difference between the two methods is the way they transform the original array.

The map() method creates a new array by applying a function to each element of the original array. The function returns a new value that is added to the new array. The new array has the same length as the original array.

For example:

let numbers = [1, 2, 3, 4, 5];

let doubled = numbers.map((num) => num * 2);

console.log(doubled); // output: [2, 4, 6, 8, 10]

In this example, the map() method is used to create a new array that contains the double of each element in the numbers array.

The filter() method creates a new array by filtering the elements of the original array based on a condition.

The condition is defined by a function that is passed as an argument to the method. The function returns true or false, depending on whether the element should be included in the new array.

The new array may have a different length than the original array.

For example:

let numbers = [1, 2, 3, 4, 5];

let even = numbers.filter((num) => num % 2 === 0);

console.log(even); // output: [2, 4]

In this example, the filter() method is used to create a new array that contains only the even numbers from the numbers array.

In summary, the map() method is used to transform each element in an array, while the filter() method is used to filter the elements of an array based on a condition.

Conclusion

mastering the fundamentals of JavaScript is essential for anyone who wants to build dynamic and interactive web applications.

This guide covered the basic concepts and techniques of JavaScript programming, including variables, data types, functions, control structures, and more.

We also explored more advanced topics such as arrays, objects, error handling, and the differences between synchronous and asynchronous programming.

We discussed how to use promises, callbacks, and the DOM to manipulate and handle events in JavaScript.

By mastering these fundamentals, you will have a solid foundation to build on as you continue to learn and develop your JavaScript skills.

Whether you’re a beginner or an experienced developer, the principles and techniques covered in this guide are essential to becoming a proficient and effective JavaScript programmer.

So, go ahead and start practicing your JavaScript skills by working on projects, solving coding challenges, and reading up on the latest trends and techniques in JavaScript programming.

With dedication and practice, you will be well on your way to becoming a skilled and successful JavaScript developer.

You may also like:

--

--