SlideShare a Scribd company logo
JavaScript interview questions with answers:
What is closure in JavaScript and how does it work?
Answer: Closure is a feature in JavaScript where a function has
access to its outer scope even after the outer function has
returned. It is created when a function is defined inside another
function, and the inner function retains access to the variables in
the outer function's scope.
Closure Example 1:
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const add5 = outerFunction(5);
console.log(add5(3)); // 8
Closure Example 2:
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const add5 = outerFunction(5);
console.log(add5(3)); // 8
Closure Example A counter function:
function createCounter() {
let count = 0;
return function() {
Laurence Svekis https://basescripts.com/
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Closure Example A function returning another function:
function greeting(message) {
return function(name) {
console.log(`${message} ${name}!`);
};
}
const sayHi = greeting('Hi');
const sayHello = greeting('Hello');
sayHi('John'); // Hi John!
sayHello('Jane'); // Hello Jane!
Closure Example A timer:
function setTimer(duration) {
let timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
console.log(`${duration} seconds have passed.`);
}, duration * 1000);
};
}
const timer1 = setTimer(3);
const timer2 = setTimer(5);
Laurence Svekis https://basescripts.com/
timer1();
timer2();
Closure Example A module:
function createModule(name) {
let module = {};
return function(data) {
module[name] = data;
return module;
};
}
const createPerson = createModule('person');
const createAddress = createModule('address');
const person = createPerson({ name: 'John', age: 32 });
const address = createAddress({ street: '123 Main St',
city: 'San Francisco' });
console.log(person); // { person: { name: 'John', age:
32 } }
console.log(address); // { address: { street: '123 Main
St', city: 'San Francisco' } }
Closure Example A function to maintain state:
function createToggler() {
let state = false;
return function() {
state = !state;
return state;
};
}
const toggler = createToggler();
console.log(toggler()); // true
Laurence Svekis https://basescripts.com/
console.log(toggler()); // false
Can you explain hoisting in JavaScript?
Answer: Hoisting is a behavior in JavaScript where variable and
function declarations are moved to the top of their scope,
regardless of where they are declared in the code. This means
that variables and functions can be called before they are
declared, but the value of variables will be undefined until they
are assigned a value.
Hoisting Example 1:
console.log(x); // undefined
var x = 5;
What is the difference between == and === in JavaScript?
Answer: The double equals (==) performs type coercion, which
means it converts the data type of one operand to match the data
type of the other operand before making a comparison. The triple
equals (===) does not perform type coercion and only returns
true if both operands have the same data type and value.
== vs === Example 1:
console.log(5 == "5"); // true
console.log(5 === "5"); // false
console.log(null == undefined); // true
console.log(null === undefined); // false
How do you declare a variable in JavaScript?
Answer: Variables in JavaScript can be declared using the "var",
"let" or "const" keywords. The "var" keyword is used to declare a
variable with function scope, while "let" and "const" are used to
declare variables with block scope.
Variable declaration 1:
Laurence Svekis https://basescripts.com/
var x = 5;
let y = 10;
const z = 15;
Variable declaration 2:
let x = 5;
x = 10;
console.log(x); // 10
const z = [1, 2, 3];
z.push(4);
console.log(z); // [1, 2, 3, 4]
Can you explain the event loop in JavaScript?
Answer: The event loop in JavaScript is a mechanism that allows
the execution of code to be scheduled in a non-blocking way. The
event loop continuously checks the message queue for new
messages, and if there is a message, it executes the
corresponding callback function. This allows the JavaScript engine
to handle multiple events and execute code in a responsive and
efficient manner.
Event loop 1:
console.log('Start');
setTimeout(function() {
console.log('Timeout');
}, 0);
console.log('End');
Event loop 2:
console.log('Start');
setTimeout(function() {
console.log('Timeout');
Laurence Svekis https://basescripts.com/
}, 2000);
console.log('End');
Event loop Using setTimeout with a queue:
console.log('Start');
setTimeout(() => console.log('Timeout 1'), 0);
setTimeout(() => console.log('Timeout 2'), 0);
console.log('End');
This will log:
Start
End
Timeout 1
Timeout 2
Event loop Handling multiple callbacks with setInterval:
let count = 0;
const intervalId = setInterval(() => {
console.log(`Interval: ${count++}`);
if (count === 5) {
clearInterval(intervalId);
}
}, 1000);
This will log:
Interval: 0
Interval: 1
Interval: 2
Interval: 3
Interval: 4
Laurence Svekis https://basescripts.com/
Event loop Chaining promises:
const delay = (duration) => new Promise(resolve =>
setTimeout(resolve, duration));
console.log('Start');
delay(1000)
.then(() => console.log('Promise 1'))
.then(() => delay(1000))
.then(() => console.log('Promise 2'));
console.log('End');
This will log:
Start
End
Promise 1
Promise 2
Event loop Processing multiple tasks with setImmediate:
console.log('Start');
setImmediate(() => console.log('Immediate 1'));
setImmediate(() => console.log('Immediate 2'));
console.log('End');
This will log:
Start
End
Immediate 1
Immediate 2
Laurence Svekis https://basescripts.com/
What is the difference between null and undefined in
JavaScript?
Answer: Undefined means a variable has been declared but has
not been assigned a value, while null is a value assigned to a
variable that represents no value or no object.
null vs undefined example:
let x;
console.log(x); // undefined
x = null;
console.log(x); // null
What is a JavaScript callback function?
Answer: A callback function is a function passed as an argument
to another function, which is then executed at a later time.
Callback functions are commonly used in JavaScript to handle
asynchronous operations, such as making a network request or
setTimeout().
Callback function example 1:
function sayHello(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
sayHello('John', function() {
console.log('Callback executed');
});
Callback function example 2:
function calculate(a, b, callback) {
const result = a + b;
callback(result);
Laurence Svekis https://basescripts.com/
}
calculate(5, 3, function(result) {
console.log(result); // 8
});
A simple callback with setTimeout:
const log = (message) => console.log(message);
setTimeout(() => log('Timeout'), 1000);
A callback with Array.forEach:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => console.log(number));
A callback with Array.map:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => number *
2);
console.log(doubledNumbers);
A callback with Array.filter:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => number % 2
=== 0);
console.log(evenNumbers);
A callback with Array.reduce:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, number) => total + number,
0);
console.log(sum);
Laurence Svekis https://basescripts.com/
A callback with Array.sort:
const names = ['John', 'Jane', 'Jim', 'Jake'];
const sortedNames = names.sort((a, b) => a.localeCompare(b));
console.log(sortedNames);
A callback with Object.keys:
const person = { name: 'John', age: 30, city: 'London' };
Object.keys(person).forEach((key) => console.log(`${key}:
${person[key]}`));
A callback with Promise.then:
const delay = (duration) => new Promise(resolve =>
setTimeout(resolve, duration));
console.log('Start');
delay(1000)
.then(() => console.log('Promise'));
console.log('End');
A callback with EventTarget.addEventListener:
const button = document.getElementById('button');
button.addEventListener('click', () => console.log('Clicked'));
A callback with XMLHttpRequest.onload:
const request = new XMLHttpRequest();
request.open('GET',
'https://jsonplaceholder.typicode.com/posts');
request.onload = () => {
if (request.status === 200) {
console.log(JSON.parse(request.responseText));
} else {
console.error(request.statusText);
}
Laurence Svekis https://basescripts.com/
};
request.send();
How do you declare a function in JavaScript?
Answer: Functions in JavaScript can be declared using the
"function" keyword followed by the function name, its parameters
in parentheses, and its code block in curly braces. Functions can
also be declared using function expressions and arrow functions.
Function declaration 1:
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
const hello = name => console.log(`Hello, ${name}!`);
Function declaration 2:
function sayHi(name) {
console.log(`Hi, ${name}!`);
}
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
const hello = name => console.log(`Hello, ${name}!`);
sayHi('John'); // Hi, John!
greet('John'); // Hello, John!
hello('John'); // Hello, John!
Laurence Svekis https://basescripts.com/
What is the difference between let and var in JavaScript?
Answer: The "let" and "var" keywords are used to declare
variables in JavaScript, but they have different scoping rules.
Variables declared with "var" have function scope, which means
they can be accessed within the entire function, while "let"
variables have block scope, which means they can only be
accessed within the block they are declared in.
let vs var example 1:
var x = 5;
if (true) {
var x = 10;
}
console.log(x); // 10
let y = 5;
if (true) {
let y = 10;
}
console.log(y); // 5
let vs var example 2:
for (var i = 0; i < 5; i++) {
console.log(i);
}
console.log(i); // 5
for (let j = 0; j < 5; j++) {
console.log(j);
}
console.log(j); // ReferenceError: j is not defined
Can you explain the "this" keyword in JavaScript?
Laurence Svekis https://basescripts.com/
Answer: The "this" keyword in JavaScript refers to the object that
the function is a method of. Its value depends on how the
function is called, and it can be set using bind, call or apply
methods. If a function is not a method of an object, "this" refers
to the global object (window in the browser).
"this" keyword example 1:
const person = {
name: 'John',
sayHello: function() {
console.log(`Hello, I'm ${this.name}`);
}
};
person.sayHello(); // Hello, I'm John
const greet = person.sayHello;
greet(); // Hello, I'm undefined
"this" keyword example 2:
const car = {
brand: 'Tesla',
drive: function() {
console.log(`Driving a ${this.brand} car`);
}
};
car.drive(); // Driving a Tesla car
const driveCar = car.drive;
driveCar(); // Driving a undefined car
examples of the this keyword in JavaScript:
this in an object method:
const person = {
name: 'John',
sayHello: function () {
Laurence Svekis https://basescripts.com/
console.log(`Hello, my name is ${this.name}`);
}
};
person.sayHello();
this in a class method:
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
const john = new Person('John');
john.sayHello();
this in an arrow function:
const person = {
name: 'John',
sayHello: () => {
console.log(`Hello, my name is ${this.name}`);
}
};
person.sayHello();
this in a function passed as a callback:
const person = {
name: 'John'
Laurence Svekis https://basescripts.com/
};
const logName = function () {
console.log(`Hello, my name is ${this.name}`);
};
setTimeout(logName.bind(person), 1000);
this in an event handler:
const button = document.getElementById('button');
button.addEventListener('click', function () {
console.log(`Button with ID "${this.id}" was clicked`);
});
this in an object constructor:
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name);
this in a closure:
const person = {
name: 'John',
sayHello: function () {
const that = this;
setTimeout(function () {
console.log(`Hello, my name is ${that.name}`);
}, 1000);
}
};
person.sayHello();
Laurence Svekis https://basescripts.com/
this in a prototype method:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hello, my name is ${this.name}`);
};
const john = new Person('John');
john.sayHello();
this in a dynamic method:
const person = {
name: 'John'
};
const method = 'sayHello';
person[method] = function () {
console.log(`Hello, my name is ${this.name}`);
};
person.sayHello();
this in a nested function:
const person = {
name: 'John',
sayHello: function () {
const nested = function () {
console.log(`Hello, my name is ${this.name}`);
};
nested.call(person);
}
};
person
Laurence Svekis https://basescripts.com/
JavaScript interview questions with code
examples:
What is hoisting in JavaScript and how does it work?
console.log(hoistedVariable); // undefined
var hoistedVariable = 'This is a hoisted variable';
console.log(notHoisted); // ReferenceError: notHoisted is not
defined
let notHoisted = 'This is not a hoisted variable';
What is closure in JavaScript and how is it useful?
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const add5 = outerFunction(5);
console.log(add5(3)); // 8
What is the difference between == and === in JavaScript?
console.log(1 == '1'); // true
console.log(1 === '1'); // false
What is the difference between null and undefined in
JavaScript?
let variable1;
console.log(variable1); // undefined
let variable2 = null;
console.log(variable2); // null
Laurence Svekis https://basescripts.com/
How does asynchronous code work in JavaScript?
console.log('Before setTimeout');
setTimeout(function () {
console.log('Inside setTimeout');
}, 1000);
console.log('After setTimeout');
What is the difference between let and var in JavaScript?
if (true) {
var variable1 = 'This is a var variable';
let variable2 = 'This is a let variable';
}
console.log(variable1); // This is a var variable
console.log(variable2); // ReferenceError: variable2 is not defined
How do you declare a variable in JavaScript?
var variable1 = 'This is a var variable';
let variable2 = 'This is a let variable';
const variable3 = 'This is a const variable';
What is the difference between forEach and map in
JavaScript?
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (number) {
console.log(number);
});
const doubledNumbers = numbers.map(function (number) {
return number * 2;
});
console.log(doubledNumbers);
Laurence Svekis https://basescripts.com/
What is the difference between function and arrow
function in JavaScript?
function regularFunction(x, y) {
return x + y;
}
const arrowFunction = (x, y) => x + y;
console.log(regularFunction(1, 2)); // 3
console.log(arrowFunction(1, 2)); // 3
How do you declare an object in JavaScript?
const objectLiteral = {
key1: 'value1',
key2: 'value2'
};
const objectConstructor = new Object();
objectConstructor.key1 = 'value1';
objectConstructor.key2 = 'value2';
Laurence Svekis https://basescripts.com/

More Related Content

PPTX
JS Event Loop
PDF
JavaScript Interview Questions Part - 1.pdf
PPTX
Loops in java script
PDF
Javascript
PDF
javascript objects
ODP
Datatype in JavaScript
PPTX
Js: master prototypes
PPTX
Javascript functions
JS Event Loop
JavaScript Interview Questions Part - 1.pdf
Loops in java script
Javascript
javascript objects
Datatype in JavaScript
Js: master prototypes
Javascript functions

What's hot (20)

PPT
Introduction to Javascript
PDF
Basics of JavaScript
PPTX
JavaScript Promises
PPTX
JavaScript Basics
PPT
JavaScript - An Introduction
PPT
Java script final presentation
PDF
TypeScript
PPT
JavaScript Object Notation (JSON)
PPTX
JavaScript
PDF
JavaScript - Chapter 6 - Basic Functions
PPTX
Java awt (abstract window toolkit)
PPT
Declarative programming language
PPTX
Tokens in C++
PDF
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
PPTX
Brief History of JavaScript
PDF
Asynchronous JavaScript Programming
PDF
Java Course 8: I/O, Files and Streams
PPTX
Mutable and immutable classes
PDF
Object-oriented Programming-with C#
Introduction to Javascript
Basics of JavaScript
JavaScript Promises
JavaScript Basics
JavaScript - An Introduction
Java script final presentation
TypeScript
JavaScript Object Notation (JSON)
JavaScript
JavaScript - Chapter 6 - Basic Functions
Java awt (abstract window toolkit)
Declarative programming language
Tokens in C++
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Brief History of JavaScript
Asynchronous JavaScript Programming
Java Course 8: I/O, Files and Streams
Mutable and immutable classes
Object-oriented Programming-with C#
Ad

Similar to JavaScript Interview Questions 2023 (20)

PPTX
Javascripts hidden treasures BY - https://geekyants.com/
PDF
[2015/2016] JavaScript
PDF
JavaScript
PDF
JavaScript for real men
PPT
Web development basics (Part-4)
PPTX
Scope and closures
PPTX
Awesomeness of JavaScript…almost
PDF
Important JavaScript Concepts Every Developer Must Know
PDF
All you need to know about JavaScript Functions
PPTX
Unit-3.pptx node js ppt documents semester-5
PPTX
JavaScript Interview Questions And Answers | JavaScript Interview Preparation...
PDF
Web 4 | Core JavaScript
PDF
JavaScript Lessons 2023 V2
PPTX
Object oriented java script
PDF
02 Introduction to Javascript
PPTX
Closure
PDF
JavaScript Interview Questions PDF By ScholarHat
PDF
1669958779195.pdf
PDF
Introduction to Object Oriented Javascript
PDF
JavaScript Basics and Best Practices - CC FE & UX
Javascripts hidden treasures BY - https://geekyants.com/
[2015/2016] JavaScript
JavaScript
JavaScript for real men
Web development basics (Part-4)
Scope and closures
Awesomeness of JavaScript…almost
Important JavaScript Concepts Every Developer Must Know
All you need to know about JavaScript Functions
Unit-3.pptx node js ppt documents semester-5
JavaScript Interview Questions And Answers | JavaScript Interview Preparation...
Web 4 | Core JavaScript
JavaScript Lessons 2023 V2
Object oriented java script
02 Introduction to Javascript
Closure
JavaScript Interview Questions PDF By ScholarHat
1669958779195.pdf
Introduction to Object Oriented Javascript
JavaScript Basics and Best Practices - CC FE & UX
Ad

More from Laurence Svekis ✔ (20)

PDF
Quiz JavaScript Objects Learn more about JavaScript
PDF
JavaScript Lessons 2023
PDF
Top 10 Linkedin Tips Guide 2023
PDF
Code examples javascript ebook
PDF
Javascript projects Course
PDF
10 java script projects full source code
PDF
Chrome DevTools Introduction 2020 Web Developers Guide
PDF
Brackets code editor guide
PDF
Web hosting get start online
PDF
JavaScript guide 2020 Learn JavaScript
PDF
Web hosting Free Hosting
PDF
Web development resources brackets
PPTX
Google Apps Script for Beginners- Amazing Things with Code
PPTX
Local SQLite Database with Node for beginners
PDF
Introduction to Node js for beginners + game project
PPTX
JavaScript DOM - Dynamic interactive Code
PPTX
JavaScript Advanced - Useful methods to power up your code
PPTX
Monster JavaScript Course - 50+ projects and applications
PPTX
JavaScript Objects and OOP Programming with JavaScript
PPTX
JavaScript Core fundamentals - Learn JavaScript Here
Quiz JavaScript Objects Learn more about JavaScript
JavaScript Lessons 2023
Top 10 Linkedin Tips Guide 2023
Code examples javascript ebook
Javascript projects Course
10 java script projects full source code
Chrome DevTools Introduction 2020 Web Developers Guide
Brackets code editor guide
Web hosting get start online
JavaScript guide 2020 Learn JavaScript
Web hosting Free Hosting
Web development resources brackets
Google Apps Script for Beginners- Amazing Things with Code
Local SQLite Database with Node for beginners
Introduction to Node js for beginners + game project
JavaScript DOM - Dynamic interactive Code
JavaScript Advanced - Useful methods to power up your code
Monster JavaScript Course - 50+ projects and applications
JavaScript Objects and OOP Programming with JavaScript
JavaScript Core fundamentals - Learn JavaScript Here

Recently uploaded (20)

PPTX
Presentation on HIE in infants and its manifestations
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
01-Introduction-to-Information-Management.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Computing-Curriculum for Schools in Ghana
PDF
Classroom Observation Tools for Teachers
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Pharma ospi slides which help in ospi learning
PDF
Anesthesia in Laparoscopic Surgery in India
Presentation on HIE in infants and its manifestations
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
01-Introduction-to-Information-Management.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
Supply Chain Operations Speaking Notes -ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
VCE English Exam - Section C Student Revision Booklet
Computing-Curriculum for Schools in Ghana
Classroom Observation Tools for Teachers
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
O7-L3 Supply Chain Operations - ICLT Program
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Pharma ospi slides which help in ospi learning
Anesthesia in Laparoscopic Surgery in India

JavaScript Interview Questions 2023

  • 1. JavaScript interview questions with answers: What is closure in JavaScript and how does it work? Answer: Closure is a feature in JavaScript where a function has access to its outer scope even after the outer function has returned. It is created when a function is defined inside another function, and the inner function retains access to the variables in the outer function's scope. Closure Example 1: function outerFunction(x) { return function innerFunction(y) { return x + y; }; } const add5 = outerFunction(5); console.log(add5(3)); // 8 Closure Example 2: function outerFunction(x) { return function innerFunction(y) { return x + y; }; } const add5 = outerFunction(5); console.log(add5(3)); // 8 Closure Example A counter function: function createCounter() { let count = 0; return function() { Laurence Svekis https://basescripts.com/
  • 2. return ++count; }; } const counter = createCounter(); console.log(counter()); // 1 console.log(counter()); // 2 Closure Example A function returning another function: function greeting(message) { return function(name) { console.log(`${message} ${name}!`); }; } const sayHi = greeting('Hi'); const sayHello = greeting('Hello'); sayHi('John'); // Hi John! sayHello('Jane'); // Hello Jane! Closure Example A timer: function setTimer(duration) { let timeoutId; return function() { clearTimeout(timeoutId); timeoutId = setTimeout(function() { console.log(`${duration} seconds have passed.`); }, duration * 1000); }; } const timer1 = setTimer(3); const timer2 = setTimer(5); Laurence Svekis https://basescripts.com/
  • 3. timer1(); timer2(); Closure Example A module: function createModule(name) { let module = {}; return function(data) { module[name] = data; return module; }; } const createPerson = createModule('person'); const createAddress = createModule('address'); const person = createPerson({ name: 'John', age: 32 }); const address = createAddress({ street: '123 Main St', city: 'San Francisco' }); console.log(person); // { person: { name: 'John', age: 32 } } console.log(address); // { address: { street: '123 Main St', city: 'San Francisco' } } Closure Example A function to maintain state: function createToggler() { let state = false; return function() { state = !state; return state; }; } const toggler = createToggler(); console.log(toggler()); // true Laurence Svekis https://basescripts.com/
  • 4. console.log(toggler()); // false Can you explain hoisting in JavaScript? Answer: Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope, regardless of where they are declared in the code. This means that variables and functions can be called before they are declared, but the value of variables will be undefined until they are assigned a value. Hoisting Example 1: console.log(x); // undefined var x = 5; What is the difference between == and === in JavaScript? Answer: The double equals (==) performs type coercion, which means it converts the data type of one operand to match the data type of the other operand before making a comparison. The triple equals (===) does not perform type coercion and only returns true if both operands have the same data type and value. == vs === Example 1: console.log(5 == "5"); // true console.log(5 === "5"); // false console.log(null == undefined); // true console.log(null === undefined); // false How do you declare a variable in JavaScript? Answer: Variables in JavaScript can be declared using the "var", "let" or "const" keywords. The "var" keyword is used to declare a variable with function scope, while "let" and "const" are used to declare variables with block scope. Variable declaration 1: Laurence Svekis https://basescripts.com/
  • 5. var x = 5; let y = 10; const z = 15; Variable declaration 2: let x = 5; x = 10; console.log(x); // 10 const z = [1, 2, 3]; z.push(4); console.log(z); // [1, 2, 3, 4] Can you explain the event loop in JavaScript? Answer: The event loop in JavaScript is a mechanism that allows the execution of code to be scheduled in a non-blocking way. The event loop continuously checks the message queue for new messages, and if there is a message, it executes the corresponding callback function. This allows the JavaScript engine to handle multiple events and execute code in a responsive and efficient manner. Event loop 1: console.log('Start'); setTimeout(function() { console.log('Timeout'); }, 0); console.log('End'); Event loop 2: console.log('Start'); setTimeout(function() { console.log('Timeout'); Laurence Svekis https://basescripts.com/
  • 6. }, 2000); console.log('End'); Event loop Using setTimeout with a queue: console.log('Start'); setTimeout(() => console.log('Timeout 1'), 0); setTimeout(() => console.log('Timeout 2'), 0); console.log('End'); This will log: Start End Timeout 1 Timeout 2 Event loop Handling multiple callbacks with setInterval: let count = 0; const intervalId = setInterval(() => { console.log(`Interval: ${count++}`); if (count === 5) { clearInterval(intervalId); } }, 1000); This will log: Interval: 0 Interval: 1 Interval: 2 Interval: 3 Interval: 4 Laurence Svekis https://basescripts.com/
  • 7. Event loop Chaining promises: const delay = (duration) => new Promise(resolve => setTimeout(resolve, duration)); console.log('Start'); delay(1000) .then(() => console.log('Promise 1')) .then(() => delay(1000)) .then(() => console.log('Promise 2')); console.log('End'); This will log: Start End Promise 1 Promise 2 Event loop Processing multiple tasks with setImmediate: console.log('Start'); setImmediate(() => console.log('Immediate 1')); setImmediate(() => console.log('Immediate 2')); console.log('End'); This will log: Start End Immediate 1 Immediate 2 Laurence Svekis https://basescripts.com/
  • 8. What is the difference between null and undefined in JavaScript? Answer: Undefined means a variable has been declared but has not been assigned a value, while null is a value assigned to a variable that represents no value or no object. null vs undefined example: let x; console.log(x); // undefined x = null; console.log(x); // null What is a JavaScript callback function? Answer: A callback function is a function passed as an argument to another function, which is then executed at a later time. Callback functions are commonly used in JavaScript to handle asynchronous operations, such as making a network request or setTimeout(). Callback function example 1: function sayHello(name, callback) { console.log(`Hello, ${name}!`); callback(); } sayHello('John', function() { console.log('Callback executed'); }); Callback function example 2: function calculate(a, b, callback) { const result = a + b; callback(result); Laurence Svekis https://basescripts.com/
  • 9. } calculate(5, 3, function(result) { console.log(result); // 8 }); A simple callback with setTimeout: const log = (message) => console.log(message); setTimeout(() => log('Timeout'), 1000); A callback with Array.forEach: const numbers = [1, 2, 3, 4, 5]; numbers.forEach((number) => console.log(number)); A callback with Array.map: const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map((number) => number * 2); console.log(doubledNumbers); A callback with Array.filter: const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter((number) => number % 2 === 0); console.log(evenNumbers); A callback with Array.reduce: const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((total, number) => total + number, 0); console.log(sum); Laurence Svekis https://basescripts.com/
  • 10. A callback with Array.sort: const names = ['John', 'Jane', 'Jim', 'Jake']; const sortedNames = names.sort((a, b) => a.localeCompare(b)); console.log(sortedNames); A callback with Object.keys: const person = { name: 'John', age: 30, city: 'London' }; Object.keys(person).forEach((key) => console.log(`${key}: ${person[key]}`)); A callback with Promise.then: const delay = (duration) => new Promise(resolve => setTimeout(resolve, duration)); console.log('Start'); delay(1000) .then(() => console.log('Promise')); console.log('End'); A callback with EventTarget.addEventListener: const button = document.getElementById('button'); button.addEventListener('click', () => console.log('Clicked')); A callback with XMLHttpRequest.onload: const request = new XMLHttpRequest(); request.open('GET', 'https://jsonplaceholder.typicode.com/posts'); request.onload = () => { if (request.status === 200) { console.log(JSON.parse(request.responseText)); } else { console.error(request.statusText); } Laurence Svekis https://basescripts.com/
  • 11. }; request.send(); How do you declare a function in JavaScript? Answer: Functions in JavaScript can be declared using the "function" keyword followed by the function name, its parameters in parentheses, and its code block in curly braces. Functions can also be declared using function expressions and arrow functions. Function declaration 1: function sayHello(name) { console.log(`Hello, ${name}!`); } const greet = function(name) { console.log(`Hello, ${name}!`); }; const hello = name => console.log(`Hello, ${name}!`); Function declaration 2: function sayHi(name) { console.log(`Hi, ${name}!`); } const greet = function(name) { console.log(`Hello, ${name}!`); }; const hello = name => console.log(`Hello, ${name}!`); sayHi('John'); // Hi, John! greet('John'); // Hello, John! hello('John'); // Hello, John! Laurence Svekis https://basescripts.com/
  • 12. What is the difference between let and var in JavaScript? Answer: The "let" and "var" keywords are used to declare variables in JavaScript, but they have different scoping rules. Variables declared with "var" have function scope, which means they can be accessed within the entire function, while "let" variables have block scope, which means they can only be accessed within the block they are declared in. let vs var example 1: var x = 5; if (true) { var x = 10; } console.log(x); // 10 let y = 5; if (true) { let y = 10; } console.log(y); // 5 let vs var example 2: for (var i = 0; i < 5; i++) { console.log(i); } console.log(i); // 5 for (let j = 0; j < 5; j++) { console.log(j); } console.log(j); // ReferenceError: j is not defined Can you explain the "this" keyword in JavaScript? Laurence Svekis https://basescripts.com/
  • 13. Answer: The "this" keyword in JavaScript refers to the object that the function is a method of. Its value depends on how the function is called, and it can be set using bind, call or apply methods. If a function is not a method of an object, "this" refers to the global object (window in the browser). "this" keyword example 1: const person = { name: 'John', sayHello: function() { console.log(`Hello, I'm ${this.name}`); } }; person.sayHello(); // Hello, I'm John const greet = person.sayHello; greet(); // Hello, I'm undefined "this" keyword example 2: const car = { brand: 'Tesla', drive: function() { console.log(`Driving a ${this.brand} car`); } }; car.drive(); // Driving a Tesla car const driveCar = car.drive; driveCar(); // Driving a undefined car examples of the this keyword in JavaScript: this in an object method: const person = { name: 'John', sayHello: function () { Laurence Svekis https://basescripts.com/
  • 14. console.log(`Hello, my name is ${this.name}`); } }; person.sayHello(); this in a class method: class Person { constructor(name) { this.name = name; } sayHello() { console.log(`Hello, my name is ${this.name}`); } } const john = new Person('John'); john.sayHello(); this in an arrow function: const person = { name: 'John', sayHello: () => { console.log(`Hello, my name is ${this.name}`); } }; person.sayHello(); this in a function passed as a callback: const person = { name: 'John' Laurence Svekis https://basescripts.com/
  • 15. }; const logName = function () { console.log(`Hello, my name is ${this.name}`); }; setTimeout(logName.bind(person), 1000); this in an event handler: const button = document.getElementById('button'); button.addEventListener('click', function () { console.log(`Button with ID "${this.id}" was clicked`); }); this in an object constructor: function Person(name) { this.name = name; } const john = new Person('John'); console.log(john.name); this in a closure: const person = { name: 'John', sayHello: function () { const that = this; setTimeout(function () { console.log(`Hello, my name is ${that.name}`); }, 1000); } }; person.sayHello(); Laurence Svekis https://basescripts.com/
  • 16. this in a prototype method: function Person(name) { this.name = name; } Person.prototype.sayHello = function () { console.log(`Hello, my name is ${this.name}`); }; const john = new Person('John'); john.sayHello(); this in a dynamic method: const person = { name: 'John' }; const method = 'sayHello'; person[method] = function () { console.log(`Hello, my name is ${this.name}`); }; person.sayHello(); this in a nested function: const person = { name: 'John', sayHello: function () { const nested = function () { console.log(`Hello, my name is ${this.name}`); }; nested.call(person); } }; person Laurence Svekis https://basescripts.com/
  • 17. JavaScript interview questions with code examples: What is hoisting in JavaScript and how does it work? console.log(hoistedVariable); // undefined var hoistedVariable = 'This is a hoisted variable'; console.log(notHoisted); // ReferenceError: notHoisted is not defined let notHoisted = 'This is not a hoisted variable'; What is closure in JavaScript and how is it useful? function outerFunction(x) { return function innerFunction(y) { return x + y; }; } const add5 = outerFunction(5); console.log(add5(3)); // 8 What is the difference between == and === in JavaScript? console.log(1 == '1'); // true console.log(1 === '1'); // false What is the difference between null and undefined in JavaScript? let variable1; console.log(variable1); // undefined let variable2 = null; console.log(variable2); // null Laurence Svekis https://basescripts.com/
  • 18. How does asynchronous code work in JavaScript? console.log('Before setTimeout'); setTimeout(function () { console.log('Inside setTimeout'); }, 1000); console.log('After setTimeout'); What is the difference between let and var in JavaScript? if (true) { var variable1 = 'This is a var variable'; let variable2 = 'This is a let variable'; } console.log(variable1); // This is a var variable console.log(variable2); // ReferenceError: variable2 is not defined How do you declare a variable in JavaScript? var variable1 = 'This is a var variable'; let variable2 = 'This is a let variable'; const variable3 = 'This is a const variable'; What is the difference between forEach and map in JavaScript? const numbers = [1, 2, 3, 4, 5]; numbers.forEach(function (number) { console.log(number); }); const doubledNumbers = numbers.map(function (number) { return number * 2; }); console.log(doubledNumbers); Laurence Svekis https://basescripts.com/
  • 19. What is the difference between function and arrow function in JavaScript? function regularFunction(x, y) { return x + y; } const arrowFunction = (x, y) => x + y; console.log(regularFunction(1, 2)); // 3 console.log(arrowFunction(1, 2)); // 3 How do you declare an object in JavaScript? const objectLiteral = { key1: 'value1', key2: 'value2' }; const objectConstructor = new Object(); objectConstructor.key1 = 'value1'; objectConstructor.key2 = 'value2'; Laurence Svekis https://basescripts.com/