JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object based Programming language.
Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent. Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language.
DOM stands for Document Object Model. A document object represent the html document. When the browser renders the html page, It creates document object representing the html document which can be used to access and change the content of html.
The == operator checks equality only whereas === checks equality and data type i.e. value must be of same type.
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered. Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.
Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared. Example: // Declare a global globalVariable = “Test”; The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.
Javascript uses the concept of hoisting, It is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.It means no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. Let's understand it with few examples how the code actually executes when using using variable, function declarations at the bottom: Example 1 a = 15; console.log(a); var a; The above code prints 15 in console, Because due to hoisting variable initialization moved to top. Example 2 printMsg(); function printMsg(){ } printMsg(); function printMsg(){ a = 10; console.log(a); var a; } console.log(num); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage
console.log(a);
let a;
var num; // Declaration
num = 6; // Initialization
We can write comments in JavaScript with below 2 ways: Single Line Comment: It is represented by // (double forward slash) // for Single line comments Multi-Line Comment: Slash represents it with asterisk symbol as /* ... */ /* This is first line coment This is second line comment. .... */
In JavaScript, All the availalbe data types area categorised into two categories. 1. Primitive Data Types: Data type which is not an object and has no methods.The primitive data types are as follows: It can be an integer, a floating point value, an exponential value, e.g., let a=250; // an integer value let b=25.5; // a number containing a decimal let c = 10e4 // an exponential value which evaluates to 10*10000; It can be group of characters enclosed by a single or double-quotes or by backticks, e.g., var str = “This is a string”; 2. Non-primitive Data Types: These are the data types which if mostly of Object type. The non-primitive data types are as follows:
Data Type
Description
Number
String
Boolean
It represents boolean value either true or false
Undefined
It represents an undefined value
Null
It represents null, which mean there no value
Date Type
Description
Object
represents an instance through which we can access members
Array
represents a group of similar values
Function
This is not a data type in JavaScript, But when we check the type of any function then we see Object.
Both are data types of JavaScript.
Below are the common ways by which Objects can be created in JavaScript: 1.By object literal: This is most shortest way to create object in JavaScript. Example: const user = {name:"Alax",age:25} ; 2. By Function constructor: Here we define a function and create object of that function. function Greet(name, age){ 3. By Object constructor: const user = new Object(); user.name="Aman"; user.age=25;
this.name=name;
this.age = age;
}
var object = new Greet("Rohit",25);
It's peace of information which is stored on users local machine when any website is visited. It is stored by the web browser when any website is visited. It is mainly stored in name-value pair separated with semi-colon. Cookie can be creted like below: document.cookie = "uid=142987561"; Read the cookie with JavaScript const x = document.cookie;
Website uses the Cookie to streamline the user experience when a user is visitiing same website frequently. Very common reasons to use cookie are:
Different ways to delete a Cookie:
Cookie
localStorage
sessionStorage
Lifetime:As configured using Expires option
until deleted
until tab is closed or deleted
SSL support: Supported
Not Supported
Not Supported
Maximum data size: 4KB
5MB
5MB
Accessed: Both client-side & server-side
only Client side
Only Client side
localStorage is a property which allows JavaScript web application/sites to store key/value pairs data in a web browser without expiration date. The data stored in the web browser will stay even after the browser window is closed.
There are mainly 5 methods available which are:
As we know this is also a type to create new object in JavaScript. But if we talk about the reusability then it is most used way of creating object because if it is needed to create multiple objects with similar properties and function then this approach is used. Example: var student2 = new Person("John", 34, 97); With the above approach, Any number of object can be created of type Student.
function Student(name,age,marks){
this.name = name;
this.age = age;
this.marks = marks;
}
const student1 = new User("Alax", 76, 90);
console.log(student1);
console.log(student2);
The use of "use strict" is to indicate that the code should be executed in "strict mode". Strict mode changes some previously-accepted mistakes into errors. Without "use strict" a=10; console.log(a); // Output: 10 with "use strict" "use strict"; a=10; console.log(a); // Output: Uncaught ReferenceError: a is not defined
Null
Undefined
It is the value assigned to a variable which means the variable has no value in it.
Any variable retruns undefined when variable is declared but any value is not assigned in it.
It's type is Object
It's type is undefined
While performing primitive operations, It converts to zero
While performing primitive operations, It converts to NaN
This function mainly evaluates JavaScript code represented as a string, Which can be a JavaScript expression, variable, statement, or sequence of statements. Example: eval('2 + 2'); // returns 4
The Browser Object Model also known as BOM allows JavaScript to "talk to" the browser. There are no official standards for the Browser Object Model (BOM), It can behave defferently based on different browsers.. It consists of the objects navigator, history, screen, location and document which are children of the window.
The Window Object is used to control the browser window lifecycle and perform various operations on it. The window object is supported by all browsers. It represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Document object is a property of the window object. See example below: // Both are same window.document.getElementById("p1"); document.getElementById("p1");
The document object represents the whole html document. In the browser when html document is loaded, it becomes a document object. It is the root element of the loaded html document. It is part/child of window object.
Window
Document
It is the root level element in any window over browser
Also known as Document Object Model(DOM), is the direct child of the window object
alert(), confirm() and properties like document, location are the methods available in this object
getElementById, getElementByTagName, createElement etc are the methods available in it
window object is available implicitly in the page
It can accessed via window.document or document.
The window.history object contains the browser's history.Previous and next URLs can loaded in the history using window.history.back() and window.history.forward() methods.
Used to prevent the page from refreshing it and parameter "zero" is passed while calling. Void(0) is used to call another method without refreshing the page.
Global variables are the variable that are available throughout the entire code of the script without any scope. To declare JavaScript global variables inside function, you need to use window object i.e., window.value=90
The form can be submitted using below ways in JavaScript:
JavaScript is an interpreted language, not a compiled language. Programing languages such as C++ or Java needs to be compiled before it is run. The browser's interpreter reads the complete JavaScript code, interprets each line, and runs it. But these days modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
Tree shaking is a form of dead code elimination. It used to reduce the bundle size of any application. For Example, While working with Angular we install many packages in the application but while creating its bundle tree shaking helps to pick only few part of that packages from node_modules which have been used in our code. Tree shaking is implemented in Rollup and Webpack bundlers.
Pure function always returns the same result if the same arguments passed in it. It does not change on external changes like any state, or data, changes during the program execution. It only depends on the arguments. Also it not produces any observable related effects such as network requests, data mutation, etc.
Arrow functions were introduced in ES6. An arrow function expression is a shorter way to define a function, but is limited and can't be used in all situations. It does not have its own scope or this, It receives the scope of the context where it is defined. // before hello = function() { // with ES6 hello = () => {
return "Hello World!";
}
return "Hello World!";
}
ECMAScript (or ES) is a general-purpose programming language, JavaScript is a subset of ECMAScript. It is a JavaScript standard meant to ensure the interoperability of Web pages across different Web browsers.
The let statement declares a block-scoped local variable, Which means if any variable is declared in any if block then it is only accessible inside that block only. Earlier when any variable was declared using the var keyword then its scope was function level. With the help of let we can have a variable with multiple values as per their scope. let a = 100;
if (condition===true) {
let a = 120;
console.log(a); // Output: 120
}
console.log(a); // Outpur: 100
let Hoisted but not initialized var
A closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. It is combination of a function and the lexical environment within which that function was declared. function user(message) { func('Hello'); func('Good morning'); As per the above code, the inner function(greetUser) has access to the variables in the outer function scope(user) due to closure in javascript.
function greetUser() { // greetUser() is the inner function, a closure
console.log(message+' '+name); // message variable declared in the parent function
}
return greetUser();
}
let func = user();
When scripts executes in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.
Yes, JavaScript is a case sensitive language.
JavaScript was developed by Netscape, in collaboration with Sun Microsystems. Before JavaScript, web browsers were fairly basic pieces of software capable of displaying hypertext documents. JavaScript was later introduced to add some extra spice to web pages and to make them more interactive. The first version, JavaScript 1.0, debuted in Netscape Navigator 2 in 1995
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a link, prevent the link from following the URL Clicking on a "Submit" button, prevent it from submitting a form
This method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, Want to show any alert or hide any error message after 2 seconds using setTimeout method, setTimeout(function(){ alert("Request sent to server"); }, 2000);
This method is used to perform any task or call any function after a fixed interval. Want to show message in every 5 seconds, the it can be done like beow: setInterval(function(){ console.log("Hello World!"); }, 5000);
Progressive Web Apps are web apps that use emerging web browser APIs and features along with traditional progressive enhancement strategy to bring a native app-like user experience to cross-platform web applications. A Progressive web application should have the following features: Secure contexts (HTTPS): The web application must be served over a secure network Service workers: A service worker is a script that allows intercepting and control of how a web browser handles its network requests and asset caching. With service workers, web developers can create reliably fast web pages and offline experiences. Manifest file: A JSON file that controls how your app appears to the user and ensures that progressive web apps are discoverable. It describes the name of the app, the start URL, icons, and all of the other details necessary to transform the website into an app-like format.
Let's say the URL is https://jsonworld.com/javascript-articles?page=4 and we want the value of 4 then below code can be used. const urlParams = new URLSearchParams(window.location.search); console.log(page); // Output: 4
const page = urlParams.get('page');
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it. For example, a polyfill could be used to mimic the functionality of a text-shadow in Internet Explorer 7(ID7) using proprietary IE filters, or mimic rem units or media queries by using JavaScript to dynamically adjust the styling as appropriate, or whatever else you require.
The anonymous function is a function that is without a name. These functions are mainly assigned to a variable name or used as a callback function. For example, const greetUser = function(){ //Anonymous function assigned to a variable ['a','b','c'].map(function(element){ //Anonymous function used as a callback function
//do something
};
//do something
});
TypeScript is an open-source language that builds on JavaScript, one of the world’s most used tools, by adding static type definitions. Developers working on bigger projects are recommended to use TypeScript over JavaScript.
Key Differences:
A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.
In Simple we can say, 'This' keyword refers to the object from where it was called.
It can be done like below: // Change Style document.getElementById("p").style.fontSize = "16"; // Change Class document.getElementById("myText").className = "form-style";
We can use 'Try… Catch---finally' to handle exceptions in the JavaScript. Try{
Write your Code here
}
Catch(exp){
Write your Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}
document.write("Hello World!") is used to print the text – 'Hello World!' in the screen.
The onload function do not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed. onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.
Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. Web storage provides two mechanisms for storing data on the client. Local storage: It stores data for current origin with no expiration date. Session storage: It stores data for one session and the data is lost when the browser tab is closed.
JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.
debugger
An event is an action that a user or system may trigger, such as pressing a key, a mouse click, etc.