Every contribution counts, regardless of its size. I value and appreciate the efforts of all contributors, from beginners to seasoned developers. Join me on this exciting journey of open-source collaboration. Together, let's build something amazing! π€
- π Please ensure that your contributions adhere to the coding style and guidelines of this project
- π Include clear and concise commit messages for all your commits
- π Provide a detailed description of your changes in the pull request.
- π Be respectful and considerate towards other contributors.
- JavaScript is a scripting language used to create dynamic and interactive websites. It is supported by all major web browsers.
- JavaScript is basically a client-side scripting language but it can also be used on the server-side with the help of technologies such as Node.js.
Primitive | Non-primitive |
---|---|
Boolean, NULL, undefined, BigInt, String, Number, Symbol | Object, Array |
a) Object Literals: A comma-separated set of name and value pairs that is wrapped inside curly braces.
var person = {
name: 'Surbhi',
age: 25,
occupation: 'Software Engineer'
}
b) Object.create method: It Creates a new object, by using an existing object as the prototype of the newly created object.
const person = {
name: 'Surbhi',
age: 25,
occupation: 'Software Engineer'
}
var info = Object.create(person);
console.log(info.name); // output - Surbhi
const person = new Person();
class Person {
constructor(name) {
this.name = name;
}
}
let person = new Person('Surbhi');
console.log(person.name); //output - Surbhi
- == : While comparing two operands, checks for only value
console.log(1=="1"); // output=>>>>>>>>> true
- === : While comparing two operands, checks for value as well as data type
console.log(1==="1"); // output=>>>>>>>>> false
- JavaScript is Single-threaded
Arrow functions were introduced in ES6 (ECMAScript 2015) and provide a simpler and compact way to write functions. They are also called βfat arrow functionsβ
const functionName = (something) => {
return something;
}
- They use a concise syntax which makes them shorter and easier to read as compared to traditional function expressions
- They do not bind their own this value, but instead inherit the this value from the enclosing lexical scope
- They do not have "prototype" property and hence cannot be used as a constructor
- If the arrow function body consists of a single expression, that expression will be implicitly returned, without the need for a return statement.
- If an arrow function has only one parameter, the parentheses around the parameter list can be omitted.
Synthetic events are objects that act as a cross-browser wrapper around a browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.
Array destructuring is a unique feature in JavaScript that allows you to extract array's value into new variables. For e.g.,
const arr = [1,2,3];
const [num1, num2, num3] = arr;
console.log(num1); // output =====> 1
console.log(num2); // output =====> 2
- Yes, using Spread Operators
const arr1 = [1,2,3,4];
const arr2 = [5,6];
const arr3 = [...arr1, ...arr2]
console.log(arr3) // output =====> [1,2,3,4,5,6]
JavaScript is a dynamically typed language, because the type of a variable is determined at runtime based on the value it holds. For e.g.,
var variable_one = "surbhi" // "string" datatype is determined at runtime
var variable_two = 20 // "number" datatype is determined at runtime
Undeclared - A variable that has not been declared or doesn't exists in the code
console.log(a); // output =====> ReferenceError: a is not defined
Undefined - A variable that has been declared but not assigned a value yet
let a;
console.log(a); // output =====> undefined
Null - Null means an empty value or a blank value. It is used to represent an intentional absence of value.
let demo = null;
console.log(demo); // output =====> null
Undefined - Undefined means the variable has been declared, but its value has not been assigned yet.
let demo;
console.log(demo); // output =====> undefined
A "let" or "const" variable is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.
In JavaScript, variables declared with let or const are hoisted to the top of the block scope, but they enter a "Temporal Dead Zone" (TDZ).
{
// TDZ for name variable starts here
console.log(name); // ReferenceError
let name = "surbhi"; // End of TDZ for name
}
IIFE stands for Immediately Invoked Function Expression. It is a JavaScript function that is executed as soon as it is defined.
An IIFE is typically written as an anonymous function expression that is enclosed within a set of parentheses, followed by another set of parentheses that call the function. For e.g.,
(function() {
// code goes here
})();
Hoisting is a default behavior in JavaScript where variable and function declarations are moved to the top of the current scope
Variable hoisting
console.log(a); // output =====> undefined
var a = 10;
a=10;
console.log(a); // output =====> 10
var a;
Function hoisting
demo(); // demo console
function demo() {
console.log('demo console');
}
**Note**
+ Only function declarations are hoisted, not the function expressions.
+ Only the declaration is hoisted, not the initialization.
In javascript, a cookie is a piece of data, stored in small text files, on the user's computer by the browser. Cookies are set, read and deleted using the document.cookie property
//**Set a cookie**
document.cookie = "username=surbhi";
//**Read a cookie**
let cookie_variable = document.cookie;
//**Delete a cookie** (set the expiration date to a past date/time)
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Memoization is a technique used in JavaScript to optimize the performance of functions by caching the results of expensive function calls, based on their input parameters. For e.g., If a function is called multiple times with the same input parameters, then it will perform the same calculations each time. By memoizing the function, we can use the cached result.
function memoizedAdd(num1, num2) {
let cache = {};
return function (a, b) {
const key = num1 + ' and ' + num2;
if (key in cache) {
console.log('Retrieving from cache:', key);
return cache[key];
} else {
console.log('Calculating result:', key);
const result = num1 + num2;
cache[key] = result;
return result;
}
};
}
const add = memoizedAdd();
console.log(add(2, 3)); // "Calculating result:", "2 and 3", output ========> 5
console.log(add(2, 3)); // "Retrieving from cache:", "2 and 3" output ========> 5
In javascript, there are 3 ways to declare a variable - var, let, and const. However, they have some differences in their behavior and scope.
var | let | const |
---|---|---|
Function scoped | Block scoped | Block scoped |
Can be re-declared in the same scope | Can not be re-declared in the same scope | Can not be re-declared in the same scope |
Can be updated in the same scope | Can be updated in the same scope | Can not be updated in the same scope |
Hoisted to the top of their scope | Hoisted to the top but are not initialized | Hoisted to the top but are not initialized |
Can be declared without being initialized | Can be declared without being initialized | Can not be declared without being initialized |
A callback function is a function that is passed as an argument to another function. The function that receives the callback as an argument can then invoke the callback at any time during its execution.
function message(callback) {
console.log('Hi, i am message function');
callback();
}
// callback function
function callBackFun() {
console.log('Hey, I am a callback function');
}
// passing callback function as an argument to message function
message(callBackFun);
Yes, we can have both with the same name. But when we do this, the local variable will take precedence over the global variable within the scope of the function or block of code in which it is declared.
However, outside of that scope, the global variable will still be accessible using its name.
let a = 10;
function Demo(){
let a = 20;
console.log(a, "local scope");
}
Demo();
console.log(a, "global scope");
Local storage and session storage are web storage provided by web browsers to store data on the client-side
Local Storage - Data stored in local storage will persist even after the browser window is closed or the user navigates away from the website and it is available across all windows and tabs of the same origin.
Session Storage - Data stored in session storage will be deleted when the browser window is closed or the session ends and it is available only within the same window or tab that created the data.
map() and forEach() are array methods that can be used to iterate over an array. map()
- map() method receives a function as an argument, executes it once for each array element and returns a new array
- It is generally used when we need to modify/change data, because it returns a new array with the transformed data
- It is chainable because we can attach sort(), filter() etc. after performing a map() method on an array
const arr = [1,2,3,4,5]
let result = arr.map(x => x * x)
console.log(result) // output ========> [1,4,9,16,25]
forEach()
- forEach() method receives a function as an argument, executes it once for each array element but returns undefined.
- It is generally used when we just need to iterate over an array
- It is not chainable
const arr = [1,2,3,4,5]
let result = arr.forEach(x => x * x)
console.log(result) // output ========> undefined
- The rest operator was introduced in ES6 (ECMAScript 2015) and it is represented by three dots (...)
- It is used in function parameters and allows you to represent an indefinite number of arguments as an array
function addition(...numbers) {
return numbers.reduce((a,b)=>a+b);
}
console.log(addition(1, 2, 3, 4)); // output ========> 10
- It collects all the remaining arguments passed to a function into an array
function profile(name, designation,...location) {
return location
}
console.log(profile("surbhi","SE","India","Indore","M.P")); // output ========> ["India", "Indore", "M.P"]
- The spread operator was introduced in ES6 (ECMAScript 2015) and it is represented by three dots (...)
- It allows an iterable to be spread into individual elements
const arr = [1, 2, 3, 4,5];
console.log(...arr); // output ======> 1, 2, 3, 4, 5
- It can be used to copy the elements of an existing array into a new array, or to concatenate arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // output =======> [1, 2, 3, 4, 5, 6]
- It can be used to copy the properties of an existing object into a new object
const obj1 = { a:1, b:2 };
const obj2 = { c:3 };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3); // output ========> { a: 1, b: 2, c: 3 }
async and defer are the attributes used with the script tag in HTML to load javaScript files.
Async - The script is loaded in parallel to the HTML parsing, and executed as soon as it is available i.e., it executes the script immediately after it is loaded. It can be useful for scripts that don't depend on the DOM.
Defer - The script is loaded in parallel to the HTML parsing, and executed after the page is completely loaded i.e., it waits until the page has finished parsing. It can be useful for scripts that depend on the DOM.
- The nullish coalescing (??) operator is a logical operator
- It allows you to check if a value is either null or undefined
- It returns its right-hand side operand if its left-hand side operand is null or undefined, otherwise returns its left-hand side operand
console.log((null || undefined) ?? "foo"); // output ========> "foo"
console.log("hello" ?? "foo"); // output ========> "hello"
Parameter - A parameter is a variable that is defined during a function declaration or definition. It represents a value that the function or method expects to receive as an input.
Argument - An argument is the actual value that is passed to a function or method when it is called.
function Demo(parameter1, parameter2){
something------
something------
}
Demo(argument1, argument2);
A closure is a combination of a function and the environment in which it was created(lexical scope). It gives you access to an outer function's scope from an inner function even if the outer function has returned
function Demo() {
let name = "Surbhi";
function displayName() {
console.log(name);
}
return displayName;
}
const result = Demo();
result();
Function Declaration
- A function declaration defines a function using the function keyword, followed by the function name
- We can call a function, declared using a function declaration, before it is defined. Because it is hoisted to the top of its scope
- It does not require a variable assignment
function Message() {
console.log("Welcome Message"); // output ========> Welcome Message
}
Message();
Function Expression
- A function Expression is similar to a function declaration without the function name
- We can not call a function, declared using a function expression, before it is defined
- It can be stored in a variable assignment
const Message = function() {
console.log("Welcome Message"); // output ========> Welcome Message
}
Message();
- Using the array literal notation
const arr = [1,2,3,4,5];
- Using the Array() constructor
const arr = new Array(1, 2, 3, 4, 5);
window object - window is the topmost object. It represents the browser window or tab containing a DOM document. It provides various properties and methods to manipulate the browser window, such as window.alert(), window.confirm(), and window.location.
document object - document represents the HTML document that is being displayed in the window. It provides properties and methods to manipulate the HTML elements in the document, such as document.title, document.getElementById(), and document.createElement().
- Strict mode was introduced in ECMAScript 5
- It performs additional checks on your code to prevent certain types of bugs and errors that may go unnoticed e.g., using undeclared variables, using duplicate property names in objects
- It can be enabled at either the global level or at the function level
- It can't be apply to block statements enclosed in {} braces
- To invoke strict mode, put the exact statement βuse strictβ; or βuse strictβ;
Using length property
let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); // output ========> []
Assigning it to a new empty array
let arr = [1,2,3,4,5];
arr = [];
console.log(arr); // output ========> []
Using the splice() method
let arr = [1, 2, 3, 4, 5];
arr.splice(0, arr.length);
console.log(arr); // output ========> []
- In Javascript, NaN stands for "Not a Number"
- It is a global property that represents an unrepresentable mathematical result
- It is returned when a mathematical operation has no meaningful result. E.g., dividing zero by zero, multiplying/dividing a non-numeric value by a number etc.
console.log(0/0); // output ========> NaN
console.log("a"*1); // output ========> NaN
console.log("a"/1) // output ========> NaN
console.log(Math.sqrt(-1)); // output ========> NaN
console.log(parseInt("blabla")); // output ========> NaN
- Use camelCase (lowercase for the first word, then uppercase for subsequent words) for variable and function names
- Use PascalCase for class names (uppercase for the first letter of each word)
- Use "is" or "has" as prefixes for boolean variables
- Use UPPERCASE for constants
- Use descriptive and meaningful names for your variables, functions, and classes.
//variable
let firstName = "Surbhi";
//function
function displayName() {
return "Surbhi Dighe";
}
displayName();
//boolean
let isLoading = false;
let hasName = true;
//constants
let SECONDS = 60;
//class
class DisplayName {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
var name = new DisplayName('Surbhi', 'Dighe');
call(), apply(), and bind() methods are used to attach a function into an object and call the function as if it belonged to that object.
call() - call() is used to invoke a function immediately with a specified this value and allows you to pass the arguments one by one
let person = {name: 'Surbhi'};
function printName(message) {
console.log(message + ' ' + this.name); // output ========> "Hello Surbhi"
}
printName.call(person, 'Hello');
apply() - apply() is used to invoke a function immediately with a specified this value and allows you to pass the arguments as an array
let person = {name: 'Surbhi'};
function printName(message) {
console.log(message + ' ' + this.name); // output ========> "Hello Surbhi"
}
printName.apply(person, ['Hello']);
bind() - bind() returns a new function (which can be invoked anytime), with a specified this value and allows you to pass in arguments
let person = {name: 'Surbhi'};
function printName(message) {
console.log(message + ' ' + this.name); // output ========> "Hello Surbhi"
}
let sayHello = printName.bind(person, "Hello");
sayHello();
isNaN() is a built-in JavaScript function. It takes a single argument and returns true if the argument is not a number, otherwise it returns false.
let num1 = 5;
let num2 = "hi";
console.log(isNaN(num1)); // output ========> false
console.log(isNaN(num2)); // output ========> true
The value of 'this' is determined by the context in which it is used. In general, 'this' keyword refers to the object it belongs to. The 'this' keyword in JavaScript can have different values depending on where it is used -
- If it is used inside a method, then it refers to the object that it belongs to
- If it is used inside any function or alone (i.e outside any function or method), then it referes to the global object
- If it is used in the context of an event handler, such as a click event, then it refers to the element that triggered the event
Single-line comments - Add comments using 2 forward slashes //
// this is a single line comment
Multi-line comments - Enclose the text between /* and */
/*
This is a
multiline comment
example
*/
The typeof operator returns a string that indicates the data type of the variable/value.
let var1 = "Surbhi";
let var2 = 10;
console.log(typeof var1); // output ========> "string"
console.log(typeof var2); // output ========> "number"
Yes, JavaScript is a case-sensitive language. For e.g., the variables firstName and firstname are considered to be two different variables.
let firstName = "Surbhi";
console.log(firstname); // output ========> Uncaught ReferenceError: firstname is not defined
Both are used to add elements to an array, but they add elements in different ways.
push() - It adds one or more elements to the end of an array and returns the new length of the array.
let arr = [1,2,3,4];
let newArr = arr.push(5,6,7);
console.log(newArr); // output ========> 7
console.log(arr); // output ========> [1, 2, 3, 4, 5, 6, 7]
unshift() - It adds one or more elements to the beginning of an array and returns the new length of the array.
let arr = [1,2,3,4];
let newArr = arr.unshift(5,6,7);
console.log(newArr); // output ========> 7
console.log(arr); // output ========> [5, 6, 7, 1, 2, 3, 4]
Both are used to remove elements from an array, but they remove elements in different ways.
pop() - It removes the last element of an array and returns the removed element.
let arr = [1,2,3,4];
let newArr = arr.pop();
console.log(newArr); // output ========> 4
console.log(arr); // output ========> [1,2,3]
shift() - It removes the first element of an array and returns the removed element.
let arr = [1,2,3,4];
let newArr = arr.shift();
console.log(newArr); // output ========> 1
console.log(arr); // output ========> [2,3,4]
getElementById - This method is used to get an element by its ID.
getElementsByClassName - This method is used to get a collection of elements by their class name.
getElementsByTagName - This method is used to get a collection of elements by their tag name.
querySelector - This method is used to get the first element that matches a specified CSS selector.
querySelectorAll - This method is used to get a collection of elements that match a specified CSS selector.
In JavaScript, promises are used to handle asynchronous operations. The code does not directly or immediately return a value. Instead, it returns a promise that, it will eventually get resolved or rejected. A promise can have three possible states:
Pending - The initial state, before the promise is resolved or rejected.
Resolved - When a promise has been successfully completed and a value is returned.
Rejected - When a promise has been failed and an error is returned.
let promise = new Promise((resolve, reject) => {
const result = AsynchronousTaskFunction();
if (result) {
resolve(result);
} else {
reject(new Error('Operation failed'));
}
});
promise.then(result => {
console.log(result, "It is resolved");
}).catch(error => {
console.error(error, "It is rejected");
});
Every object in JavaScript has a built-in property, which is called its prototype. All JavaScript objects inherit properties and methods from a prototype.
It allows us to add properties and methods to all instances of a given object type.
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.city = "Indore"
var person1 = new Person('John', 30);
console.log(person1);
Callback hell is a situation in which callback functions are nested inside each other at several levels, making the code difficult to read, write, and maintain.
asyncFunc1(function(response1) {
asyncFunc2(response1, function(response2) {
asyncFunc3(response2, function(response3) {
asyncFunc4(response3, function(response4) {
asyncFunc5(response4, function(response5) {
// ... and so on
});
});
});
});
});
The event loop is a key mechanism in JavaScript that provides an illusion of being multithreaded despite being single-threaded, allowing for non-blocking, asynchronous processing of events and callbacks.It monitors both the callback queue and the call stack.
If the call stack is not empty, the event loop waits until it is empty
If the call stack is empty it places the next function from the callback queue to the call stack
ES6 stands for ECMAScript 6, also known as ECMAScript 2015. It is the sixth major version of the ECMAScript language specification for JavaScript. Below are some of the significant features of ES6
Arrow functions, template literals, block-scoped variables (let and const), default function parameters, array and object destructing, promises, rest and spread operators, classes.
method - A method is a function associated with an object.
let obj = {
name:"Surbhi",
greet: function(){
return `Hi ${this.name}`
}
}
console.log(obj.greet());
function - A function is a self-contained block of code that can be defined and called independently of any object.
function sum(a, b) {
return a + b;
}
sum(2,4);
async/await is a feature in JavaScript that allows us to write asynchronous code that looks more like synchronous code. "await" works only inside "async" functions
"async" ensures that a function returns a promise and "await" pause the execution of the function until a promise is resolved or rejected.
const getData = async () => {
const response = await fetch('https://api.openweathermap.org/data/2.5/weather?q=New%20York&appid=YOUR_API_KEY');
const data = await response.json();
console.log(data);
}
getData();
The preventDefault() method is used to stop the default action of an element.
E.g., when a user submits a form, the browser sends the form data to the URL specified in the action attribute. In some cases, we may want to prevent this default behavior.
JSON.stringify() method is used to convert a JavaScript object or value into an equivalent JSON string.
const obj = { firstname: "Surbhi", lastname: "Dighe" };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // output ========> {"firstname":"Surbhi","lastname":"Dighe"}
You can use the clearTimeout method. This method takes the id returned by setTimeout and cancels the timer.
const timerId = setTimeout(() => {
console.log('setTimeout is done');
}, 5000);
clearTimeout(timerId);
JavaScript is single-threaded, means it can execute only one task at a time. Still, it supports asynchronous operations using the Web API provided by the browser.
In JavaScript, scope refers to the current context of your code. This context determines visibility and accessibility of variables, functions, and objects within a certain part of the code. Generally, there are two types of scope in JavaScript - global scope and local scope.
Global scope - Global scope refers to the variables, functions, and objects that are defined outside of any function or block. They can be accessible from any part of the code.
let name = "Surbhi";
function printName() {
console.log(name); // output ========> Surbhi
}
printName();
Local scope - Local scope refers to the variables, functions, and objects that are defined inside any function or block. They can be accessible only within the function or block where they are defined.
function printName() {
let name = "Surbhi;
console.log(name); // output ========> Surbhi
}
printName();
console.log(name); // ReferenceError: name is not defined
1. parseInt() - This function takes a string and an optional radix (a number between 2 and 36 that represents the base in a numeral system) as its arguments.
console.log(parseInt("20")); // output ========> 20
console.log(parseInt("52", 8)); // output ========> 42
2. unary plus operator (+) - This operator converts a string into a number and it should be placed before the operand.
console.log(+"10"); // output ========> 10
3. Number() - It is a built-in function which converts its argument to a number. If the argument is a string that contains non-numeric characters, then it returns NaN.
Number("10"); // output ========> 10
Number("abc"); // output ========> NaN
We can use the navigator.platform property to find out the operating system of the client machine
console.log(navigator.platform); // output ========> 'Linux x86_64'
Frameworks - Angular, Ember.js, Vue.js, Meteor, Next.js
Libraries - React, Backbone.js
Event bubbling and Event Capturing are two different mechanisms used for handling event propagation in the HTML DOM API. When an event is triggered on an element which is inside another element, and both elements have an event listener attached to them , the event propagation mode determines the order in which the elements receive the event.
Event Bubbling - The event is first triggered on the innermost element and then propagated/bubbles up to its parent elements and eventually to the outermost element in the DOM hierarchy.
Event Capturing - The event is first triggered on the outermost element and then propagated/bubbles down to its child elements and eventually to the innermost element in the DOM hierarchy.
This method is used to stop the event from propagating up or down the DOM hierarchy.
To change the style of an element using JavaScript, we can use the style property of the element's DOM object.
document.getElementById("myDiv").style.backgroundColor = "red";
Object destructuring allows you to extract properties from an object and assign them to variables.
const fullname = {
firstName: 'Surbhi',
lastName: 'Dighe',
};
const { firstName, lastName } = fullname;
console.log(firstName); // output ========> 'Surbhi'
console.log(lastName); // output ========> 'Dighe'
Alert Box - It has only one button, typically labeled "OK" and it is used to display a message to the user.
Confirmation Box - It has two buttons, typically labeled "OK" and "Cancel" and it is used to ask the user to confirm an action.
In JavaScript, we can handle exceptions using a try-catch block. The try block contains the code that might throw an exception, and the catch block contains the code that handles the exception if it occurs.
try {
const name = "Surbhi";
console.log(firstname)
} catch (error) {
console.log("Error: " + error); // output ========> Error: ReferenceError: firstname is not defined
}
- Improve the load time of web pages
- Ease of editing
- Code reusability
- Separation of Code
An anonymous function is a function that does not have a name. It is common to assign anonymous functions to a variable or use them as callback functions.
const sayHi = function() {
console.log("Hi there!!");
};
sayHi();
A first order function is a function that does not take any other functions as arguments and does not return any function as its result.
function sayHello() {
console.log("A first order function")
}
sayHello();
Dot notation - It uses dot (.) to access the object properties.
object.propertyName
Bracket notation - It uses bracket "[ ]" to access the object properties.
object[propertyName]
Object destructuring - It creates variables that correspond to the object properties.
const obj1 = {name : "surbhi", designation : "SE"}
const {name , designation} = obj1;
console.log(name, designation) // output ========> "Surbhi","SE"
slice() - This method creates a new array by copying a specified section of an existing array and returns that new array. This operation does not modify the original array in any way.
const arr=[1,2,3,4,5];
const result = arr.slice(2)
console.log(arr); // output ========> [1, 2, 3, 4, 5]
console.log(result); // output ========> [3, 4, 5]
splice() - This method is used to add or remove elements from an array. It modifies the original array and returns an array containing the removed elements (if any).
const arr=[1,2,3,4,5];
const result = arr.splice(2)
console.log(arr); // output ========> [1, 2]
console.log(result); // output ========> [3, 4, 5]
When working with special characters such as ampersands (&), apostrophes ('), double quotes (" "), and single quotes (' '). JavaScript requires the use of escape characters, which are often represented by the backslash (). These escape characters instruct JavaScript to interpret the special characters correctly. Below are some common escape characters in JavaScript:
- \n - Represents a newline character.
- \t - Represents a tab character.
- ' - Represents a single quote character.
- " - Represents a double quote character.
- \ - Represents a backslash character.
- \r - Represents a carriage return character.
location.href - It is used to navigate to a new page and add it to the browser's history.
window.location.href = "https://www.example.com";
location.replace - It is used to replace the current page with a new page without adding it to the history.
window.location.replace("https://www.example.com");
innerHTML retrieves or modifies the HTML content of an element, including its tags, while innerText only retrieves or modifies the text content of an element, excluding any HTML tags.
//HTML code
<div id="example">Hello <strong>world</strong>!</div>
//Javascript code
let result = document.getElementById("example").innerHTML;
console.log(result); // output ========> "Hello <strong>world</strong>!"
//HTML code
<div id="example">Hello <strong>world</strong>!</div>
//Javascript code
let result = document.getElementById("example").innerText;
console.log(result); // output ========> "Hello world!"
To get the current time using JavaScript, you can use the built-in Date object.
let currentTime = new Date();
let hours = currentTime.getHours();
let minutes = currentTime.getMinutes();
let seconds = currentTime.getSeconds();
console.log(`Current time is ${hours}:${minutes}:${seconds}`); // output ========> "Current time is 16:7:22"
Currying is the process of breaking down a function that takes multiple arguments into a series of functions that take a single argument.
const add = (a, b) => {
return a + b;
}
const curryingAdd = (a) => (b) => a + b;
console.log(add(5, 4)); // output ========> 9
console.log(curryingAdd(5)(4)); // output ========> 9
shallow copy - It creates a new object that points to the same memory location as the original object. Therefore, any changes made to the original object will also be reflected in the shallow copy. It can be done using the spread operator or object.assign() method.
deep copy - It creates a completely new object with its own memory space. This means that any changes made to the original object will not be reflected in the deep copy. It can be done using the JSON.parse() and JSON.stringify() methods.
A service worker is a kind of web worker that operates in the background of a web page, decoupled from the primary browser thread, and capable of executing diverse tasks. It is essentially a JavaScript file that is associated with a web page and executes independently, without depending on the user interface.
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
{
"users":[
{"name":"Test1", "age":"20"},
{"name":"Test2", "age":"30"},
{"name":"Test3", "age":"40"}
]
}
The Object.keys() method returns an array containing all the keys of the object
const obj1 = {
name: 'Surbhi',
city: 'Indore'
};
const keys = Object.keys(obj1);
console.log(keys); // output ========> ["name", "city"]
A unary function is a function that takes only one argument
function greet(message){
console.log(message, "unary function example");
}
Promise chaining is the term used to describe the process of executing a series of asynchronous tasks one after another in a specific order
fetch('API_URL')
.then(response => response.json())
.then(data => printData(data))
.then(anotherData => printAnotherData(anotherData))
.then(finalData => printFinalData(finalData))
The eval() is a method of the JavaScript global object and it takes a string as an argument and evaluates it.
console.log("10" + "20"); // output ========> 30
You can assign default values to variables using the || operator. If the variable on the left-hand side of the || operator is falsy (e.g. null, 0, undefined, NaN, empty string, false), the expression on the right-hand side of the || operator will be returned.
const var1 = undefined || 'default value';
console.log(var1); // output ========> "default value"
const var1 = "surbhi" || 'default value';
console.log(var1); // output ========> "surbhi"
Object.isExtensible() method is used to determine if an object is extensible or not. It returns true if new properties can be added to the object otherwise it returns false.
const obj1 = { name: 'surbhi' };
console.log(Object.isExtensible(obj1)); // output ========> true
- Object.preventExtensions()
- Object.seal()
- Object.freeze()
- Object.freeze makes the object immutable
- Can not add new properties to existing object
- Can not delete or modify existing properties
const obj = {
property1: 'value 1',
property2: 'value 2',
};
Object.freeze(obj);
obj.property1 = 'new value'; // This will not modify the existing property
obj.property3 = 'value 3'; // This will not add new property to the object
console.log(obj); // output ========> { property1: "value 1", property2: "value 2" }
- Object.seal makes the object immutable
- Can not add new properties or delete existing properties
- Can modify existing properties.
const obj = {
property1: 'value 1',
property2: 'value 2',
};
Object.seal(obj);
obj.property1 = 'new value'; // This will modify the existing property
obj.property3 = 'value 3'; // This will not add new property to the object
console.log(obj); // output ========> { property1: "new value", property2: "value 2" }
<noscript>
tag is used to determine if JavaScript is disabled on a page. It provides alternative content that should be displayed when JavaScript is not supported or disabled in the user's browser.
<noscript>
<p>JavaScript is disabled in your browser.</p>
</noscript>
<script>
console.log("JavaScript is enabled on page");
</script>
getTime() method is used to compare two date objects.
let date1 = new Date();
let date2 = new Date(date1);
console.log(date1.getTime() < date2.getTime()); // output ========> false
console.log(date1.getTime() > date2.getTime()); // output ========> false
console.log(date1.getTime() === date2.getTime()); // output ========> true
Yes, JavaScript supports automatic type conversion. It refers to the implicit conversion of one data type to another by the JavaScript engine.
Variable shadowing means a variable declared in a local scope has the same name as a variable declared in an outer scope. The inner variable "shadows" the outer variable and the outer variable is said to be shadowed.
let x = 10;
function Demo() {
let x = 20;
console.log(x); // output ========> 20
}
myFunction();
console.log(x); // output ========> 10
The ternary operator is a shorthand conditional operator that allows you to write a compact if-else statement in a single line.
condition ? expression1 : expression2;
It is evaluated from left to right. If the condition is true, the result of the entire expression is expression1, otherwise it's expression2.
let number = 20 ;
let result = number >= 15 ? "output 1" : "output 2";
console.log(result); // output ========> output 1