1)
What is Javascript and why is it important?
High level interpreted programming language used to create interactive and dynamic content on
websites.
2)
3)
4)
5)
6)
7)
8)
9)
10)
What are different data types in JS?
Seven primitive data types:
Number--> Can’t hold large no.s
String --> “ ” or ‘ ‘
Boolean --> true/false
Null --> empty object or object with no value
Undefined--> doesn’t hold value, variable declared but no value assigned
Symbol --> new datatype to store anonymous and unique value . eg: var
symbol1 = Symbol('symbol');
BigInt --> for large numbers.
Non-primitive / Compound data types:
object
arrays
11)
What is hoisting in JS?
--> Hoisting is default behavior of JS where all the variable and function declarations are moved
on top.
Example 1:
a=3;
console.log(a);
var a;
// outputs 3 even when variable is declared after it is initialized.
Example 2:
hoistedFunc(): // outputs "Hello world!" even when the function is declared after
calling
function hoistedFunc(){
console.log("Hello world!");
}
Example 3: // Hoisting takes place in the local scope as well
function doSomething(){
x=33;
console.log(x);
var x;
}
doSomething(); //outputs 33
Note: Variable initializations are not hoisted but only declarations are hoisted.
var x;
console.log(x): // outputs undefined since the initialization of x is not hoisted
x=30;
Note: To avoid hoisting run JS in "use strict" mode on top of code:
"use strict";
x=40; // gives an error as x is not declared.
var x;
12) Difference between var and let keywords.
var and let both are used to declare the variables in JS. But there are some differences.
var has global scope means the value can be accessed from anywhere in the code or function scope
accessible anywhere in the function, let has local scope or block scope meaning the variable can be
accessed within the block of code where it is declared.
13) Is JavaScript statically or dynamically typed language?
Dynamically(loosely) typed language --> type of variable is checked during run-time rather
than statically typed language where type of variable is checked during compile time.
--> Static typing eg: String name; name ="John"; cannot have name = 34; Variables have types,
values have types, variable cannot change type.
--> dynamic typing eg: var name; name="John"; name = 34; variables have no types, values
have types, variables change type dynamically.
14) Explain passed by value and passed by reference.
--> In JS, primitive data types are passed by value whereas non-primitive passed by reference.
Passed by value (primitive datatypes): eg:
var y=40; // "=" operator allocates some space in memory where 40 is stored and
returns the location of allocated memory space, so y is pointing to location not 40.
var z=y; // assign operator takes the value of y(40) and allocates new memory space
and returns address. so variable z is not pointing to location of y but to new
location in memory.
if y=23; // this wont affect value of z as z is pointing to other location not the location
of y.
console.log(Z); // outputs 40.
passed by reference (non-primitive datatypes): eg:
var obj = { name:"Sabin", surname:"Khadka"};
var obj2 = obj; // "=" directly passes the location of variable obj to the variable obj2,
pointing to same location/address in the memory.
// any change in obj creates change obj2.
15) Explain scope and scope chain in JS.
--> Scope helps us to know what functions and variables we can or cannot access at
various part of code.
--> 3 types of scope: Global, Local/Function , Block scope.
--> Global Scope: all variables and functions with global scope can be accessed from anywhere in
the code.
--> Function Scope: All the variables and fucntions can be accessed within the function and not
outside it.
example:
function awesomeFunction(){
var a=3;
var multiplyBy2 = function(){
console.log(a*2);
}
}
console.log(a);
be accessed outside of it.
// inside the function a can be accessed.
// reference error since a is written in local scope and cannot
-->Blockscope : related to variables declared using let and const. var variables don't have block scope.
Accessed only inside the block and not outside.
{
let x = 45;
}
console.log(x); // Gives reference error since x cannot be accessed outside of
the block
for(let i=0; i<2; i++){
// do something
}
console.log(i); // Gives reference error since i cannot be accessed outside of the
for loop block
Scope chain: JS engine uses scope to find variables. Looks for variable in local scope, if not found then
looks for outer scope, if not found then looks for global scope.
var y = 24;
function favFunction(){
var x = 667;
var anotherFavFunction = function(){
console.log(x); // Does not find x inside anotherFavFunction, so looks for variable inside
favFunction, outputs 667
}
var yetAnotherFavFunction = function(){
console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for variable
inside favFunction and does not find it, so looks for variable in global scope, finds it and
outputs 24
}
anotherFavFunction();
yetAnotherFavFunction();
}
favFunction();
16) 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.
Example:
var x = 2;
var y = "2";
(x == y)
(x === y)
// Returns true since the value of both x and y is the same.
// Returns false since the typeof x is "number" and typeof y is "string".
17) Explain Implicit Type Coercion in JS.
Implicit type coercion in JavaScript is the automatic conversion of value from one
data type to another. It takes place when the operands of an expression are of different data
types.
1) String coercion
String coercion takes place while using the ‘+ ‘ operator. When a number is added to a string,
the number type is always converted to the string type.
Example 1:
var x = 3;
var y = "3";
x+y
// Returns "33" x = 3 turns to string
Example 2:
var x = 24;
var y = "Hello";
x+y
// Returns "24Hello"; x=24 turns to string
Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘
operator when used to add two strings, outputs the concatenated string:
var name = "Vivek";
var surname = " Bisht";
name + surname
// Returns "Vivek Bisht"
Note - Type coercion also takes place when using the ‘ - ‘ operator, but the difference
while using ‘ - ‘ operator is that, a string is converted to a number and then subtraction
takes place.
var x = 3;
Var y = "3";
x-y
// this gets converted to number
//Returns 0 since the variable y (string type) is converted to a number type
2) Boolean Coercion
Boolean coercion takes place when using logical operators, ternary operators, if statements,
and loop checks. Truthy- True and Falsy -False.
All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.
3) Logical Operators
Logical operators in JavaScript, unlike operators in other programming languages, do not
return true or false. They always return one of the operands.
OR ( | | ) operator - If the first value is truthy, then the first value is returned. Otherwise,
always the second value gets returned.
AND ( && ) operator - If both the values are truthy, always the second value is returned. If
the first value is falsy then the first value is returned or if the second value is falsy then the
second value is returned.
Example:
var x = 220;
var y = "Hello";
var z = undefined;
x||y
// Returns 220 since the first value is truthy
x | | z // Returns 220 since the first value is truthy
x && y
// Returns "Hello" since both the values are truthy
y && z // Returns undefined since the second value is falsy
if( x && y ){
console.log("Code runs" ); // This block runs because x && y returns "Hello" (Truthy)
}
if( x || z ){
console.log("Code runs"); // This block runs because x || y returns 220(Truthy)
}
4) Equality Coercion
Equality coercion takes place when using ‘ == ‘ operator but not this “===”. As we
have stated before
The ‘ == ‘ operator compares values and not types.
The ‘==’ operator, converts both the operands to the same type and then compares
them.
Example:
var a = 12;
var b = "12";
a == b
// Returns true because both 'a' and 'b' are converted to the same type and then
compared. Hence the operands are equal.
a === b
// Returns false because coercion does not take place and the operands are of
different types. Hence, they are not equal.
18) What does the ! operator do?
The ! operator converts the operand to a boolean and negates it. It’ll convert falsy
values true and truthy value to false .
console.log(!0);
console.log(!"");
console.log(!false);
console.log(!NaN);
console.log(!undefined);
console.log(!null);
then they all log true .
If ! is placed before a truthy expression then it’ll log false
19) What does the !! operator do?
!! is the double NOT operator, which coerces the operand to a boolean value.
It’ll convert truthy values to true and falsy values to false .
For example, if we have:
console.log(!!0);
console.log(!!'');
console.log(!!false);
console.log(!!NaN);
console.log(!!undefined);
console.log(!!null);
They’ll log false .
Applying !! before any truthy expression should return true .
Functions and loops
20) What are Functions?
Reusable block of code designed to perform specific tasks. In JS, it can be defined
in many ways: Functions declarations, function expressions, arrow functions and
anonymous functions.
Function declaration:
function greet(name){
console.log("Hello" + " " + name);
}
greet("Sabin");
Function expression: function assigned to a variable or used within an expression.
Can be anonymous ( no name) or named. Like here function sayHello(name)
samething.
const greet = function(name){
return "Hello" + " " + name;
}
console.log(greet("Sabin"));
Arrow function:
const greet = (name) => { return "Hello" + " " + name;};
console.log(greet("Sabin"));
Anonymous function: no name function, often used as function expressions and are
commonly found in places like callback functions and higher-order-functions.
Anonymous functions can’t be function declarations since all function declarations
require a name.
: Using an Anonymous Function as an Argument to a Higher-Order Function:
const numbers = [1, 2, 3, 4];
// Passing an anonymous function to `map`
const doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled);
// Output: [2, 4, 6, 8]
: Immediately Invoked Function Expression (IIFE) with an Anonymous Function:
(function() {
console.log("This is an anonymous function executed immediately!");
})(); // Output: This is an anonymous function executed immediately!
21) Function declaration vs Function Expression
Basic: declaration requires name and Expression requires no name or can be
named.
Declaration is hoisted meaning they can be called before they are defined or appear in
the code. Expressions are not hoisted meaning they need to defined before use.
// Function Declaration - can be called before it's defined
console.log(add(3, 4)); // Output: 7
function add(a, b) {
return a + b;
}
// Function Expression - cannot be called before it's defined
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(3, 4));
// Output: 12
22 ) What does a for loop structure include?
The for-loop structure includes initialization (let i = 0), condition (i < 5), and
increment (i++). This loop type is particularly useful for scenarios with a fixed
iteration count.
23) Closures ??
Allows inner function to access the outer function variables even after the
outer function has executed. Useful for creating private variables and
maintaining state. Basis for JS lexical scoping.
function createCounter() {
let count = 0; // Private variable
return function() {
count++;
return count;
};
}
const counter1 = createCounter();
console.log(counter1()); // Output: 1
console.log(counter1()); // Output: 2
const counter2 = createCounter();
console.log(counter2()); // Output: 1
24) What are IIFE ( Immediately Invoked Function Expression)?
Functions that are executed immediately after they are defined. Useful for creating
isolated scopes and avoiding polluting the global namespace. Used in module
patterns, avoid global variable conflicts and maintain modular code.
(function(){
let message = "Hello World";
console.log ( message );
})();
Or with a parameter,
(function(name){
console.log("Hello" +" " + name);
})("Sabin");
25) Do—while vs While loop?
while loops check the condition before executing the loop body, while do...while
loops execute the loop body at least once before checking the condition.
26) How do you break out of loop?
The break statement allows you to exit a loop before it has completed all iterations.
Used in for, while loops and switch statements.
for (let i=1; i<=6; i++){
if (i==3)
break;
console.log(i); // outputs 1 2
}
27) How do you skip iterations in a loop?
The continue statement skips the current loop iteration and proceeds to the next
one.
for (let i=1; i<=6; i++){
if (i==3)
continue;
console.log(i); // outputs 1 2 4 5 6
}
28) What are recursive function?
Function that calls itself to solve a problem in smaller parts. They usually have a
base case to avoid infinite calls. A Popular example is factorial.
function fact(n){
if(n<=1)
{
return 1; // base case
}
return n* fact(n-1);
}
console.log(fact(4));
Regular Expressions
1) What is a regular Expression and its syntax?
sequence of characters that forms a search pattern. Can be a single
character or more complicated pattern.
Perform all types of text search and text replace operations.
Syntax: /pattern/modifiers or flags; example: /w3schools/i .
2) What are the usage of Regex in JS?
Searching within text (using .test() or .exec()).
Replacing parts of strings (using .replace()).
Validating input formats (like emails, phone numbers, etc.).
3) How do you create Regex in JS?
2 ways:
Literal notation: /pattern/modifiers. const regex1 = /abc/;
Using constructor func: const regex2= new RegExp(‘abc’);
4) Explain common regex modifiers in JS?
g (global): Searches the entire string instead of stopping after the first match.
i (ignore case): makes regex case-insensitive.
m (multiline): Allows ^ and $ to match the start and end of each line.
d : perform start and end matching (new).
const regex= /hello/gi; // search through entire string and case-insensitive
const str="Hello, Hello";
console.log(str.match(regex)); //outputs array of found items [ 'Hello', 'Hello'
]
5) How do you validate an email using regex?
const emailRegex = /[a-z0-9]+@[a-z]+\.[a-z]{2,3}/ ;
console.log(emailRegex.test("sabinkhadka32@gmail.com")); // true
console.log(emailRegex.test("match@124")); // false
6) Difference between test() and match()?
test(): Returns a boolean indicating whether the pattern exists in the string.
match(): Returns an array of matches or null if no matches are found.
7) How do you replace all occurrences of a pattern in a string?
Use replace() method with the global flag(g) in the regex.
8) How do you extract numbers from a string using regex?
Use the regex pattern \d+ (one or more digits) with the match() method and the g flag to find
all numbers in a string.
9) How do you validate if a string only contains digits?
Use the regex ^\d+$. ^ asserts the start of the string, \d+ matches one or more digits, and $
asserts the end of the string.
10) How would you find words that start with a specific letter in a string?
Use \b (word boundary) and the desired letter, for example /\bA\w*/g for words starting with
"A".
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )