Javascript

What are the features of JavaScript? What are the advantages of JavaScript over other web technologies?

  1. Dynamic Typing: JavaScript allows variables to change their type at runtime, offering flexibility but requiring careful management to avoid runtime errors.

  2. Interpreter-Based: It runs in the browser, interpreting code line by line, reducing development complexity without sacrificing performance.

  3. Validation of User’s Input: JavaScript can validate user input before submission, enhancing security and user experience.

  4. In-built Functions: Offers a wide range of built-in functions for common tasks, simplifying development.

  5. Case Sensitive: Differentiates between uppercase and lowercase letters, affecting variable names and function calls.

  6. Lightweight and Delicate: Efficiently handles operations without needing to declare variables, focusing on objects for operations.

  7. Async Processing: Enables asynchronous operations through callbacks and promises, improving performance for IO-bound tasks.\

  8. Saves Time and Bandwidth: Executes on the client side, reducing load times and bandwidth consumption.

  9. Easily Sends HTTP Requests: Utilizes XMLHttpRequest for asynchronous communication with servers without page reloads.

  10. Browser Compatibility: Works across all modern browsers, ensuring consistent behavior and user experience

  11. Community Support: Backed by global companies like Google (Angular) and Facebook (React.js), fostering a rich ecosystem of libraries and frameworks.

  12. Open Source: Benefits from a wealth of open-source projects and extensive documentation, aiding rapid development and problem-solving.

  13. Backend Usage: Through Node.js, enables full-stack JavaScript development, streamlining development processes.

  14. Performance: Fast execution due to client-side processing and just-in-time compilation by browsers.

  15. Reduced Server Load: Being client-side, minimizes server demands, potentially eliminating the need for a server for simple applications.

  16. Rich Interfaces: Enhances user experience with interactive features like drag-and-drop and sliders.

  17. Extended Functionality: Allows extending web page functionalities with third-party add-ons.

  18. Versatility: Capable of full-stack development with Node.js, enabling the creation of comprehensive JavaScript applications.

  19. More Features:

    • Lightweight

    • Cross-platform compatible

    • Object-oriented

Explain Hoisting in JavaScript?

Hoisting is JavaScript's automatic behavior of moving all variable and function declarations to the top of their scope during the compilation phase, making them accessible throughout that scope before any code execution takes place

Why Hosting?

Understanding hoisting is essential for avoiding unexpected behavior in JavaScript programs. It encourages developers to declare variables and functions at the beginning of their scope to prevent confusion and potential bugs.

  • Scope: This movement applies to both global and local scopes, meaning that regardless of where a variable or function is declared within a scope, it becomes available at the top of that scope.

  • Declaration vs. Initialization: It's crucial to distinguish between hoisting declarations and initializations. While declarations are hoisted, initializations are not. This means that if a variable is declared and initialized after it's used, accessing it before its declaration will result in undefined for variables declared with var. For let and const, attempting to access them before declaration will throw an error because they are block-scoped and not initialized until their declaration.

Consider the following example:

console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5

Here’s what actually happens due to hoisting:

  1. The variable declaration (var x) is hoisted to the top of its scope.

  2. The variable assignment (x = 5) stays in place.

So, the code is interpreted as:

var x;
console.log(x); // Output: undefined
x = 5;
console.log(x); // Output: 5

In contrast, let and const variables are hoisted but not initialized, leading to a "temporal dead zone" until the line where they are defined:

console.log(y); 
// ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // Output: 10
  • Behavior with var: When using var, the declaration is hoisted, but the initialization is not. This means that if you try to use a variable declared with var before it's initialized, it will return undefined.

  • Behavior with let and const: Unlike var, let and const are block-scoped, and their declarations are hoisted to the top of their block. However, they are not initialized until their declaration statement is executed. Attempting to access them before their declaration will result in a Reference Error.

  • Function Declarations: Both named and anonymous function declarations are hoisted, allowing them to be called before their declaration in the code. However, function expressions (including those involving arrow functions) are not hoisted unless they are declared as named functions.

  • Strict Mode: In strict mode, undeclared variables are treated as undefined instead of being automatically declared as global variables, further emphasizing the importance of proper declaration practices.

What are the scopes of a variable in JavaScript?

