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

What's hot

Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0Buu Nguyen
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Hashing PPT
Hashing PPTHashing PPT
Hashing PPT
Saurabh Kumar
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
Dr. Jasmine Beulah Gnanadurai
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
Parallel Programming for Multi- Core and Cluster Systems - Performance Analysis
Parallel Programming for Multi- Core and Cluster Systems - Performance AnalysisParallel Programming for Multi- Core and Cluster Systems - Performance Analysis
Parallel Programming for Multi- Core and Cluster Systems - Performance Analysis
Shah Zaib
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
Directed Acyclic Graph Representation of basic blocks
Directed Acyclic Graph Representation of basic blocksDirected Acyclic Graph Representation of basic blocks
Directed Acyclic Graph Representation of basic blocks
Mohammad Vaseem Akaram
 
What is Constructors and Destructors in C++ (Explained with Example along wi...
What is Constructors and Destructors in  C++ (Explained with Example along wi...What is Constructors and Destructors in  C++ (Explained with Example along wi...
What is Constructors and Destructors in C++ (Explained with Example along wi...
Pallavi Seth
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based Testing
Shai Geva
 
Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
Knoldus Inc.
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
KrutikaWankhade1
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
Tasif Tanzim
 

What's hot (20)

Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0Dynamic Binding in C# 4.0
Dynamic Binding in C# 4.0
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Hashing PPT
Hashing PPTHashing PPT
Hashing PPT
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Parallel Programming for Multi- Core and Cluster Systems - Performance Analysis
Parallel Programming for Multi- Core and Cluster Systems - Performance AnalysisParallel Programming for Multi- Core and Cluster Systems - Performance Analysis
Parallel Programming for Multi- Core and Cluster Systems - Performance Analysis
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Directed Acyclic Graph Representation of basic blocks
Directed Acyclic Graph Representation of basic blocksDirected Acyclic Graph Representation of basic blocks
Directed Acyclic Graph Representation of basic blocks
 
What is Constructors and Destructors in C++ (Explained with Example along wi...
What is Constructors and Destructors in  C++ (Explained with Example along wi...What is Constructors and Destructors in  C++ (Explained with Example along wi...
What is Constructors and Destructors in C++ (Explained with Example along wi...
 
Property-Based Testing
Property-Based TestingProperty-Based Testing
Property-Based Testing
 
Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Indexing Data Structure
Indexing Data StructureIndexing Data Structure
Indexing Data Structure
 
Exception handling
Exception handlingException handling
Exception handling
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
 

Similar to JavaScript Interview Questions 2023

JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
Laurence Svekis ✔
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara Pehlivanian
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
Ivano Malavolta
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
Ankit Agarwal
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
Janssen Harvey Insigne
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
Doeun KOCH
 

Similar to JavaScript Interview Questions 2023 (20)

JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptxJavaScript Multithread or Single Thread.pptx
JavaScript Multithread or Single Thread.pptx
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 

More from Laurence Svekis ✔

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
Laurence Svekis ✔
 
Code examples javascript ebook
Code examples javascript ebookCode examples javascript ebook
Code examples javascript ebook
Laurence Svekis ✔
 
Javascript projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
Laurence Svekis ✔
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source code
Laurence Svekis ✔
 
Chrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideChrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers Guide
Laurence Svekis ✔
 
Brackets code editor guide
Brackets code editor guideBrackets code editor guide
Brackets code editor guide
Laurence Svekis ✔
 
Web hosting get start online
Web hosting get start onlineWeb hosting get start online
Web hosting get start online
Laurence Svekis ✔
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
Web hosting Free Hosting
Web hosting Free HostingWeb hosting Free Hosting
Web hosting Free Hosting
Laurence Svekis ✔
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources brackets
Laurence Svekis ✔
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
Laurence Svekis ✔
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive Code
Laurence Svekis ✔
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
Laurence Svekis ✔
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
Laurence Svekis ✔
 

More from Laurence Svekis ✔ (20)

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
 
Code examples javascript ebook
Code examples javascript ebookCode examples javascript ebook
Code examples javascript ebook
 
Javascript projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source code
 
Chrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideChrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers Guide
 
Brackets code editor guide
Brackets code editor guideBrackets code editor guide
Brackets code editor guide
 
Web hosting get start online
Web hosting get start onlineWeb hosting get start online
Web hosting get start online
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Web hosting Free Hosting
Web hosting Free HostingWeb hosting Free Hosting
Web hosting Free Hosting
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources brackets
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game project
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive Code
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
 

Recently uploaded

Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 

Recently uploaded (20)

Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 

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/