JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive forms, and many more.
JavaScript, in short JS, was created in 1995 by Brendan Eich, who was working at Netscape Communications. In the beginning, it was designed to add interactivity to websites. Currently, JavaScript can support both client-side and server-side development. It plays a very important role in modern web apps by helping developers manipulate the Document Object Model (DOM), handle user events, and communicate with servers asynchronously.
These are the following topics that we are going to discuss:
Evolution of JavaScript
JavaScript has undergone significant evolution to meet the demands of web development:
- ECMAScript Standards: JavaScript is based on ECMAScript standards, which define the language syntax, semantics, and libraries. ECMAScript 6 (ES6), released in 2015, it introduced major enhancements such as arrow functions, classes, modules, and promises.
- Browser Compatibility: Early versions of JavaScript varied between web browsers, which caused compatibility issues. Today, modern browsers and JavaScript engines conform closely to ECMAScript standards, which makes sure the behavior is consistent across different platforms.
JavaScript is an old programming language. Initially, it was quite basic, but as web development needs grew, so did JavaScript. Here are some key updates:
- ECMAScript 3 (1999): Added useful features like regular expressions for searching text and try/catch for handling errors.
- ECMAScript 5 (2009): Introduced strict mode to help catch errors and support for JSON (JavaScript Object Notation).
- ECMAScript 6 (2015): Also known as ES6, it brought major improvements like let and const for variable declaration and arrow functions for cleaner syntax.
There are so many more updates of JavaScript, currently, it is on the 15th edition which is ECMAScript 2024.
JavaScript Engines
JavaScript engines are responsible for executing JavaScript code. The two most important JavaScript engines are V8 (used in Chrome and Node.js) and SpiderMonkey (used in Firefox). These engines follow a similar process to interpret and execute JavaScript:
How JavaScript Engines Interpret and Execute Code?
- Parsing: When we load a webpage or execute a script, the JavaScript engine first parses the source code to understand its structure. It converts the code into an Abstract Syntax Tree (AST) which is a hierarchical representation of the script.
- Compilation: Now in compilation phase, the engine translates the AST into machine-readable bytecode using JIT (Just-In-Time) compilation. JIT compilation optimizes performance by compiling frequently executed code segments at runtime.
- Execution: Finally, the bytecode or machine code is executed line by line, which produces the output or behavior as defined by the JavaScript code.
Example: Here, the engine parses the calculateSum function, compiles it into bytecode or machine code, executes it with arguments 3 and 4, and logs 7 to the console.
JavaScript
function calculateSum(a, b) {
return a + b;
}
let result = calculateSum(3, 4);
console.log(result); // Output: 7
Execution Contexts in JavaScript
JavaScript operates within execution contexts, which define the environment in which code is executed. Whenever we run a JavaScript code, a new execution context is created and if there is any proper function call (proper function means not arrow function or variable directly defining and calling a function), the execution context for that function is created inside the execution context of global execution context. If the function returns , the function's execution context is deleted and if there is no more code left, the global execution context is also deleted.
There are two main types of execution contexts:
- Global Execution Context in JavaScript :The global execution context is the default context in which JavaScript code runs. It includes global variables and functions accessible throughout the script.
- Function Execution Context in JavaScript :Every time a function is invoked, a new function execution context is created. This context manages local variables, function arguments, and the function's return value.
Call Stack and Management of Function Calls in JavaScript
The call stack is a data structure that tracks function calls in JavaScript. When a function is invoked, its context is pushed onto the call stack. Once the function completes execution, its context is popped off the stack.
The call is stack keeps track the order of execution of execution context.
The call stack contains its first function as the global execution context then if there is a function call , the execution context of that function is pushed inside the stack and if it returns, the call stack pops out the execution context of that function. After completing the whole code execution, the global execution context at bottom of the stack is also popped out which implies the code has been executed.
Example: Here, First () is called and added to the call stack. It again calls second(), which is then added to the stack.Now, second () completes execution and is removed from the stack. First () completes execution and is removed from the stack.
JavaScript
function first() {
console.log("First function");
second();
}
function second() {
console.log("Second function");
}
first();
OutputFirst function
Second function
Asynchronous Tasks and Event Loop in JavaScript
JavaScript is single-threaded, meaning it can only execute one task at a time. It also employs asynchronous programming techniques to handle multiple tasks concurrently without blocking the main thread.
Asynchronous TasksEvent Loop, Callback Queue, and Microtask Queue
The event loop
Event loop is a mechanism that continuously checks the call stack and manages asynchronous tasks in JavaScript. It ensures that tasks are executed in the correct order and which prevents the main thread from being blocked.
event loop in jsCallback queue and microtask queue
It hold tasks which are ready to be executed once the call stack is empty. Promises uses the microtask queue for handling asynchronous operations with higher priority.
Example: The code logs "Start" and "End" immediately since they are synchronous; the promise resolves next due to its microtask priority, logging "Promise," and finally, the setTimeout callback is executed, logging "Timeout," even though it's set to 0ms, as it is placed in the callback queue, which runs after microtasks.
JavaScript
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
Promise.resolve().then(() => {
console.log("Promise");
});
console.log("End");
OutputStart
End
Promise
Timeout
Memory Management in JavaScript
JavaScript manages memory allocation in dynamic way to store variables, objects, and functions during runtime.
Allocation of Memory
- Primitive Values: Stored directly in the stack memory.
- Objects and Functions: Stored in the heap memory, and references are stored in the stack.
Garbage Collection
JavaScript has automatic garbage collection to get memory occupied by objects that are no longer reachable or referenced by the program. This process helps us to efficiently manage memory and prevent memory leaks.
Example: This example demonstrates the garbage Collection.
JavaScript
let obj = {
name: "John"
};
obj = null;
// Object is no longer referenced and eligible for garbage collection
Call Stack vs. Heap (for function execution)
The call stack manages function calls and their contexts, while the heap is used for dynamic memory allocation during runtime.
Call Stack (for function execution)
- Function Calls: Manages the execution context of function calls in JavaScript.
- Last In, First Out (LIFO): Operates on a LIFO principle where the most recently called function is processed first.
- Context Management: Tracks where the execution is in the program with the current function's context.
- Single Threaded: Executes code sequentially, allowing only one function to be processed at a time.
- Example: When a function is called (functionA()), its context is pushed onto the call stack. When it completes, its context is popped off, allowing the next function (functionB()) to be processed.
Heap (for function execution)
- Memory Allocation: Used for dynamic memory allocation during runtime.
- Objects and References: Stores objects and variables that are accessed globally or referenced from the call stack.
- Garbage Collection: Managed by the JavaScript engine to reclaim memory occupied by objects that are no longer in use.
- Example: Objects like arrays or complex data structures (let obj = { key: value }) are stored in the heap. Variables referencing these objects are stored in the call stack.
Execution Phases in JavaScript
JavaScript code execution can be broadly divided into two phases: the Compilation Phase and the Execution Phase.
Compilation Phase:
- Syntax Analysis: The JavaScript engine parses the source code to understand its structure.
- Memory Allocation: Allocates memory for variables and functions (hoisting).
- Example: During compilation, function and variable declarations are processed first, allowing them to be accessed before they are defined in the code (console.log(greet());).
Execution Phase:
- Code Execution: Executes the compiled code line by line.
- Evaluation of Expressions: Processes expressions, function calls, and operations defined in the code.
- Example: After compilation, the engine starts executing from top to bottom, evaluating expressions and performing operations (function greet() { return "Hello"; }).
Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope during the compilation phase. Function declarations '(function greet() { ... })' are fully hoisted, meaning they can be called before they are defined in the code. Variable declarations '(let, const, var)' are hoisted but not their assignments '(let x = 10; hoists let x; but not x = 10;)'.
Example: This demonstrates the hoisting in Javascript.
JavaScript
console.log(greet()); // Output: Hello
function greet() {
return "Hello";
}
Output:
Hello
Node.js Runtime in JavaScript
Node.js extends JavaScript's capabilities beyond the browser, which enables server-side scripting and development of scalable network applications. It provides built-in modules for file system operations, networking, and HTTP server creation.
Example: This code reads text file in node.js in a file named example.txt and displays in console.
JavaScript
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Concurrency Model in JavaScript
JavaScript uses an event-driven, non-blocking concurrency model to manage multiple tasks concurrently without blocking the main thread.
How JavaScript is Single-Threaded?
JavaScript is single-threaded, meaning it can only execute one piece of code at a time in a single sequence. This single-threaded nature simplifies code execution but poses challenges when dealing with asynchronous tasks like network requests or file handling.
- Call Stack: JavaScript uses a call stack to keep track of function calls. If a function is currently being executed, it blocks the execution of other functions until it is complete.
- Event Loop: To manage asynchronous operations, JavaScript uses the event loop. It ensures that even though JavaScript can only handle one task at a time, it doesn't get stuck waiting for long-running tasks like HTTP requests.
Example: Despite the setTimeout being called first, the message is logged last because setTimeout is non-blocking. The call stack clears console.log("Start") and console.log("End") first, then moves to the delayed task.
JavaScript
console.log("Start");
setTimeout(() => {
console.log("Delayed Message");
}, 2000);
console.log("End");
Output:
Start
End
Delayed Message
Promises, Async/Await, and Handling Concurrency in JavaScript
Promises and async/await are used to handle asynchronous tasks more effectively, avoiding "callback hell" and making the code more readable.
Promises: Promises represent a value that may be available now, or in the future, or never. They have three states: pending, fulfilled, and rejected.
Example: This example demonstrates the Promises in javascript.
JavaScript
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise Resolved!");
}, 1000);
});
promise.then((message) => {
console.log(message);
});
Output:
Promise Resolved!
Async/Await: async functions allow you to write asynchronous code that looks synchronous. The await keyword pauses the execution until the promise resolves.
Example: This example demonstrates the usuage of Async/await function.
JavaScript
async function fetchData() {
let data = await fetch("https://api.example.com/data");
console.log("Data fetched:", data);
}
fetchData();
Event-Driven Architecture in JavaScript
JavaScript is inherently event-driven, meaning actions are taken in response to events such as user interactions, timers, or network responses.
JavaScript's Event-Driven Nature in Web Development
- Events: Events are actions or occurrences that happen in the system you are programming, such as a user clicking a button or a webpage loading.
- Event Listeners: Functions that are executed in response to certain events.
Example: When the button with the ID myButton is clicked, the event listener executes the function, logging “Button clicked!”.
JavaScript
document.getElementById("myButton").addEventListener("click", function() {
console.log("Button clicked!");
});
Event Delegation and Handling User Interactions
Event delegation is a technique to handle events efficiently by using a single event listener to manage all events of a particular type.
Example: Instead of attaching an event listener to each li element, we attach it to the parent and use event delegation to identify which li was clicked.
JavaScript
document.getElementById("parent").addEventListener("click", function (event) {
if (event.target && event.target.matches("li.item")) {
console.log("List item clicked!");
}
});
JavaScript’s Prototypal Inheritance
Prototypal inheritance allows objects to inherit properties and methods from other objects, using prototypes.
JavaScript’s Prototypal InheritanceHow Objects Inherit Properties and Methods in JavaScript
Prototype Chain: Each object in JavaScript has a prototype object, which acts as a template from which it inherits properties and methods.
Example: This JavaScript code defines a constructor function Person to create person objects with name and age properties, and adds a greet method to the Person prototype to print a greeting message.
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function () {
console.log("Hello, my name is " + this.name);
};
let john = new Person("John", 30);
john.greet();
OutputHello, my name is John
Role of Prototypes in JavaScript
- Inheritance: Prototypes enable inheritance in JavaScript. An object can use another object's methods and properties through its prototype chain.
- Shared Methods: Methods defined on the prototype are shared across all instances, saving memory.
JIT Compilation (Just-in-Time Compilation) in JavaScript
JIT compilation is an optimization technique used by modern JavaScript engines to improve performance by compiling code at runtime.
- Parsing and Compilation: Initially, JavaScript code is parsed and compiled to an intermediate bytecode, which is executed by the engine.
- Dynamic Optimization: The JIT compiler optimizes frequently executed code paths, compiling them to machine code to speed up execution.
Example: The add function, called repeatedly in a loop, may be optimized by the JIT compiler to reduce execution time.
function add(a, b) {
return a + b;
}
for (let i = 0; i < 1000000; i++) {
add(10, 20);
}
Modules and Scope in JavaScript
Modules and scopes in JavaScript help in organizing code, preventing conflicts, and improving maintainability.
Understanding JavaScript Modules (ES6 Modules, CommonJS)
ES6 Modules: Introduced in ES6, they use import and export statements to include or share code between files.
Example:
// In utils.js
export function add(a, b) {
return a + b;
}
// In main.js
import { add } from './utils.js';
console.log(add(10, 20)); // Output: 30
CommonJS: CommonJS modules use require and module.exports for importing and exporting code (commonly used in Node.js).
Example:
// In utils.js
module.exports = {
add: function (a, b) {
return a + b;
}
};
// In main.js
const utils = require('./utils.js');
console.log(utils.add(10, 20)); //Output:30
Global, Function, and Block-Level Scopes
Global Scope: Variables declared outside of functions or blocks are in the global scope, accessible from anywhere in the code.
var globalVar = "I am global";
function showGlobal() {
console.log(globalVar);
}
showGlobal(); //Output: I am Global
Function Scope: Variables declared within a function are only accessible within that function.
function showLocal() {
var localVar = "I am local";
console.log(localVar);
}
showLocal(); // Output: I am local
console.log(localVar); // Error: localVar is not defined
Block Scope: Introduced in ES6, let and const are block-scoped, meaning they are only accessible within the block they are declared in.
if (true) {
let blockVar = "I am block scoped";
console.log(blockVar); // Output: I am block scoped
}
console.log(blockVar); // Error: blockVar is not defined
Conclusion
Understanding these advanced concepts such as concurrency, event-driven architecture, prototypal inheritance, and scopes, helps us to write more efficient and scalable JavaScript code. It allows us to handle asynchronous operations smoothly, utilize inheritance effectively, and organize code through modules and scopes, enhancing both frontend and backend development.
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
Introduction to Object Oriented Programming in JavaScriptAs JavaScript is widely used in Web Development, in this article we will explore some of the Object Oriented mechanisms supported by JavaScript to get the most out of it. Some of the common interview questions in JavaScript on OOPS include: How is Object-Oriented Programming implemented in JavaScrip
7 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