In JavaScript, the scope of a variable determines its visibility and accessibility within different parts of the code. There are three primary scopes for variables:

  • Global Scope: Variables declared outside any function have a global scope. They can be accessed from anywhere in the JavaScript program. Examples include variables declared with var, let, or const outside of any function or block.

  • Function Scope: Each function in JavaScript creates a new scope. Variables declared within a function using var, let, or const are local to that function and are not accessible from outside the function. This means they can only be accessed within the function they were declared in.

  • Block Scope: Introduced with ES6, let and const declarations have block scope. This means they are only accessible within the block they are declared in, including blocks within loops and conditionals. Variables declared with var do not have block scope; they are function-scoped or globally scoped depending on where they are declared.

// Global scope
var globalVar = "I'm global!";
console.log(globalVar); // Accessible from anywhere

function exampleFunction() {
  // Function scope
  var localVar = "I'm local!";
  console.log(localVar); // Accessible within the function
  
  if (true) {
    // Block scope
    let blockScopedVar = "I'm block scoped!";
    console.log(blockScopedVar); // Accessible within the if block
    console.log(localVar); // Accessible within the if block cause function scope
  }
  console.log(blockScopedVar); // Error: blockScopedVar is not defined
  
}

exampleFunction(); // Call the function to see the output
console.log(globalVar); // Still accessible outside the function
console.log(localVar); // Error: localVar is not defined
console.log(blockScopedVar); // Error: blockScopedVar is not defined

Difference between var and let keyword in JavaScript.

The var and let keywords in JavaScript are used to declare variables, but they differ significantly in terms of scope, hoisting behavior, and redeclaration rules:

  • Usage in Loops:

    • var: When used in a loop, the variable retains its value after the loop completes, which can lead to unexpected behavior if not managed carefully.

    • let: When used in a loop, the variable is confined to the loop's block, and its value resets with each iteration, aligning with typical expectations for loop counters.

var
let

Syntax -:

var name = value.

Syntax -:

let name = value.

The variables that are defined with var statement have function scope.

The variables that are defined with let statement have block scope.

We can declare a variable again even if it has been defined previously in the same scope.

We cannot declare a variable more than once if we defined that previously in the same scope.

Hoisting is allowed with var.

let is hoisted but inaccessible due to temporal dead zone

Example -:

var websitename = “geeksforgeeks”;

Example -:

let x = 69;

var is an ECMAScript1 feature.

let is a feature of ES6.

In summary, let offers more precise control over variable scope and lifecycle, making it the preferred choice for modern JavaScript development. Its block scoping and strict handling of hoisting and redeclaration help prevent common pitfalls associated with var.

Explain Implicit Type Coercion in JavaScript?

When the value of one data type is automatically converted into another data type, it is called Implicit type coercion in JavaScript.

var a = 4;
var b = "2";

console.log(a+b); // converted to string = 42
console.log(a-b); // converted to number = 2

Difference between “== “ and “ === “ operators ?

Both are comparison operators. The difference between both the operators is that “==” is used to compare values whereas, “ === “ is used to compare both values and types.

let a = 0;
let b = false;
console.log((a == b));  // true
console.log((a === b)); // false

What is the difference between Session storage and Local storage?

Session storage

Local storage

The data stored in session storage gets expired or deleted when a page session ends.

Websites store some data in local machine to reduce loading time; this data does not get deleted at the end of a browsing session.

What is the difference between Undefined and Null in JavaScript?

Undefined means a variable has been declared but a value has not yet been assigned to that variable.

Null is an assignment value that we can assign to any variable that is meant to contain no value.

Output of Following Codes

(function(){
  setTimeout(()=> console.log(1),2000);
  console.log(2);
  setTimeout(()=> console.log(3),0);
  console.log(4);
})();

Output:
2 
4
3
1

What is a self-invoked function? How does a self-invoked function work?

A self-invoked function, also known as an Immediately Invoked Function Expression (IIFE), is a function that is executed immediately after it is defined. This technique is commonly used in JavaScript to create a new scope and to avoid polluting the global namespace.

Structure of an Immediately Invoked Function Expression (IIFE)

An IIFE is typically structured as follows:

(function() {
    console.log("This is a self-invoked function!");
})();

