Notes of some important JavaScript concepts

Figooooo
2 min readOct 11, 2021

--

I spent the whole last week revising JavaScript interview questions and found out some basic rules. I’m going to summarize some types of questions that get asked a lot.

Passing values by reference vs by value

So what would be the output of the following code?

var strA = "hi there";
var strB = strA;
strB="bye there!";
console.log (strA)

and

var objA = {prop1: 42};
var objB = objA;
objB.prop1 = 90;
console.log(objA)

What about this one?

var objA = {prop1: 42};
var objB = objA;
objB = {};
console.log(objA)

The first answer will be 'hi there' because we're dealing with strings here. Strings are passed by value, that is, copied. The second answer will be 90 because this is an object. Objects are passed by reference, that is, objA and objB point to the same object in memory. The third one is kind of tricky, the output will be {prop1: 42}. When we assign objA to objB, the objB variable will point to the same object as the objB variable. However, when we reassign objB to an empty object, we simply change where objB variable references to. This doesn't affect where objA variable references to.

Hoisting

So what would be the output of the following code?

console.log(employeeId);

This will cause an error of ReferenceError because employeeId is not defined.

console.log(employeeId);
var employeeId = '19000';

This is very typical for hoisting questions because thanks to hoisting the variable employeeId will be “leveled up” to the beginning of its scope but the assignment will not. So the output will be undefined .

Same output with these codes:

//#1
var employeeId = '1234abe';
(function(){
console.log(employeeId);
var employeeId = '122345';
})();
//#2
var employeeId = '1234abe';
(function() {
console.log(employeeId);
var employeeId = '122345';
(function() {
var employeeId = 'abc1234';
}());
}());
//#3
(function() {
console.log(typeof displayFunc);
var displayFunc = function(){
console.log("Hi I am inside displayFunc");
}
}());

This is it for today’s note!

--

--

Figooooo
Figooooo

No responses yet