Javascript QnA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

1.

Why choose JS

JavaScript is emerging as the only language that can be used both in frontend and backend
programming. This has truly enabled fullstack web development. Easy to learn. You can also create
desktop, mobile, and web apps with Electron, React Native, and React.

2. JS is dynamic typing? Explain

Yes. It means that JS does not require the explicit declaration of the variables before they’re used.
For example declare var name=”John. ‘name’ is assigned to “John,” which is a String. Later, it can be
assigned to 34, a Number. An error will not occur and JS will continue reading the code as normal.

3. why javascript is called loosely typed language?

JavaScript is a loosely typed language, meaning you don’t have to specify what type of information
will be stored in a variable in advance. JavaScript automatically types a variable based on what kind of
information you assign to it.

4. What are primitive and nonprimitive data types

Prim are mutable where as non-prim aren’t. Prim are compared by value and non-prim are copied by
reference. Prims don’t have methods and properties.

5. Whats call by reference and by value

Call by value method copies the value of an argument into the formal parameter of that function.
Therefore, changes made to the parameter of the main function do not affect the argument. Call by
reference method copies the address of an argument into the formal parameter. In this method, the
address is used to access the actual argument used in the function call. It means that changes made in
the parameter alter the passing argument.

6. Diff between == & ===

=== first checks if type is same and then if value is also same it returns true.

== checks only for value and returns true if it can be implicity convert to that value. Ex string 5 n
number 5 are equal.

7. 5+”5” => 55

6-“5” => 1

6* “a” => Nan

8. Type of :

Null: object, NaN: number, array: obj, undefined: undefined,


any function: function

9. What is type coercion

Type Coercion refers to the process of automatic or implicit conversion of values from one data type
to another. When any string or non-string value is added to a string, it always converts the non-string
value to a string implicitly. When an operation like subtraction (-), multiplication (*), division (/) or modulus
(%) is performed, all the values that are not number are converted into the number data type, as these
operations can be performed between numbers only.

10. Diff between null and undefined


Null is an assignment value. It can be assigned to a variable as a representation of no value. Null means
an empty or non-existent value. Null is assigned, and explicitly means nothing. Null is an object

Undefined means a variable has been declared but has not yet been assigned a value. Undefined is of
type undefined

11. Truthy and falsy values:

False: 0, undefined, null, Nan,‘’, false

Truth: any number except 0, any string except empty string, empty or filled array, empty or filled
object, true

12. Ecsape characters

JavaScript uses the \ (backslash) as an escape character. When working with strings, you'll notice there
are some characters that always seem to break your program. It prevents JS from interpreting a quote as
end of string

You can avoid by using: opposite string syntax, template literals, use escape characters

13. Arrays? Its props and methods:

Ordered, integer indexed collection of values. Neither length nor type is fixed in JS

Property: length

Methods: pop, shift, push, unshift, indexOf, splice, slice, reverse, includes, toString, join, keys, values,
entries

The splice() method adds and/or removes array elements. Modifies the original array.
array.splice(index, howmany, item1, ....., itemX)

The slice() method creates a new array. array.slice(start, end) -> end not inclusive.

toString() JavaScript automatically converts an array to a comma separated string when a primitive
value is expected.

All JavaScript objects have a toString() method.

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator

14. difference between for and foreach

For: The break statement can be used to come out from the for loop. Faster in performance. Can use on
strings

Foreach: In foreach cannot be used because of the callback function. Slower. Should convert strings to
array and then use this.

The find() method returns the value of the first element in the provided array that satisfies the provided
testing function. If no values satisfy the testing function, undefined is returned.

The every() method tests whether all elements in the array pass the test implemented by the provided
function. It returns a Boolean value.

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end
index (default array.length). It returns the modified array.

The filter() method creates a new array with all elements that pass the test implemented by the provided
function.

The forEach() method executes a provided function once for each array element.
The map() method creates a new array populated with the results of calling a provided function on every
element in the calling array.

15. Object? Methods and props:

Unordered, string indexed collection of values, name-values pairs

Methods: freeze (Prevents any changes to an object), isFrozen, seal (Prevents changes
of object properties (not values)), isSealed, assign, keys, values, hasOwnProperty

16. This keyword : In most cases, the value of this is determined by how a function is called (runtime
binding). It can't be set by assignment during execution, and it may be different each time the function
is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's
called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains
the this value of the enclosing lexical context).