Why Use an IIFE?

  1. Avoid Global Variables: Variables defined within an IIFE are not accessible outside its scope, which helps in preventing global namespace pollution.

    code(function() {
        var secret = "I'm a secret!";
        console.log(secret); // This will log "I'm a secret!"
    })();
    
    console.log(secret); // This will throw a ReferenceError: secret is not defined
  2. Module Pattern: IIFEs are often used in the module pattern to create private and public members.

    var counterModule = (function() {
        var count = 0; // private variable
        
        return {
            increment: function() {
                count++;
                console.log(count);
            },
            reset: function() {
                count = 0;
                console.log(count);
            }
        };
    })();
    
    counterModule.increment(); // logs 1
    counterModule.increment(); // logs 2
    counterModule.reset(); // logs 0

    In this example, count is a private variable that can only be accessed and modified by the methods increment and reset.

  3. Immediate Initialization: IIFEs can be used to initialize variables or set up configurations right away.

    var appConfig = (function() {
        var config = {
            apiKey: '1234567890',
            apiUrl: 'https://api.example.com'
        };
        return config;
    })();
    
    console.log(appConfig.apiKey); /

What happens if you initialize a variable in a block but do not declare it anywhere in the code?

If you initialize a variable in a block without declaring it anywhere in the code (i.e., without using var, let, or const), it will be treated as an implicit global variable in JavaScript. This happens because the JavaScript interpreter will automatically create a global variable with the given name.

Here is an example to illustrate this behavior:

function example() {
    // No declaration with var, let, or const
    implicitGlobal = "I'm an implicit global variable!";
}

example();

console.log(implicitGlobal); // This will log: "I'm an implicit global variable!"

Why This Happens

  • Global Scope: If a variable is assigned a value without being declared using var, let, or const, it will be added to the global object (window in browsers, global in Node.js). This makes it accessible from anywhere in the code.

Let's assume a function receives 3 parameters but you call it using 2 parameters. a. What will happen? b. What will be the value of the 3rd parameter?

a. What will happen?

The function will execute without any error. JavaScript does not enforce a strict number of parameters, so it allows you to call a function with fewer or more arguments than it is defined to take.

b. What will be the value of the 3rd parameter?

The third parameter will be undefined. When a function is called with fewer arguments than the number of parameters defined, the parameters for which no corresponding arguments are provided will be set to undefined.

Example

Here is an example to illustrate this behavior:

function exampleFunction(a, b, c) {
    console.log(a); // logs the value of the first argument
    console.log(b); // logs the value of the second argument
    console.log(c); // logs the value of the third argument, which will be undefined
}

exampleFunction(1, 2); // Only two arguments are provided

Output:

1
2
undefined

In this example:

  • a is assigned the value 1.

  • b is assigned the value 2.

  • c is not provided, so it is assigned undefined.

Handling Undefined Parameters

If you want to provide default values for parameters that might be undefined, you can use default parameter syntax:

function exampleFunction(a, b, c = 3) {
    console.log(a); // logs the value of the first argument
    console.log(b); // logs the value of the second argument
    console.log(c); // logs the value of the third argument, which will be 3 if not provided
}

exampleFunction(1, 2); // Only two arguments are provided

Output:

1
2
3

In this modified example, c will default to 3 if it is not provided.

Differences between declaring variables using var, let and cons?

When declaring variables in JavaScript, you have three options: var, let, and const. Each has its own characteristics and scope rules. Here's a detailed explanation of the differences:

1. var

  • Scope: var is function-scoped, meaning it is accessible within the function it is declared in. If declared outside any function, it becomes globally scoped.

  • Hoisting: Variables declared with var are hoisted to the top of their scope. This means the declaration is processed before any code is executed, but the initialization is not. As a result, you can reference a var variable before its declaration without getting a ReferenceError, although its value will be undefined until the line where it's initialized is executed.

  • Re-declaration: You can re-declare a variable using var within the same scope without any errors.

  • Example:

    function example() {
        console.log(x); // undefined due to hoisting
        var x = 5;
        console.log(x); // 5
    }
    example();
    
    var y = 10;
    var y = 20; // No error
    console.log(y); // 20

2. let

  • Scope: let is block-scoped, meaning it is only accessible within the block (enclosed by {}) it is declared in. This includes for-loops, if statements, etc.

  • Hoisting: Variables declared with let are hoisted to the top of their block, but they are not initialized. This means referencing a let variable before its declaration results in a ReferenceError.

  • Re-declaration: You cannot re-declare a variable using let within the same scope.

  • Example:

    function example() {
        console.log(x); // ReferenceError: Cannot access 'x' before initialization
        let x = 5;
        console.log(x); // 5
    }
    example();
    
    let y = 10;
    let y = 20; // SyntaxError: Identifier 'y' has already been declared

