You are on page 1of 8

Tutorial

JAVASCRIPT
TRICKY
INTERVIEW
QUESTIONS
PART - 2
Swipe >>

1. String Mutability :

let text = 'abcde'


text[1] = 'z'
console.log(text)

What is the output of it?

azcde? zbcde?
swipe to find out...

@nikhilvallore
Swipe >>

Output: abcde

why?
String is immutable, which means that once a
string is created and assigned a value, it cannot
be changed. However, you can create a new
string with a different value and assign it to the
same variable.

ex:
let text = 'abcde'
text = 'abcdz'
console.log(text)
//output: abcdz

@nikhilvallore
Swipe >>

2. Accidental Global Variable :

function foo() {
let a = b = 0;
a++;
return a;
}
foo();

console.log(b);
console.log(a);

What is the output of it?

@nikhilvallore
Swipe >>

Output:
0
ReferenceError: a is not defined

when you write "let a = b = 0",


it looks like both "a" and "b" are declared using
"let". However, this is not the case.

In reality, "b" is declared as a global variable


using the keyword "var". This means that it is
not limited to a block of code, but can be
accessed and used anywhere in your program.

@nikhilvallore
Swipe >>

3. This :
const obj = {
value: "val1",
prop: {
value: "val2",
print: function(){console.log(this.value)},
},
print: function(){ console.log(this.value) },
print2: () => console.log(this.value)
}

obj.print()
obj.prop.print()
obj.print2()

What is the output of it?

@nikhilvallore
Swipe >>

Output: val1 val2 undefined

obj.print(), the function logs the value of this.value of


object 'obj' which is "val1"

When you run the code obj.prop.print(), the function


logs the value of this.value of object 'obj.prop' which
now points to the inner object in which value is "val2"

When you run the code obj.print2(), the arrow


function logs the value of this.value which is
"undefined", This is because arrow functions do not
have their own "this" and therefore the value of this
inside an arrow function refers to the window global
object

@nikhilvallore
Found it interesting?
Follow ME on Linked
for more such content

Until Next Time Keep Learning


and Keep Sharing!!

Nikhil Vallore

You might also like