Global: {}

Es5 func: global object

Es6 arrow func: this value in immediate outer space

Method: current obj

Constructor func: new obj

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

17. Func methods:

Call => invoked immediately, pass arg one by one, func.call(thisvalue, arg1, arg2…)

let obj = {age: 7}

let increaseAge = function(a, b, c){

return this.age = this.age + a + b + c

increaseAge.call(obj, 5, 0, 1)

Apply=> invoked immediately, pass arg as an array, func.apply(thisvalue,[ arg1, arg2…])

Let’s say instead of writing out each and every argument, we wanted to pass in an array of arguments.

Bind=>returns new func, that func needs to be invoked separately, pass arg one by one. Allows you to
bind ‘this’ value now and execute func later

18. Func exp: assigning a func to a variable. You can invoke the func using variable name
HOF: In Javascript, functions can be assigned to variables in the same way that strings or arrays can.
They can be passed into other functions as parameters or returned from them as well. A “higher-order
function” is a function that accepts functions as parameters and/or returns a function.

Callback Functions: In JavaScript, a callback function is a function that is passed into another function as
an argument. This function can then be invoked during the execution of that higher order function (that it
is an argument of). Since, in JavaScript, functions are objects, functions can be passed as arguments.

Pure func: is a function (a block of code ) that always returns the same result if the same arguments are
passed. It does not depend on any state, or data change during a program’s execution rather it only
depends on its input arguments. Doesn’t modify variable outside of their scope

IIFE: is a JavaScript function that runs as soon as it is defined. There is a good chance of having same
name of function exists in different .js files written by multiple developer and if these files included in a
single web page then it will pollute the global scope by having two or more function or variables with the
same name. IEFE solves this problem by having its own scope and restricting functions and variables to
become global. The functions and variables declare inside IIFE will not pollute global scope even they
have same name as global variables & functions.

(function () {

statements

})();

Recursive func: A function that calls itself is called a recursive function. A recursive function always has a
condition to stop calling itself. Otherwise, it will call itself indefinitely.

19. Func hoisting

Hoisting is a JavaScript technique which moves variables and function declarations to the top of their
scope before code execution begins. Within a scope no matter where functions or variables are declared,
they're moved to the top of their scope.

20. Var, let and const

· var declarations are globally scoped or function scoped while let and const are block scoped.

· var variables can be updated and re-declared within its scope; let variables can be updated but
not re-declared; const variables can neither be updated nor re-declared.

· They are all hoisted to the top of their scope. But while var variables are initialized with
undefined, let and const variables are not initialized.

· While var and let can be declared without being initialized, const must be initialized during
declaration.

Just like var, let declarations are hoisted to the top. Unlike var which is initialized as undefined, the
let keyword is not initialized. So if you try to use a let variable before declaration, you'll get a
Reference Error

21. How to create an arrary or object

Array literal: []

Array constructor: new keyword =>const cars = new Array("Saab", "Volvo", "BMW")
Obj literal: {}

Obj constructor: new keyword=>const person = new Object(); person.firstName = "John";


person.lastName = "Doe";

22. Shallow – deep copy of Objects

Shallow copy: certain values’/sub values are still connected to the original array

Let a= [‘dct’], let c=a

Deep copy: all values are copied and disconnected from original array

Array deep copy: let b = a.slice(0),

b= [].concat(a),

b=[…a]

Obj deep copy: let b = Object.assign({}, a),

b={…a}

23. Lexical scope

Variables defined outside a function can be accessible inside another function.But the opposite is not
true; the variables defined inside a function will not be accessible outside that function.

24. DOM? Methods and props

The Document Object Model (DOM) is a programming interface for web documents. It represents the
page so that programs can change the document structure, style, and content. The DOM represents the
document as nodes and objects; that way, programming languages can interact with the page. (DOM)
representation allows it to be manipulated. As an object-oriented representation of the web page, it can
be modified with a scripting language such as JavaScript.

The DOM (Document Object Model) is an API that represents and interacts with any HTML or XML
document. The DOM is a document model loaded in the browser and representing the document as a
node tree, where each node represents part of the document (e.g. an element, text string, or comment).

The DOM is one of the most-used APIs on the Web because it allows code running in a browser to
access and interact with every node in the document. Nodes can be created, moved and changed. Event
listeners can be added to nodes and triggered on occurrence of a given event.

getElementById, getElementByClass, getElementByName, getElementByTagName, querySelectorAll

25. What ways to handle events

HTML events are "things" that happen to HTML elements. Event handlers can be used to handle and
verify user input, user actions, and browser actions:

Things that should be done every time a page loads

Things that should be done when the page is closed

Action that should be performed when a user clicks a button

Content that should be verified when a user inputs data


26. Explain event propagation / event bubbling and its phases.

Event propagation is a mechanism that defines how events propagate or travel through the DOM tree to
arrive at its target and what happens to it afterward.

Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element
inside another element, and both elements have registered a handle to that event. It is a process that
starts with the element that triggered the event and then bubbles up to the containing elements in the
hierarchy. In event bubbling, the event is first captured and handled by the innermost element and then
propagated to outer elements.

27. local storage and its methods

The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. The
localStorage object stores data with no expiration date. The data will not be deleted when the browser is
closed, and will be available the next day, week, or year. The localStorage property is read-only.

localStorage.setItem("key", "value");

var lastname = localStorage.getItem("key");

localStorage.removeItem("key");

localStorage.clear()

28. AJAX and its benefits

AJAX = Asynchronous JavaScript And XML. AJAX is not a programming language.

AJAX just uses a combination of:

A browser built-in XMLHttpRequest object (to request data from a web server)

JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the
scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Some of the many benefits of using Ajax in web-based applications include the following:

Improved user experience

Asynchronous processing

Reduced server hits and network load

Platform and architecture neutrality

Multibrowser support

Faster page renders and improved response times

29. What is a closure

Closure means that an inner function always has access to the vars and parameters of its outer function,
even after the outer function has returned.

function OuterFunction() {

var outerVariable = 100;


function InnerFunction() {

alert(outerVariable);

return InnerFunction;

var innerFunc = OuterFunction();

innerFunc(); // 100

In the above example, return InnerFunction; returns InnerFunction from OuterFunction when you call
OuterFunction(). A variable innerFunc reference the InnerFunction() only, not the OuterFunction(). So
now, when you call innerFunc(), it can still access outerVariable which is declared in OuterFunction().
This is called Closure.

Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create
private variables or functions.

30. difference between http and https

HTTP stands for Hypertext Transfer Protocol. When you enter http:// in your address bar in front of
the domain, it tells the browser to connect over HTTP. HTTP uses TCP (Transmission Control Protocol),
generally over port 80, to send and receive data packets over the web. To put it simply it is a protocol
that's used by a client and server which allows you to communicate with other websites.

HTTPS transmits its data security using an encrypted connection. Basically it uses a public key which
is then decrypted on the recipient side. The public key is deployed on the server, and included in what
you know as an SSL certificate. The certificates are cryptographically signed by a Certificate Authority
(CA), and each browser has a list of CAs it implicitly trusts. Any certificate signed by a CA in the trusted
list is given a green padlock lock in the browser's address bar, because it's proven to be "trusted" and
belongs to that domain.

31. what is dom manipulation in javascript

The Document Object Model (DOM) is a programming interface for web documents. It represents the
page so that programs can change the document structure, style, and content. The DOM represents the
document as nodes and objects; that way, programming languages can interact with the page. The DOM
is not part of the JavaScript language, but is instead a Web API used to build websites. The DOM was
designed to be independent of any particular programming language, making the structural
representation of the document available from a single, consistent API. Manipulating means changing the
document structure, style, and content.

32. What is data structure?

Data structures, at a high level, are techniques for storing and organizing data that make it easier to
modify, navigate, and access. Data structures determine how data is collected, the functions we can use
to access it, and the relationships between data.

Data structures enable us to:

· Manage and utilize large datasets

· Search for particular data from a database

· Design algorithms that are tailored towards particular programs


· Handle multiple requests from users at once

· Simplify and speed up data processing

JavaScript has primitive and non-primitive data structures. Primitive data structures and data types are native
to the programming language. These include boolean, null, number, string, etc.

Non-primitive data structures are not defined by the programming language but rather by the programmer.
These include linear data structures, static data structures, and dynamic data structures, like queue and
linked lists.

Promises and ajax

You might also like