3. const

  • Scope: const is also block-scoped, similar to let.

  • Hoisting: Variables declared with const are hoisted to the top of their block but are not initialized. Like let, referencing a const variable before its declaration results in a ReferenceError.

  • Re-declaration and Assignment: You cannot re-declare or reassign a variable declared with const. This makes const useful for defining constants that should not change.

  • Mutable Objects: Note that while you cannot reassign a const variable, if it holds an object or array, the properties or elements of that object/array can be changed.

  • Example:

    function example() {
        console.log(x); // ReferenceError: Cannot access 'x' before initialization
        const x = 5;
        console.log(x); // 5
    }
    example();
    
    const y = 10;
    y = 20; // TypeError: Assignment to constant variable.
    
    const obj = { key: 'value' };
    obj.key = 'newValue'; // Allowed
    console.log(obj.key); // 'newValue'

Summary

  • Scope: var is function-scoped; let and const are block-scoped.

  • Hoisting: All are hoisted, but let and const are not initialized until their declaration is encountered.

  • Re-declaration: var allows re-declaration; let and const do not.

  • Assignment: const does not allow reassignment; var and let do.

Is JavaScript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. In a dynamically typed language, variable types are determined at runtime, allowing a variable to hold values of any type without explicit type declarations. This flexibility can make coding more convenient but may also lead to runtime errors if types are not handled appropriately.

JavaScript, being dynamically typed, allows variables to change types during execution and accommodates a wide range of data types without explicit type annotations

What is Callback Hell?

Callback hell (or "pyramid of doom") is a situation in which multiple nested callbacks make the code difficult to read and maintain. This often occurs when dealing with asynchronous operations, such as making multiple API calls or handling multiple events.

Here's an example of callback hell:

getUser(function(user) {
    getProfile(user.id, function(profile) {
        getPosts(user.id, function(posts) {
            displayUserProfile(user, profile, posts, function() {
            });
        });    
    });
});

More nested callbacks... In this example, we have nested callbacks for getting a user, fetching their profile, retrieving their posts, and finally displaying the user profile. As more asynchronous operations are added, the code becomes more difficult to read and maintain.

To address callback hell, developers often use techniques like Promises or async/await in modern JavaScript to make code more readable and manageable


Writing clear and bug-free JavaScript

Examples of Poor Practice:

// Non-descriptive variable names
let x = 100;
let y = 200;

// Using reserved words and unclear naming
let function = "functionName"; // Syntax error: reserved word
let temp = "John"; // What is 'temp' referring to?

// Inconsistent naming conventions
function CalculateTotalPrice(Items) { // Inconsistent function naming
    let Total_price = 0; // Inconsistent variable naming
    Items.forEach(Item => {
        Total_price += Item.Price;
    });
    return Total_price;
}

Examples of Good Practice:

// Descriptive variable names using camelCase
let userFirstName = "John";
let userLastName = "Doe";
const MAX_LOGIN_ATTEMPTS = 3;

// Avoiding reserved words and using meaningful names
let isLoggedIn = false;
let userRole = "admin";

// Consistent naming for functions and variables
function calculateTotalPrice(items) {
    let totalPrice = 0;
    items.forEach(item => {
        totalPrice += item.price;
    });
    return totalPrice;
}

What is the difference between Function declaration and Function expression?

Function Declaration
Function Expression

1

Function declarations are hoisted to the top of their containing scope. This means you can call the function before its definition in the code.

Function expressions are not hoisted. This means you cannot call the function before it is defined in the code.

2

Uses the function keyword followed by a name and parameter list.

Often assigned to a variable, can be anonymous or named, and defined using the function keyword.

3

Typically used for defining main functions that need to be available throughout the code.

Often used for inline functions, such as callbacks or immediately invoked function expressions (IIFEs).

Syntax: Function Declaration

console.log(add(2, 3)); // Output: 5

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

Syntax: Function Expression

// This will cause an error because the function is not hoisted
console.log(multiply(2, 3));
// Uncaught ReferenceError: Cannot access 'multiply' before initialization

const multiply = function(a, b) {
    return a + b;
};

console.log(multiply(2, 3)); // Output: 5

What is the distinction between client-side and server-side JavaScript?

Client - Side JavaScript
Server - Side JavaScript

1

Client-side JavaScript runs in the user's web browser, interacting with the web page's content and the browser itself.

Server-side JavaScript runs on the web server, handling backend logic, database interactions, and serving web pages to clients

2

