Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

JavaScript-Interview-Coding-Examples-V6

The document provides a comprehensive overview of various JavaScript concepts including variable declarations (let, var, const), arrow functions, equality operators (== vs ===), string manipulation, closures, the 'this' keyword, synchronous vs asynchronous code, promises, callback functions, and checking for arrays. Each concept is explained with examples to illustrate their usage and differences. The content is aimed at helping readers understand fundamental JavaScript programming principles.

Uploaded by

oliverwekesa337
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript-Interview-Coding-Examples-V6

The document provides a comprehensive overview of various JavaScript concepts including variable declarations (let, var, const), arrow functions, equality operators (== vs ===), string manipulation, closures, the 'this' keyword, synchronous vs asynchronous code, promises, callback functions, and checking for arrays. Each concept is explained with examples to illustrate their usage and differences. The content is aimed at helping readers understand fundamental JavaScript programming principles.

Uploaded by

oliverwekesa337
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

JavaScript Code Examples

What is the difference between let, var, and const in JavaScript? 2

How would you declare and use an arrow function in JavaScript? 3

What is the difference between == and === in JavaScript? 4

How would you reverse a string in JavaScript? 7

What is a closure in JavaScript? 7

What is the this keyword in JavaScript? 9

What is the difference between synchronous and asynchronous code in


JavaScript? 10

What is a promise in JavaScript? 13

What is a callback function in JavaScript? 14

How would you check if a variable is an array in JavaScript? 15

Laurence Svekis https://basescripts.com/


1
What is the difference between let, var, and
const in JavaScript?
let, var, and const are all ways to declare variables in JavaScript,
but they have some important differences.

var is the old way of declaring variables in JavaScript, and it has


some quirks that can lead to hard-to-debug issues. One of the
main issues is that var has function scope, not block scope, which
means that variables declared with var are accessible anywhere
within the function, even outside of blocks. For example:

function example() {
if (true) {
var message = "Hello, world!";
}
console.log(message); // "Hello, world!"
}

example();
In this example, the variable message is declared
inside an if block, but it's still accessible outside
of the block because of var's function scope.

Laurence Svekis https://basescripts.com/


2
let and const were introduced in ES6 (also known as ECMAScript
2015) to solve some of the issues with var. let and const have
block scope, which means that variables declared with them are
only accessible within the block in which they're declared. The
difference between let and const is that let allows you to reassign
the variable to a new value, while const does not. For example:

let x = 1;
x = 2; // OK
console.log(x); // 2

const y = 1;
y = 2; // Error: Assignment to constant variable.

How would you declare and use an arrow


function in JavaScript?
An arrow function is a shorthand way of declaring a function in
JavaScript. Arrow functions are often used when you need to pass
a function as a parameter to another function. Here's an
example:

// Declaring an arrow function


const add = (x, y) => {

Laurence Svekis https://basescripts.com/


3
return x + y;
};

// Using an arrow function


const result = add(1, 2);
console.log(result); // 3

In this example, we're declaring an arrow function called add that


takes two parameters, x and y, and returns their sum. We're then
calling the add function with 1 and 2, and logging the result to
the console.

Note that the curly braces and return keyword are optional if the
function only contains one expression. Here's a shorter version of
the same function:

const add = (x, y) => x + y;

What is the difference between == and ===


in JavaScript?
== and === are both used to compare values in JavaScript, but
they have some important differences.

Laurence Svekis https://basescripts.com/


4
== is the loose equality operator, which means that it performs
type coercion when comparing values. This means that it will
convert one or both operands to a common type before making
the comparison. For example:

console.log(1 == "1"); // true

In this example, 1 and "1" are not the same type (one is a
number and one is a string), but == performs type coercion and
converts the string to a number before making the comparison.

=== is the strict equality operator, which means that it does not
perform type coercion when comparing values. This means that it
will only return true if the operands are of the same type and
have the same value. For example:

console.log(1 === "1"); // false


== and === are both used for comparison in JavaScript, but
they behave differently. == is the loose equality operator, while
=== is the strict equality operator.

When using ==, JavaScript will try to convert the operands to the
same type before doing the comparison. This can lead to some
unexpected results. For example:

Laurence Svekis https://basescripts.com/


5
console.log(1 == "1"); // true
console.log(0 == ""); // true
console.log(null == undefined); // true

In these examples, JavaScript is converting the operands to the


same type before doing the comparison. In the first example, it
converts the string "1" to the number 1. In the second example,
it converts the empty string to the number 0. In the third
example, it considers null and undefined to be equal.

On the other hand, when using ===, JavaScript does not convert
the operands to the same type. It simply checks if they are the
same type and have the same value. For example:

console.log(1 === "1"); // false


console.log(0 === ""); // false
console.log(null === undefined); // false

In these examples, JavaScript is not converting the operands to


the same type before doing the comparison. In the first example,
it considers the number 1 and the string "1" to be different types.
In the second example, it considers the number 0 and the empty
string to be different types. In the third example, it considers null
and undefined to be different types.

Laurence Svekis https://basescripts.com/


6
In general, it is recommended to use === for equality
comparisons in JavaScript, as it avoids the potential for
unexpected behavior caused by type coercion.

How would you reverse a string in JavaScript?


There are many ways to reverse a string in JavaScript, but one
common way is to convert the string to an array, reverse the
array, and then join the array back into a string. Here's an
example:

const str = "hello";


const reversed = str.split("").reverse().join("");
console.log(reversed); // "olleh"

In this example, we're using the split method to convert the


