Create a Video and Audio Recorder with JavaScript MediaRecorder API
Last Updated :
16 Mar, 2021
WebRTC is very popular for accessing device cameras and device microphones and streaming the video or audio media in the browser. But in many cases, we might need to record the streaming for future use or for users (Like user might want to download the streaming, etc.). In that case, we can use the MediaRecorder API to record the media streaming.
In this article, we will create a basic Video and Audio Recorder website using pure JavaScript and its MediaRecorder API.
The Project Description: The website we are building will have-
- A select option to let the users choose what type of media (audio or video with audio) to record.
- If the user chooses to record video then the browser will ask for permission to access the device camera and microphone and if the user allows it, then —
- A video element will display the camera media stream
- The "Start Recording" button will start the recording
- The "Stop Recording" button will stop the recording.
- When the recording is complete, a new video element containing the recorded media gets displayed.
- A link to let the users download the recorded video.
- If the user chooses to record only audio, then the browser will ask for permission to access the microphone, and if the user allows it, then —
- The "Start Recording" button will start the recording
- The "Stop Recording" button will stop the recording
- When the recording is done, a new audio element containing the recorded audio gets displayed.
- A link is given to let the users download the recorded audio.
So, let's first set up our simple HTML page —
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<title>Video & Audio Recorder</title>
</head>
<body>
<h1> Video & Audio Recorder </h1>
<label for="media">
Select what you want to record:
</label>
<select id="media">
<option value="choose-an-option">
Choose an option
</option>
<option value="vid">Video</option>
<option value="aud">Audio</option>
</select>
<div class="display-none" id="vid-recorder">
<h3>Record Video </h3>
<video autoplay id="web-cam-container"
style="background-color: black;">
Your browser doesn't support
the video tag
</video>
<div class="recording" id="vid-record-status">
Click the "Start video Recording"
button to start recording
</div>
<!-- This button will start the video recording -->
<button type="button" id="start-vid-recording"
onclick="startRecording(this,
document.getElementById('stop-vid-recording'))">
Start video recording
</button>
<!-- This button will stop the video recording -->
<button type="button" id="stop-vid-recording"
disabled onclick="stopRecording(this,
document.getElementById('start-vid-recording'))">
Stop video recording
</button>
<!--The video element will be created using
JavaScript and contains recorded video-->
<!-- <video id="recorded-video" controls>
Your browser doesn't support the video tag
</video> -->
<!-- The below link will let the
users download the recorded video -->
<!-- <a href="" > Download it! </a> -->
</div>
<div class="display-none" id="aud-recorder">
<h3> Record Audio</h3>
<div class="recording" id="aud-record-status">
Click the "Start Recording"
button to start recording
</div>
<button type="button" id="start-aud-recording"
onclick="startRecording(this,
document.getElementById('stop-aud-recording'))">
Start recording
</button>
<button type="button" id="stop-aud-recording"
disabled onclick="stopRecording(this,
document.getElementById('start-aud-recording'))">
Stop recording
</button>
<!-- The audio element will contain the
recorded audio and will be created
using Javascript -->
<!-- <audio id="recorded-audio"
controls></audio> -->
<!-- The below link will let the users
download the recorded audio -->
<!-- <a href="" > Download it! </a> -->
</div>
<script src="index.js"></script>
</body>
</html>
Output:
If you check the index.html carefully, you will see that the video and audio tags are not given any source, We will add the sources later using JavaScript. For now, we have a select option that lets the user select the type of media they want to record. The first video element inside the "vid-recorder" div element will contain the webcam stream and the video element in the comments will contain the recorded video. Notice that only the last video element has the "controls" attribute as the first video element will contain the stream and don't need any controls.
Inside the "aud-recorder" div, we have two buttons to start and stop the recording, the commented audio element will contain recorded audio.
Now, let's add some CSS to the HTML page —
index.css
body {
text-align: center;
color: green;
font-size: 1.2em;
}
.display-none {
display: none;
}
.recording {
color: red;
background-color: rgb(241 211 211);
padding: 5px;
margin: 6px auto;
width: fit-content;
}
video {
background-color: black;
display: block;
margin: 6px auto;
width: 420px;
height: 240px;
}
audio {
display: block;
margin: 6px auto;
}
a {
color: green;
}
Output:
For now, we have added the "display-none" class to the "vid-recorder" and "aud-recorder" divs. As we want to display the correct recorder based on the user's choice.
Now, let's implement the logic to display only the user-selected recorder using JavaScript—
index.js
const mediaSelector = document.getElementById("media");
let selectedMedia = null;
// Handler function to handle the "change" event
// when the user selects some option
mediaSelector.addEventListener("change", (e) => {
selectedMedia = e.target.value;
document.getElementById(
`${selectedMedia}-recorder`).style.display = "block";
document.getElementById(
`${otherRecorder(selectedMedia)}-recorder`)
.style.display = "none";
});
function otherRecorder(selectedMedia) {
return selectedMedia === "vid" ? "aud" : "vid";
}
Output: When the user selects "video", the following video recorder is displayed —
Similarly, when the user selects the "audio" option, the audio recorder gets displayed —
The above code displays only the user-selected recorder i.e. audio or video. We have added a "change" event listener to the mediaSelector element, when the value of the select element changes, it emits a "change" event and the event is handled by the given callback function. The callback function changes the CSS "display" property of the selected media recorder to "block" and other media recorder to "none".
Accessing the Web cam and microphone: The WebRTC getUserMedia API lets you access the device camera and microphone. The getUserMedia() method returns a Promise that resolves to a MediaStream which contains the media contents (a stream of media tracks) based on the given specifications. The getUserMedia() method takes a MediaStreamConstraints object as the parameter that defines all the constraints the resulting media stream should match.
const mediaStreamConstraints = {
audio: true,
video: true
};
// The above MediaStreamConstraints object
// specifies that the resulting media must have
// both the video and audio media content or tracks.
// The mediaStreamConstraints object is passed to
// the getUserMedia method
navigator.mediaDevices.getUserMedia( MediaStreamConstraints )
.then( resultingMediaStream => {
// Code to use the received media stream
});
When the getUserMedia method is invoked, the browser prompts the user asking for permission to use the device camera and microphone. If the user allows it, then the promise returned by getUserMedia resolves to the resulting media stream, otherwise, it throws a NotAllowedError exception. In the above code, the received media stream contains both the video and audio media data.
So, add the below lines of code to the index.js file :
index.js
const mediaSelector =
document.getElementById("media");
// Added code
const webCamContainer = document
.getElementById('web-cam-container');
let selectedMedia = null;
/* Previous code
...
Added code */
const audioMediaConstraints = {
audio: true,
video: false
};
const videoMediaConstraints = {
// or you can set audio to false
// to record only video
audio: true,
video: true
};
function startRecording(thisButton, otherButton) {
navigator.mediaDevices.getUserMedia(
selectedMedia === "vid" ?
videoMediaConstraints :
audioMediaConstraints)
.then(mediaStream => {
// Use the mediaStream in
// your application
// Make the mediaStream global
window.mediaStream = mediaStream;
if (selectedMedia === 'vid') {
// Remember to use the "srcObject"
// attribute since the "src" attribute
// doesn't support media stream as a value
webCamContainer.srcObject = mediaStream;
}
document.getElementById(
`${selectedMedia}-record-status`)
.innerText = "Recording";
thisButton.disabled = true;
otherButton.disabled = false;
});
}
function stopRecording(thisButton, otherButton) {
// Stop all the tracks in the received
// media stream i.e. close the camera
// and microphone
window.mediaStream.getTracks().forEach(track => {
track.stop();
});
document.getElementById(
`${selectedMedia}-record-status`)
.innerText = "Recording done!";
thisButton.disabled = true;
otherButton.disabled = false;
}
The startRecording function invokes the navigator.mediaDevices.getUserMedia() method to access the device camera and microphone, disables the "start recording" button, and enables the "stop recording" button. Whereas, the stopRecording function closes the camera and microphone by calling the "stop()" method of each media track used by the media stream, disables the "stop recording" button, and enables the "start recording" button.
Implementing the Recorder: Until now, we have only accessed the webcam and microphone but didn't do anything to record the media.
To record a media stream, we first need to create an instance of MediaRecorder( an interface for recording media streams ) using the MediaRecorder constructor.
The MediaRecorder constructor takes two parameters —
- stream: A stream is like a flow of data( data of any type). Here in this article, we will use MediaStream which is basically a stream of media(video or audio or both) data or media content.
- Options( optional ): An object containing some specifications about the recording. You can set the MIME-type of the recorded media, the audio bit rate, video bit rate, etc. MIME-type is a standard that represents the format of the recorded media file( for example, the two MIME types — "audio/webm", "video/mp4" indicate an audio webm file and a video mp4 file respectively).
Syntax:
const mediaRecorder = new MediaRecorder(
stream, { mimeType: "audio/webm" });
The above line of code creates a new MediaRecorder instance that records the given stream and stores it as an audio WebM file.
So, modify your index.js file :
index.js file
/* Previous code
... */
function startRecording(thisButton, otherButton) {
navigator.mediaDevices.getUserMedia(
selectedMedia === "vid" ?
videoMediaConstraints :
audioMediaConstraints)
.then(mediaStream => {
/* New code */
// Create a new MediaRecorder
// instance that records the
// received mediaStream
const mediaRecorder =
new MediaRecorder(mediaStream);
// Make the mediaStream global
window.mediaStream = mediaStream;
// Make the mediaRecorder global
// New line of code
window.mediaRecorder = mediaRecorder;
if (selectedMedia === 'vid') {
// Remember to use the srcObject
// attribute since the src attribute
// doesn't support media stream as a value
webCamContainer.srcObject = mediaStream;
}
document.getElementById(
`${selectedMedia}-record-status`)
.innerText = "Recording";
thisButton.disabled = true;
otherButton.disabled = false;
});
}
/* Remaining code
...*/
When the startRecording() function gets invoked, it creates a MediaRecorder instance to record the received mediaStream. Now, we need to use the created MediaRecorder instance. MediaRecorder provides some useful methods that we can use here —
- start(): When this method is invoked, the MediaRecorder instance starts recording the given media stream. Optionally takes "timeslice" as an argument which is specified will result in recording the given media in small separate chunks of that time slice duration.
- pause(): When invoked, pauses the recording
- resume(): When invoked after invoking the pause( ) method, resumes the recording.
- stop(): When invoked, stops the recording and fires a "dataavailable" event containing the final Blob of the saved data.
- requestData() : When invoked, requests a Blob containing data saved till now.
Similarly, MediaRecorder also provides some useful Event Handlers —
- ondataavailable: Event Handler for "dataavailable" event. Whenever the timeslice (if specified) milliseconds of media data is recorded or when the recording is done(if timeslice is not specified), the MediaRecorder emits a "dataavailable" event with the recorded Blob data. This data can be obtained from the "data" property of the "event" —
mediaRecorder.ondataavailable = ( event ) => {
const recordedData = event.data;
}
- onstop: Event Handler for the "stop" event emitted by MediaRecorder. This event is emitted when the MediaRecorder.stop() method is called or when the corresponding MediaStream is stopped.
- onerror: Handler for the "error" event which is emitted whenever an error occurs while using the MediaRecorder. The "error" property of the event contains the details of the error —
mediaRecorder.onerror = ( event ) => {
console.log(event.error);
}
- onstart : Handler for the "start" event which is emitted when the MediaRecorder starts recording.
- onpause: Handler for the "pause" event. This event is emitted when the recording is paused.
- onresume : Handler for the " resume" event. This event is emitted when the recording is resumed again after being paused.
Now, we need to use some of these methods and event handlers to make our project work.
index.js
const mediaSelector = document.getElementById("media");
const webCamContainer =
document.getElementById("web-cam-container");
let selectedMedia = null;
// This array stores the recorded media data
let chunks = [];
// Handler function to handle the "change" event
// when the user selects some option
mediaSelector.addEventListener("change", (e) => {
// Takes the current value of the mediaSeletor
selectedMedia = e.target.value;
document.getElementById(
`${selectedMedia}-recorder`)
.style.display = "block";
document.getElementById(
`${otherRecorderContainer(
selectedMedia)}-recorder`)
.style.display = "none";
});
function otherRecorderContainer(
selectedMedia) {
return selectedMedia === "vid" ?
"aud" : "vid";
}
// This constraints object tells
// the browser to include only
// the audio Media Track
const audioMediaConstraints = {
audio: true,
video: false,
};
// This constraints object tells
// the browser to include
// both the audio and video
// Media Tracks
const videoMediaConstraints = {
// or you can set audio to
// false to record
// only video
audio: true,
video: true,
};
// When the user clicks the "Start
// Recording" button this function
// gets invoked
function startRecording(
thisButton, otherButton) {
// Access the camera and microphone
navigator.mediaDevices.getUserMedia(
selectedMedia === "vid" ?
videoMediaConstraints :
audioMediaConstraints)
.then((mediaStream) => {
// Create a new MediaRecorder instance
const mediaRecorder =
new MediaRecorder(mediaStream);
//Make the mediaStream global
window.mediaStream = mediaStream;
//Make the mediaRecorder global
window.mediaRecorder = mediaRecorder;
mediaRecorder.start();
// Whenever (here when the recorder
// stops recording) data is available
// the MediaRecorder emits a "dataavailable"
// event with the recorded media data.
mediaRecorder.ondataavailable = (e) => {
// Push the recorded media data to
// the chunks array
chunks.push(e.data);
};
// When the MediaRecorder stops
// recording, it emits "stop"
// event
mediaRecorder.onstop = () => {
/* A Blob is a File like object.
In fact, the File interface is
based on Blob. File inherits the
Blob interface and expands it to
support the files on the user's
systemThe Blob constructor takes
the chunk of media data as the
first parameter and constructs
a Blob of the type given as the
second parameter*/
const blob = new Blob(
chunks, {
type: selectedMedia === "vid" ?
"video/mp4" : "audio/mpeg"
});
chunks = [];
// Create a video or audio element
// that stores the recorded media
const recordedMedia = document.createElement(
selectedMedia === "vid" ? "video" : "audio");
recordedMedia.controls = true;
// You can not directly set the blob as
// the source of the video or audio element
// Instead, you need to create a URL for blob
// using URL.createObjectURL() method.
const recordedMediaURL = URL.createObjectURL(blob);
// Now you can use the created URL as the
// source of the video or audio element
recordedMedia.src = recordedMediaURL;
// Create a download button that lets the
// user download the recorded media
const downloadButton = document.createElement("a");
// Set the download attribute to true so that
// when the user clicks the link the recorded
// media is automatically gets downloaded.
downloadButton.download = "Recorded-Media";
downloadButton.href = recordedMediaURL;
downloadButton.innerText = "Download it!";
downloadButton.onclick = () => {
/* After download revoke the created URL
using URL.revokeObjectURL() method to
avoid possible memory leak. Though,
the browser automatically revokes the
created URL when the document is unloaded,
but still it is good to revoke the created
URLs */
URL.revokeObjectURL(recordedMedia);
};
document.getElementById(
`${selectedMedia}-recorder`).append(
recordedMedia, downloadButton);
};
if (selectedMedia === "vid") {
// Remember to use the srcObject
// attribute since the src attribute
// doesn't support media stream as a value
webCamContainer.srcObject = mediaStream;
}
document.getElementById(
`${selectedMedia}-record-status`)
.innerText = "Recording";
thisButton.disabled = true;
otherButton.disabled = false;
});
}
function stopRecording(thisButton, otherButton) {
// Stop the recording
window.mediaRecorder.stop();
// Stop all the tracks in the
// received media stream
window.mediaStream.getTracks()
.forEach((track) => {
track.stop();
});
document.getElementById(
`${selectedMedia}-record-status`)
.innerText = "Recording done!";
thisButton.disabled = true;
otherButton.disabled = false;
}
Output:
Suppose, the user selects the audio recorder —
Now, if the user clicks the start recording button, then —
And when the "stop recording" button is clicked —
It displays the recorded audio and gives a link to download the recorded audio.
So, what does the startRecording( ) function do?- It invokes the navigator.mediaDevices.getUserMedia() method and accesses the device camera or microphone or both. This method returns a Promise that resolves to a MediaStream.
- After receiving the MediaStream, it creates an instance of MediaRecorder that can record the given MediaStream, makes both the MediaStream and the MediaRecorder global so that we can use them outside the startRecording function —
window.mediaStream = mediaStream;
window.mediaRecorder = mediaRecorder;
- Starts the recording of the given MediaStream by calling the MediaRecorder.start() method.
mediaRecorder.start();
- Defines the event handlers for the created MediaRecorder. The "dataavailable" event handler function pushes the recorded data to the chunks array (Array of recorded media data Blob). The "stop" event handler function.
- Creates a new Blob from the chunks array using the Blob() constructor.
- Re-initializes the chunks array
- Creates a URL for the created Blob using URL.createObjectURL() method.
- Sets the source of the newly created "video"/"audio" element to the created URL.
- Creates a link to download the recorded media and revokes the created URL after the link is clicked using URL.revokeObjectURL() method.
- Disables the "start recording" button and enables the "stop recording" button.
What does the stopRecording() function do?- Stops the recording by calling the MediaRecorder.stop() method.
- Stops all the Media Tracks of the MediaStream i.e. close the camera and the microphone
- Disables the "stop recording" button and enables the "start recording" button.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.Client Side: On the client side, JavaScript works
11 min read
JavaScript Basics
Introduction to JavaScriptJavaScript is a versatile, dynamically typed programming language that brings life to web pages by making them interactive. It is used for building interactive web applications, supports both client-side and server-side development, and integrates seamlessly with HTML, CSS, and a rich standard libra
4 min read
JavaScript VersionsJavaScript is a popular programming language used by developers all over the world. Itâs a lightweight and easy-to-learn language that can run on both the client-side (in your browser) and the server-side (on the server). JavaScript was created in 1995 by Brendan Eich.In 1997, JavaScript became a st
2 min read
How to Add JavaScript in HTML Document?To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file.Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other ev
3 min read
JavaScript SyntaxJavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.Syntaxconsole.log("Basic Print method in JavaScript");Ja
6 min read
JavaScript OutputJavaScript provides different methods to display output, such as console.log(), alert(), document.write(), and manipulating HTML elements directly. Each method has its specific use cases, whether for debugging, user notifications, or dynamically updating web content. Here we will explore various Jav
4 min read
JavaScript CommentsComments help explain code (they are not executed and hence do not have any logic implementation). We can also use them to temporarily disable parts of your code.1. Single Line CommentsA single-line comment in JavaScript is denoted by two forward slashes (//), JavaScript// A single line comment cons
2 min read
JS Variables & Datatypes
Variables and Datatypes in JavaScriptVariables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.Data TypesVariabl
6 min read
Global and Local variables in JavaScriptIn JavaScript, understanding the difference between global and local variables is important for writing clean, maintainable, and error-free code. Variables can be declared with different scopes, affecting where and how they can be accessed. Global VariablesGlobal variables in JavaScript are those de
4 min read
JavaScript LetThe let keyword is a modern way to declare variables in JavaScript and was introduced in ECMAScript 6 (ES6). Unlike var, let provides block-level scoping. This behaviour helps developers avoid unintended issues caused by variable hoisting and scope leakage that are common with var.Syntaxlet variable
6 min read
JavaScript constThe const keyword in JavaScript is a modern way to declare variables, introduced in (ES6). It is used to declare variables whose values need to remain constant throughout the lifetime of the application.const is block-scoped, similar to let, and is useful for ensuring immutability in your code. Unli
5 min read
JavaScript Var StatementThe var keyword is used to declare variables in JavaScript. It has been part of the language since its inception. When a variable is declared using var, it is function-scoped or globally-scoped, depending on where it is declared.Syntaxvar variable = value;It declares a variable using var, assigns it
7 min read
JS Operators
JavaScript OperatorsJavaScript operators are symbols or keywords used to perform operations on values and variables. They are the building blocks of JavaScript expressions and can manipulate data in various ways.There are various operators supported by JavaScript:1. JavaScript Arithmetic OperatorsArithmetic Operators p
5 min read
Operator precedence in JavaScriptOperator precedence refers to the priority given to operators while parsing a statement that has more than one operator performing operations in it. Operators with higher priorities are resolved first. But as one goes down the list, the priority decreases and hence their resolution. ( * ) and ( / )
2 min read
JavaScript Arithmetic OperatorsJavaScript Arithmetic Operators are the operator that operate upon the numerical values and return a numerical value. Addition (+) OperatorThe addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers.JavaScript// Number + Number =>
5 min read
JavaScript Assignment OperatorsAssignment operators are used to assign values to variables in JavaScript.JavaScript// Lets take some variables x = 10 y = 20 x = y ; console.log(x); console.log(y); Output20 20 More Assignment OperatorsThere are so many assignment operators as shown in the table with the description.OPERATOR NAMESH
5 min read
JavaScript Comparison OperatorsJavaScript comparison operators are essential tools for checking conditions and making decisions in your code. 1. Equality Operator (==) The Equality operator is used to compare the equality of two operands. JavaScript// Illustration of (==) operator let x = 5; let y = '5'; // Checking of operands c
5 min read
JavaScript Logical OperatorsLogical operators in JavaScript are used to perform logical operations on values and return either true or false. These operators are commonly used in decision-making statements like if or while loops to control the flow of execution based on conditions.In JavaScript, there are basically three types
5 min read
JavaScript Bitwise OperatorsIn JavaScript, a number is stored as a 64-bit floating-point number but bitwise operations are performed on a 32-bit binary number. To perform a bit-operation, JavaScript converts the number into a 32-bit binary number (signed) and performs the operation and converts back the result to a 64-bit numb
5 min read
JavaScript Ternary OperatorThe Ternary Operator in JavaScript is a conditional operator that evaluates a condition and returns one of two values based on whether the condition is true or false. It simplifies decision-making in code, making it more concise and readable. Syntaxcondition ? trueExpression : falseExpressionConditi
4 min read
JavaScript Comma OperatorJavaScript Comma Operator mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. JavaScriptlet x = (1, 2, 3); console.log(x); Output3 Here is another example to show that all expressions are actually executed.JavaScriptlet a = 1, b = 2, c = 3; l
2 min read
JavaScript Unary OperatorsJavaScript Unary Operators work on a single operand and perform various operations, like incrementing/decrementing, evaluating data type, negation of a value, etc.Unary Plus (+) OperatorThe unary plus (+) converts an operand into a number, if possible. It is commonly used to ensure numerical operati
4 min read
JavaScript in and instanceof operatorsJavaScript Relational Operators are used to compare their operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result.JavaScript in OperatorThe in-operator in JavaScript checks if a specified property exists in an object or if an e
3 min read
JavaScript String OperatorsJavaScript String Operators are used to manipulate and perform operations on strings. There are two operators which are used to modify strings in JavaScript. These operators help us to join one string to another string.1. Concatenate OperatorConcatenate Operator in JavaScript combines strings using
3 min read
JS Statements
JS Loops
JavaScript LoopsLoops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as long as a specified condition is true. This makes code more concise and efficient.Suppose we want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly, we can u
3 min read
JavaScript For LoopJavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. Syntaxfor (statement 1 ; statement 2 ; statement 3){ code here...}Statement 1: It is the initialization of
4 min read
JavaScript While LoopThe while loop executes a block of code as long as a specified condition is true. In JavaScript, this loop evaluates the condition before each iteration and continues running as long as the condition remains true.Syntaxwhile (condition) { Code block to be executed}Here's an example that prints from
3 min read
JavaScript For In LoopThe JavaScript for...in loop iterates over the properties of an object. It allows you to access each key or property name of an object.JavaScriptconst car = { make: "Toyota", model: "Corolla", year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }Outputmake: Toyota model: Corolla
3 min read
JavaScript for...of LoopThe JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have bre
3 min read
JavaScript do...while LoopA do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the co
4 min read
JS Perfomance & Debugging
JS Object
Objects in JavascriptAn object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime.There are two primary w
4 min read
Object Oriented Programming in JavaScriptObject Oriented Programming (OOP) is a style of programming that uses classes and objects to model real-world things like data and behavior. A class is a blueprint that defines the properties and methods an object can have, while an object is a specific instance created from that class. Why OOP is N
3 min read
JavaScript ObjectsIn our previous article on Introduction to Object Oriented Programming in JavaScript we have seen all the common OOP terminology and got to know how they do or don't exist in JavaScript. In this article, objects are discussed in detail.Creating Objects:In JavaScript, Objects can be created using two
6 min read
Creating objects in JavaScriptAn object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, e
5 min read
JavaScript JSON ObjectsJSON (JavaScript Object Notation) is a handy way to share data. It's easy for both people and computers to understand. In JavaScript, JSON helps organize data into simple objects. Let's explore how JSON works and why it's so useful for exchanging information.const jsonData = { "key1" : "value1", ...
3 min read
JavaScript Object ReferenceJavaScript Objects are the most important data type and form the building blocks for modern JavaScript. The "Object" class represents the JavaScript data types. Objects are quite different from JavaScriptâs primitive data types (Number, String, Boolean, null, undefined, and symbol). It is used to st
4 min read
JS Function
Functions in JavaScriptFunctions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
4 min read
How to write a function in JavaScript ?JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
JavaScript Function CallThe call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). This allows borrowing methods from other objects, executing them within a different context, overriding the default value, and passing arguments. Syntax: cal
2 min read
Different ways of writing functions in JavaScriptA JavaScript function is a block of code designed to perform a specific task. Functions are only executed when they are called (or "invoked"). JavaScript provides different ways to define functions, each with its own syntax and use case.Below are the ways of writing functions in JavaScript:Table of
3 min read
Difference between Methods and Functions in JavaScriptGrasping the difference between methods and functions in JavaScript is essential for developers at all levels. While both are fundamental to writing effective code, they serve different purposes and are used in various contexts. This article breaks down the key distinctions between methods and funct
3 min read
Explain the Different Function States in JavaScriptIn JavaScript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions. Â In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( )
3 min read
JavaScript Function Complete ReferenceA JavaScript function is a set of statements that takes inputs, performs specific computations, and produces outputs. Essentially, a function performs tasks or computations and then returns the result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function body}Example: Be
3 min read
JS Array
JavaScript ArraysIn JavaScript, an array is an ordered list of values. Each value, known as an element, is assigned a numeric position in the array called its index. The indexing starts at 0, so the first element is at position 0, the second at position 1, and so on. Arrays can hold any type of dataâsuch as numbers,
7 min read
JavaScript Array MethodsTo help you perform common tasks efficiently, JavaScript provides a wide variety of array methods. These methods allow you to add, remove, find, and transform array elements with ease.Javascript Arrays Methods1. JavaScript Array length The length property of an array returns the number of elements i
7 min read
Best-Known JavaScript Array MethodsAn array is a special variable in all programming languages used to store multiple elements. JavaScript array come with built-in methods that every developer should know how to use. These methods help in adding, removing, iterating, or manipulating data as per requirements.There are some Basic JavaS
6 min read
Important Array Methods of JavaScriptJavaScript arrays are powerful tools for managing collections of data. They come with a wide range of built-in methods that allow developers to manipulate, transform, and interact with array elements.Some of the most important array methods in JavaScript areTable of Content1. JavaScript push() Metho
7 min read
JavaScript Array ReferenceJavaScript Array is used to store multiple elements in a single variable. It can hold various data types, including numbers, strings, objects, and even other arrays. It is often used when we want to store a list of elements and access them by a single variable.Syntax:const arr = ["Item1", "Item2", "
4 min read