Runs in the browser (e.g., Chrome, Firefox, Safari).

Runs on the server (e.g., Node.js).

3

Popular libraries and frameworks include jQuery, React, Angular, and Vue.js.

Popular frameworks include Express.js, Koa.js, and Hapi.js.

4

Common Uses:

  • Manipulating the Document Object Model (DOM) to update the content, structure, and style of web pages dynamically.

  • Handling user events such as clicks, form submissions, and mouse movements.

  • Validating user input before it is sent to the server.

  • Making asynchronous requests to the server using AJAX (Asynchronous JavaScript and XML) or Fetch API to update parts of the web page without reloading.

Common Uses:

  • Handling HTTP requests and responses.

  • Interacting with databases, file systems, and other server resources.

  • Implementing business logic, authentication, and authorization.

  • Serving dynamic content and APIs to client-side applications.

Example: Client-Side JavaScript

// Client-Side JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>Client-Side JavaScript Example</title>
    <script>
        function showAlert() {
            alert("Button clicked!");
        }
    </script>
</head>
<body>
    <button onclick="showAlert()">Click Me</button>
</body>
</html>

Example: Server-Side JavaScript

// Server-Side JavaScript using Node.js and Express.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello from the server!');
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Explain the key features introduced in JavaScript ES6

ECMAScript 6 (ES6), also known as ECMAScript 2015, introduced a number of key features that significantly enhanced JavaScript's functionality and usability. Here are the major features:

1. let and const

  • let: Declares block-scoped variables.

  • const: Declares block-scoped constants that cannot be reassigned.

let variable = 'value';
const constant = 'constant value';

2. Arrow Functions

  • Provide a shorter syntax for writing function expressions and lexically bind this value.

const add = (a, b) => a + b;

3. Template Literals

  • Allow embedded expressions and multi-line strings using backticks (`) instead of single or double quotes.

const name = 'World';
const greeting = `Hello, ${name}!`;

4. Default Parameters

  • Allow function parameters to have default values.

function greet(name = 'Guest') {
    return `Hello, ${name}!`;
}

5. Destructuring Assignment

  • Allows unpacking values from arrays or properties from objects into distinct variables.

// Array Destructuring
const [a, b] = [1, 2];

// Object Destructuring
const {name, age} = {name: 'Alice', age: 25};

6. Enhanced Object Literals

  • Simplify object property definitions.

const name = 'Alice';
const age = 25;
const person = {
    name,
    age,
    greet() {
        console.log('Hello!');
    }
};

7. Modules

  • Allow code to be split into modules that can be imported and exported.

// module.js
export const name = 'Alice';
export function greet() {
    console.log('Hello!');
}

// main.js
import {name, greet} from './module.js';

8 Promises

  • Provide a way to handle asynchronous operations.

const fetchData = new Promise((resolve, reject) => {
    // Simulate an async operation
    setTimeout(() => resolve('Data fetched'), 1000);
});

fetchData.then(data => console.log(data));

9. Rest and Spread Operators

  • Rest operator (...) allows for variable numbers of arguments.

  • Spread operator (...) allows an iterable to be expanded in places where zero or more arguments are expected.

// Rest Parameter
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

// Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];

10. Iterators and for...of Loop

  • Provide a way to iterate over iterable objects (like arrays, strings, etc.).

const array = [1, 2, 3, 4];
for (const value of array) {
    console.log(value);
}

What do you understand about cookies?

Cookies are small pieces of data stored on the user's computer by the web browser while browsing a website. They are used for various purposes, including session management, personalization, and tracking user behavior. Here's a detailed understanding of cookies:

Key Characteristics of Cookies

  1. Storage:

    • Cookies are stored in the user's web browser and can persist between sessions.

  2. Expiration:

    • Cookies can have an expiration date set by the server. If no expiration date is set, the cookie is a session cookie and will be deleted when the browser is closed.

    • Persistent cookies remain until the specified expiration date or until manually deleted by the user.

Types of Cookies

  1. Session Cookies:

    • Temporary cookies that are deleted when the browser is closed.

    • Used for session management, like keeping users logged in as they navigate through a site.

  2. Persistent Cookies:

    • Remain on the user's device until they expire or are deleted.

    • Used for storing preferences, authentication tokens, and other information that should persist between sessions.

  3. Third-Party Cookies:

    • Set by domains other than the one the user is currently visiting.

    • Commonly used for tracking and advertising purposes.

Last updated