string to an array of characters, the reverse method to reverse
the order of the characters in the array, and the join method to
join the characters back into a string.

What is a closure in JavaScript?


A closure is a feature of JavaScript that allows a function to
access variables from an outer (enclosing) function, even after

Laurence Svekis https://basescripts.com/


7
the outer function has returned. Closures are created when a
function is defined inside another function, and the inner function
refers to a variable in the outer function. Here's an example:

function outer() {
const name = "Alice";

function inner() {
console.log(name);
}

return inner;
}

const innerFunc = outer();


innerFunc(); // "Alice"

In this example, outer is a function that defines a variable called


name and a function called inner. inner refers to name in its body,
which creates a closure. When we call outer and assign the result
to innerFunc, inner is returned and can be called later. When we
call innerFunc, it logs the value of name, even though outer has
already returned.

Laurence Svekis https://basescripts.com/


8
What is the this keyword in JavaScript?
The this keyword in JavaScript refers to the object that the
current function or method is a property of. The value of this
depends on how the function or method is called. Here are a few
examples:

const person = {
name: "Alice",
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};

person.greet(); // "Hello, my name is Alice"

In this example, this refers to the person object, because the


greet method is a property of the person object.

function greet() {
console.log(`Hello, my name is ${this.name}`);
}

Laurence Svekis https://basescripts.com/


9
const person1 = { name: "Alice" };
const person2 = { name: "Bob" };

greet.call(person1); // "Hello, my name is Alice"


greet.call(person2); // "Hello, my name is Bob"

In this example, we're defining a standalone function called greet


that uses this to refer to a name property. We're then using the
call method to call greet with different objects as the this value.
When we call greet.call(person1), this refers to person1, and
when we call greet.call(person2), this refers to person2.

What is the difference between synchronous


and asynchronous code in JavaScript?
Synchronous code in JavaScript is executed in a sequential order,
where each statement is executed one after the other.
Asynchronous code, on the other hand, allows multiple things to
happen at the same time, and does not block the execution of
other code while it is waiting for something to happen.

In synchronous code, each line of code is executed in order, and


the program waits for each line to finish executing before moving
on to the next one. This means that if a particular line of code

Laurence Svekis https://basescripts.com/


10
takes a long time to execute (e.g., a network request or a large
calculation), the entire program will be blocked and unresponsive
until that line finishes executing.

In contrast, in asynchronous code, the program can move on to


the next line of code without waiting for the current line to finish
executing. Instead, the current line of code is executed in the
background, and the program can continue to respond to user
input and other events while the code is running.

Asynchronous code is typically used for operations that may take


a long time to complete, such as network requests or file I/O. In
JavaScript, asynchronous code is usually implemented using
callbacks, promises, or async/await.

Here's an example of synchronous code:

console.log("Line 1");
console.log("Line 2");
console.log("Line 3");

In this example, each line of code is executed in order, and the


program will not move on to the next line until the previous line
has finished executing.

Laurence Svekis https://basescripts.com/


11
Here's an example of asynchronous code using callbacks:

console.log("Line 1");
setTimeout(() => {
console.log("Line 2");
}, 1000);
console.log("Line 3");

In this example, the setTimeout function is used to execute a


callback function after a delay of one second. The program will
not wait for the callback function to finish executing before
moving on to the next line of code. Instead, the program will
immediately move on to the next line of code (console.log("Line
3")), while the callback function is running in the background.
After one second, the callback function will be executed, and
"Line 2" will be logged to the console.

Note that while the program is waiting for the setTimeout callback
to execute, it is still responsive to user input and other events.
This is because the callback is running in the background, and the
program can continue to execute other lines of code while it waits
for the callback to finish.

Laurence Svekis https://basescripts.com/


12
Overall, asynchronous code can help improve the responsiveness
and performance of JavaScript programs, especially when dealing
with long-running operations.

What is a promise in JavaScript?


A promise in JavaScript is an object that represents the eventual
completion (or failure) of an asynchronous operation and its
resulting value. Promises provide a way to handle asynchronous
operations in a more structured and less error-prone way.
Promises have three states: pending, fulfilled, and rejected.
Here's an example:

const promise = new Promise((resolve, reject) => {


setTimeout(() => {
resolve("done");
}, 1000);
});

promise.then((result) => {
console.log(result);
}).catch((error) => {
console.error(error);
});

Laurence Svekis https://basescripts.com/


13
In this example, we're creating a new Promise that resolves after
1 second with the value "done". We're then calling the then
method on the promise to handle the success case, and the catch
method to handle any errors.

What is a callback function in JavaScript?


A callback function in JavaScript is a function that is passed as an
argument to another function and is called when the first function
has completed its task. Callback functions are often used with
asynchronous code to handle the completion of an operation.
Here's an example:

function doSomething(callback) {
setTimeout(() => {
callback("done");
}, 1000);
}

doSomething((result) => {
console.log(result);
});

Laurence Svekis https://basescripts.com/


14
In this example, we're defining a function called doSomething
that takes a callback function as an argument. We're then using
setTimeout to simulate an asynchronous operation that takes 1
second to complete. When the operation is complete, we're
calling the callback function with the value "done".

How would you check if a variable is an array


in JavaScript?
In JavaScript, you can check if a variable is an array by using the
Array.isArray method. Here's an example:

const arr = [1, 2, 3];

console.log(Array.isArray(arr)); // true
console.log(Array.isArray("hello")); // false

In this example, we're using the Array.isArray method to check if


the arr variable is an array. The method returns true if the
variable is an array, and false otherwise.

Laurence Svekis https://basescripts.com/


15

You might also like